Spaces:
Sleeping
Sleeping
Upload 29 files
Browse files- app/services/banner_service.py +254 -255
- app/services/banner_unsplash_desktop_service.py +130 -0
- app/services/banner_unsplash_ipad_service.py +130 -0
- app/services/banner_unsplash_mobile_service.py +130 -0
- app/services/bestnetwork_service.py +5 -3
- app/services/byop_service.py +5 -3
- app/services/byop_unsplash_desktop_service.py +75 -0
- app/services/byop_unsplash_ipad_service.py +75 -0
- app/services/byop_unsplash_mobile_service.py +75 -0
- app/services/custom_banner_desktop_service.py +9 -8
- app/services/custom_banner_ipad_service.py +6 -12
- app/services/custom_banner_mobile_service.py +8 -7
- app/services/custom_byop_service.py +3 -4
- app/services/custom_network_service.py +4 -5
- app/services/logo_service.py +3 -4
- app/services/network_unsplash_desktop_service.py +75 -0
- app/services/network_unsplash_ipad_service.py +75 -0
- app/services/network_unsplash_mobile_service.py +75 -0
- app/services/single_icon_logo_service.py +1 -1
- app/services/single_text_logo_service.py +1 -1
- app/services/text_logo_service.py +8 -8
- app/services/upload_image_service.py +43 -0
app/services/banner_service.py
CHANGED
|
@@ -1,256 +1,255 @@
|
|
| 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
|
| 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 |
-
final_img = ImageEnhance.
|
| 99 |
-
final_img = ImageEnhance.
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
final_img = ImageEnhance.
|
| 103 |
-
final_img = ImageEnhance.
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
final_img = ImageEnhance.
|
| 107 |
-
final_img = ImageEnhance.
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
buffer.
|
| 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 |
-
overage_ratio
|
| 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 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
width, height
|
| 229 |
-
|
| 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 |
-
logger.info("All banner variations generated successfully.")
|
| 256 |
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 showing the essence of the brand whose details are:
|
| 19 |
+
|
| 20 |
+
{brand_details}
|
| 21 |
+
|
| 22 |
+
Exclude the use of color {primary_color} in the palette. Do not Include any text, typographic or Alphanumeric Elements.''',
|
| 23 |
+
'ipad': f'''Generate a realistic image which includes real people and
|
| 24 |
+
The image must show essence of the brand:
|
| 25 |
+
|
| 26 |
+
{brand_details}
|
| 27 |
+
|
| 28 |
+
Exclude the use of color {primary_color} in the palette. Do not Include any text, typographic or Alphanumeric Elements.''',
|
| 29 |
+
'mobile': f'''Generate a realistic image which includes real people and
|
| 30 |
+
The image must show essence of the brand:
|
| 31 |
+
|
| 32 |
+
{brand_details}
|
| 33 |
+
|
| 34 |
+
Exclude the use of color {primary_color} in the palette. Do not Include any text, typographic or Alphanumeric Elements.''',
|
| 35 |
+
}
|
| 36 |
+
return device_prompts
|
| 37 |
+
|
| 38 |
+
def process_image(image_data: bytes, target_width: int, target_height: int) -> bytes:
|
| 39 |
+
"""
|
| 40 |
+
Resize, sharpen, enhance and compress an image to fit a given resolution and file size.
|
| 41 |
+
Optimized for 1024x1024 source images with better quality preservation.
|
| 42 |
+
"""
|
| 43 |
+
img = Image.open(BytesIO(image_data)).convert('RGB')
|
| 44 |
+
original_width, original_height = img.size
|
| 45 |
+
|
| 46 |
+
# Calculate aspect ratios
|
| 47 |
+
original_ratio = original_width / original_height
|
| 48 |
+
target_ratio = target_width / target_height
|
| 49 |
+
|
| 50 |
+
# Step 1: Smart upscaling based on target size relative to source
|
| 51 |
+
# Only upscale if target is significantly larger than source
|
| 52 |
+
upscale_threshold = max(target_width, target_height) / max(original_width, original_height)
|
| 53 |
+
|
| 54 |
+
if upscale_threshold > 1.2: # Only upscale if target is 20% larger
|
| 55 |
+
scale_factor = min(3, math.ceil(upscale_threshold)) # Cap at 3x to avoid excessive processing
|
| 56 |
+
intermediate_width = original_width * scale_factor
|
| 57 |
+
intermediate_height = original_height * scale_factor
|
| 58 |
+
|
| 59 |
+
# Use bicubic for upscaling (better than Lanczos for enlargement)
|
| 60 |
+
working_img = img.resize((intermediate_width, intermediate_height), Image.BICUBIC)
|
| 61 |
+
|
| 62 |
+
# Apply subtle unsharp mask for upscaled images
|
| 63 |
+
working_img = working_img.filter(ImageFilter.UnsharpMask(radius=1.0, percent=120, threshold=3))
|
| 64 |
+
else:
|
| 65 |
+
working_img = img
|
| 66 |
+
|
| 67 |
+
# Step 2: Smart cropping/fitting based on aspect ratio difference
|
| 68 |
+
if abs(original_ratio - target_ratio) > 0.1: # Significant aspect ratio difference
|
| 69 |
+
# Crop to target ratio first, then resize (preserves more detail)
|
| 70 |
+
if original_ratio > target_ratio:
|
| 71 |
+
# Source is wider - crop width
|
| 72 |
+
new_width = int(working_img.height * target_ratio)
|
| 73 |
+
left = (working_img.width - new_width) // 2
|
| 74 |
+
working_img = working_img.crop((left, 0, left + new_width, working_img.height))
|
| 75 |
+
else:
|
| 76 |
+
# Source is taller - crop height
|
| 77 |
+
new_height = int(working_img.width / target_ratio)
|
| 78 |
+
top = (working_img.height - new_height) // 2
|
| 79 |
+
working_img = working_img.crop((0, top, working_img.width, top + new_height))
|
| 80 |
+
|
| 81 |
+
# Step 3: Final resize to target dimensions
|
| 82 |
+
# Use Lanczos for downscaling, bicubic for upscaling
|
| 83 |
+
current_size = max(working_img.size)
|
| 84 |
+
target_size = max(target_width, target_height)
|
| 85 |
+
|
| 86 |
+
if current_size > target_size:
|
| 87 |
+
# Downscaling - use Lanczos
|
| 88 |
+
final_img = working_img.resize((target_width, target_height), Image.LANCZOS)
|
| 89 |
+
else:
|
| 90 |
+
# Upscaling - use bicubic
|
| 91 |
+
final_img = working_img.resize((target_width, target_height), Image.BICUBIC)
|
| 92 |
+
|
| 93 |
+
# Step 4: Conditional enhancement based on target size
|
| 94 |
+
target_pixels = target_width * target_height
|
| 95 |
+
|
| 96 |
+
if target_pixels < 500000: # Small images need more sharpening
|
| 97 |
+
final_img = ImageEnhance.Sharpness(final_img).enhance(1.4)
|
| 98 |
+
final_img = ImageEnhance.Contrast(final_img).enhance(1.15)
|
| 99 |
+
final_img = ImageEnhance.Color(final_img).enhance(1.05)
|
| 100 |
+
elif target_pixels < 1500000: # Medium images
|
| 101 |
+
final_img = ImageEnhance.Sharpness(final_img).enhance(1.2)
|
| 102 |
+
final_img = ImageEnhance.Contrast(final_img).enhance(1.1)
|
| 103 |
+
final_img = ImageEnhance.Color(final_img).enhance(1.08)
|
| 104 |
+
else: # Large images need subtle enhancement
|
| 105 |
+
final_img = ImageEnhance.Sharpness(final_img).enhance(1.1)
|
| 106 |
+
final_img = ImageEnhance.Contrast(final_img).enhance(1.05)
|
| 107 |
+
final_img = ImageEnhance.Color(final_img).enhance(1.03)
|
| 108 |
+
|
| 109 |
+
# Step 5: Intelligent compression with quality optimization
|
| 110 |
+
buffer = BytesIO()
|
| 111 |
+
|
| 112 |
+
# Start with higher quality for better results
|
| 113 |
+
quality = 98
|
| 114 |
+
max_file_size = 500 * 1024 # 500KB
|
| 115 |
+
|
| 116 |
+
while quality >= 75: # Don't go below 75 quality
|
| 117 |
+
buffer.seek(0)
|
| 118 |
+
buffer.truncate()
|
| 119 |
+
|
| 120 |
+
# Adjust subsampling based on quality
|
| 121 |
+
if quality >= 95:
|
| 122 |
+
subsampling = 0 # No chroma subsampling for highest quality
|
| 123 |
+
elif quality >= 85:
|
| 124 |
+
subsampling = 1 # Moderate chroma subsampling
|
| 125 |
+
else:
|
| 126 |
+
subsampling = 2 # Standard chroma subsampling
|
| 127 |
+
|
| 128 |
+
final_img.save(
|
| 129 |
+
buffer,
|
| 130 |
+
format='JPEG',
|
| 131 |
+
quality=quality,
|
| 132 |
+
optimize=True,
|
| 133 |
+
progressive=True,
|
| 134 |
+
subsampling=subsampling
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
current_size = buffer.tell()
|
| 138 |
+
|
| 139 |
+
# If we're within size limit or quality is getting too low, stop
|
| 140 |
+
if current_size <= max_file_size or quality <= 80:
|
| 141 |
+
break
|
| 142 |
+
|
| 143 |
+
# Adjust quality reduction based on how far over we are
|
| 144 |
+
overage_ratio = current_size / max_file_size
|
| 145 |
+
if overage_ratio > 2:
|
| 146 |
+
quality -= 8 # Aggressive reduction if way over
|
| 147 |
+
elif overage_ratio > 1.5:
|
| 148 |
+
quality -= 5 # Moderate reduction
|
| 149 |
+
else:
|
| 150 |
+
quality -= 3 # Conservative reduction
|
| 151 |
+
|
| 152 |
+
return buffer.getvalue()
|
| 153 |
+
|
| 154 |
+
def process_images_for_devices(image_data: bytes) -> Dict[str, bytes]:
|
| 155 |
+
"""
|
| 156 |
+
Resize banner image for desktop, tablet (iPad), and mobile.
|
| 157 |
+
"""
|
| 158 |
+
return {
|
| 159 |
+
'desktop': process_image(image_data, 1440, 500),
|
| 160 |
+
'ipad': process_image(image_data, 768, 500),
|
| 161 |
+
'mobile': process_image(image_data, 375, 500)
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
def generate_banner(brand_details: str, primary_color: str) -> Dict:
|
| 165 |
+
"""
|
| 166 |
+
Generate multiple variations of banner images for each device using Gemini and upload to Reach platform.
|
| 167 |
+
Returns a dictionary with URLs for different device sizes and prompt variations.
|
| 168 |
+
"""
|
| 169 |
+
api_key = settings.GEMINI_API_KEY
|
| 170 |
+
client = genai.Client(api_key=api_key)
|
| 171 |
+
brand_name = generate_brand_name()
|
| 172 |
+
|
| 173 |
+
# Create two identical prompt sets for two variations
|
| 174 |
+
base_prompt = get_banner_prompts(brand_details, primary_color)
|
| 175 |
+
all_prompt_sets = [base_prompt, base_prompt] # Two variations, same prompts
|
| 176 |
+
|
| 177 |
+
all_banner_results = []
|
| 178 |
+
|
| 179 |
+
logger.info(f"Starting banner generation with ID: {brand_name}")
|
| 180 |
+
|
| 181 |
+
# Device-specific dimensions
|
| 182 |
+
device_dimensions = {
|
| 183 |
+
'desktop': (1440, 500),
|
| 184 |
+
'ipad': (768, 500),
|
| 185 |
+
'mobile': (375, 500)
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
# File types used for uploading
|
| 189 |
+
device_file_types = {
|
| 190 |
+
"desktop": "DESKTOP_IMAGE",
|
| 191 |
+
"ipad": "IPAD_IMAGE",
|
| 192 |
+
"mobile": "WEB_IMAGE"
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
# Loop through all variations of prompt sets
|
| 196 |
+
for variation_index, device_prompts in enumerate(all_prompt_sets, start=1):
|
| 197 |
+
banner_results = {}
|
| 198 |
+
|
| 199 |
+
for device, prompt in device_prompts.items():
|
| 200 |
+
logger.info(f"Generating variation {variation_index}, device: {device}")
|
| 201 |
+
|
| 202 |
+
try:
|
| 203 |
+
response = client.models.generate_content(
|
| 204 |
+
model="gemini-2.0-flash-preview-image-generation",
|
| 205 |
+
contents=prompt,
|
| 206 |
+
config=types.GenerateContentConfig(response_modalities=['TEXT', 'IMAGE'])
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
for part in response.candidates[0].content.parts:
|
| 210 |
+
if part.inline_data is not None:
|
| 211 |
+
image_data = part.inline_data.data
|
| 212 |
+
mime_type = part.inline_data.mime_type
|
| 213 |
+
|
| 214 |
+
# Determine image format
|
| 215 |
+
if "jpeg" in mime_type or "jpg" in mime_type:
|
| 216 |
+
image_format = "jpeg"
|
| 217 |
+
elif "png" in mime_type:
|
| 218 |
+
image_format = "png"
|
| 219 |
+
elif "webp" in mime_type:
|
| 220 |
+
image_format = "webp"
|
| 221 |
+
else:
|
| 222 |
+
image_format = "jpeg"
|
| 223 |
+
|
| 224 |
+
logger.info(f"Processing image for {device} in variation {variation_index}")
|
| 225 |
+
|
| 226 |
+
# Resize and enhance
|
| 227 |
+
width, height = device_dimensions[device]
|
| 228 |
+
processed_image = process_image(image_data, width, height)
|
| 229 |
+
# Upload to Reach with UUID-based name
|
| 230 |
+
result = upload_to_reach(
|
| 231 |
+
processed_image,
|
| 232 |
+
f"banner_{brand_name}_{device}_v{variation_index}",
|
| 233 |
+
image_format,
|
| 234 |
+
1,
|
| 235 |
+
device_file_types[device]
|
| 236 |
+
)
|
| 237 |
+
banner_results[device] = result['url']
|
| 238 |
+
|
| 239 |
+
logger.info(f"{device} banner uploaded successfully for variation {variation_index}")
|
| 240 |
+
|
| 241 |
+
except Exception as error:
|
| 242 |
+
logger.error(f"Error processing {device} banner in variation {variation_index}: {str(error)}")
|
| 243 |
+
raise
|
| 244 |
+
|
| 245 |
+
if not banner_results:
|
| 246 |
+
logger.error(f"No images were generated for variation {variation_index}")
|
| 247 |
+
raise Exception(f"No images were generated for variation {variation_index}")
|
| 248 |
+
|
| 249 |
+
all_banner_results.append({
|
| 250 |
+
"variation": variation_index,
|
| 251 |
+
"banners": banner_results
|
| 252 |
+
})
|
| 253 |
+
|
| 254 |
+
logger.info("All banner variations generated successfully.")
|
|
|
|
| 255 |
return {"variations": all_banner_results}
|
app/services/banner_unsplash_desktop_service.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import random
|
| 3 |
+
from typing import Dict
|
| 4 |
+
import requests
|
| 5 |
+
from app.config.settings import settings
|
| 6 |
+
from app.utils.reach_upload import upload_to_reach
|
| 7 |
+
from PIL import Image, ImageEnhance, ImageOps, ImageFilter
|
| 8 |
+
from io import BytesIO
|
| 9 |
+
import math
|
| 10 |
+
|
| 11 |
+
logger = logging.getLogger(__name__)
|
| 12 |
+
logger.setLevel(logging.INFO)
|
| 13 |
+
|
| 14 |
+
UNSPLASH_API_KEY = settings.UNSPLASH_API_KEY
|
| 15 |
+
UNSPLASH_BASE_URL = "https://api.unsplash.com"
|
| 16 |
+
|
| 17 |
+
def process_image(image_data: bytes, target_width: int, target_height: int) -> bytes:
|
| 18 |
+
img = Image.open(BytesIO(image_data)).convert('RGB')
|
| 19 |
+
original_width, original_height = img.size
|
| 20 |
+
original_ratio = original_width / original_height
|
| 21 |
+
target_ratio = target_width / target_height
|
| 22 |
+
upscale_threshold = max(target_width, target_height) / max(original_width, original_height)
|
| 23 |
+
if upscale_threshold > 1.2:
|
| 24 |
+
scale_factor = min(3, math.ceil(upscale_threshold))
|
| 25 |
+
intermediate_width = original_width * scale_factor
|
| 26 |
+
intermediate_height = original_height * scale_factor
|
| 27 |
+
working_img = img.resize((intermediate_width, intermediate_height), Image.BICUBIC)
|
| 28 |
+
working_img = working_img.filter(ImageFilter.UnsharpMask(radius=1.0, percent=120, threshold=3))
|
| 29 |
+
else:
|
| 30 |
+
working_img = img
|
| 31 |
+
if abs(original_ratio - target_ratio) > 0.1:
|
| 32 |
+
if original_ratio > target_ratio:
|
| 33 |
+
new_width = int(working_img.height * target_ratio)
|
| 34 |
+
left = (working_img.width - new_width) // 2
|
| 35 |
+
working_img = working_img.crop((left, 0, left + new_width, working_img.height))
|
| 36 |
+
else:
|
| 37 |
+
new_height = int(working_img.width / target_ratio)
|
| 38 |
+
top = (working_img.height - new_height) // 2
|
| 39 |
+
working_img = working_img.crop((0, top, working_img.width, top + new_height))
|
| 40 |
+
current_size = max(working_img.size)
|
| 41 |
+
target_size = max(target_width, target_height)
|
| 42 |
+
if current_size > target_size:
|
| 43 |
+
final_img = working_img.resize((target_width, target_height), Image.LANCZOS)
|
| 44 |
+
else:
|
| 45 |
+
final_img = working_img.resize((target_width, target_height), Image.BICUBIC)
|
| 46 |
+
target_pixels = target_width * target_height
|
| 47 |
+
if target_pixels < 500000:
|
| 48 |
+
final_img = ImageEnhance.Sharpness(final_img).enhance(1.4)
|
| 49 |
+
final_img = ImageEnhance.Contrast(final_img).enhance(1.15)
|
| 50 |
+
final_img = ImageEnhance.Color(final_img).enhance(1.05)
|
| 51 |
+
elif target_pixels < 1500000:
|
| 52 |
+
final_img = ImageEnhance.Sharpness(final_img).enhance(1.2)
|
| 53 |
+
final_img = ImageEnhance.Contrast(final_img).enhance(1.1)
|
| 54 |
+
final_img = ImageEnhance.Color(final_img).enhance(1.08)
|
| 55 |
+
else:
|
| 56 |
+
final_img = ImageEnhance.Sharpness(final_img).enhance(1.1)
|
| 57 |
+
final_img = ImageEnhance.Contrast(final_img).enhance(1.05)
|
| 58 |
+
final_img = ImageEnhance.Color(final_img).enhance(1.03)
|
| 59 |
+
buffer = BytesIO()
|
| 60 |
+
quality = 98
|
| 61 |
+
max_file_size = 500 * 1024
|
| 62 |
+
while quality >= 75:
|
| 63 |
+
buffer.seek(0)
|
| 64 |
+
buffer.truncate()
|
| 65 |
+
if quality >= 95:
|
| 66 |
+
subsampling = 0
|
| 67 |
+
elif quality >= 85:
|
| 68 |
+
subsampling = 1
|
| 69 |
+
else:
|
| 70 |
+
subsampling = 2
|
| 71 |
+
final_img.save(
|
| 72 |
+
buffer,
|
| 73 |
+
format='JPEG',
|
| 74 |
+
quality=quality,
|
| 75 |
+
optimize=True,
|
| 76 |
+
progressive=True,
|
| 77 |
+
subsampling=subsampling
|
| 78 |
+
)
|
| 79 |
+
current_size = buffer.tell()
|
| 80 |
+
if current_size <= max_file_size or quality <= 80:
|
| 81 |
+
break
|
| 82 |
+
overage_ratio = current_size / max_file_size
|
| 83 |
+
if overage_ratio > 2:
|
| 84 |
+
quality -= 8
|
| 85 |
+
elif overage_ratio > 1.5:
|
| 86 |
+
quality -= 5
|
| 87 |
+
else:
|
| 88 |
+
quality -= 3
|
| 89 |
+
return buffer.getvalue()
|
| 90 |
+
|
| 91 |
+
def get_unsplash_desktop_banners(search_query: str) -> Dict:
|
| 92 |
+
headers = {"Authorization": f"Client-ID {UNSPLASH_API_KEY}"}
|
| 93 |
+
search_url = f"{UNSPLASH_BASE_URL}/search/photos"
|
| 94 |
+
random_page = random.randint(1, 10)
|
| 95 |
+
params = {"query": search_query, "per_page": 2, "orientation": "landscape", "page": random_page, "order_by": "random", "content_filter": "high"}
|
| 96 |
+
logger.info(f"Fetching Unsplash images for query: '{search_query}', page: {random_page}")
|
| 97 |
+
response = requests.get(search_url, headers=headers, params=params)
|
| 98 |
+
if response.status_code != 200:
|
| 99 |
+
logger.error(f"Unsplash API error: {response.status_code} - {response.text}")
|
| 100 |
+
raise Exception("Failed to fetch images from Unsplash")
|
| 101 |
+
results = response.json().get("results", [])
|
| 102 |
+
all_banner_results = []
|
| 103 |
+
for idx, image in enumerate(results, start=1):
|
| 104 |
+
try:
|
| 105 |
+
image_url = image["urls"]["regular"]
|
| 106 |
+
img_response = requests.get(image_url)
|
| 107 |
+
if img_response.status_code != 200:
|
| 108 |
+
logger.warning(f"Failed to download image {idx} from Unsplash")
|
| 109 |
+
continue
|
| 110 |
+
image_data = img_response.content
|
| 111 |
+
processed_image = process_image(image_data, 1440, 500)
|
| 112 |
+
result = upload_to_reach(
|
| 113 |
+
processed_image,
|
| 114 |
+
f"unsplash_desktop_banner_v{idx}",
|
| 115 |
+
"jpeg",
|
| 116 |
+
idx,
|
| 117 |
+
"DESKTOP_IMAGE"
|
| 118 |
+
)
|
| 119 |
+
all_banner_results.append({
|
| 120 |
+
"variation": idx,
|
| 121 |
+
"banner": result['url']
|
| 122 |
+
})
|
| 123 |
+
logger.info(f"Processed and uploaded Unsplash desktop image variation {idx}")
|
| 124 |
+
except Exception as e:
|
| 125 |
+
logger.error(f"Error processing image {idx}: {str(e)}")
|
| 126 |
+
continue
|
| 127 |
+
if not all_banner_results:
|
| 128 |
+
logger.error("No images were processed successfully from Unsplash")
|
| 129 |
+
raise Exception("No images were processed successfully")
|
| 130 |
+
return {"variations": all_banner_results}
|
app/services/banner_unsplash_ipad_service.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import random
|
| 3 |
+
from typing import Dict
|
| 4 |
+
import requests
|
| 5 |
+
from app.config.settings import settings
|
| 6 |
+
from app.utils.reach_upload import upload_to_reach
|
| 7 |
+
from PIL import Image, ImageEnhance, ImageOps, ImageFilter
|
| 8 |
+
from io import BytesIO
|
| 9 |
+
import math
|
| 10 |
+
|
| 11 |
+
logger = logging.getLogger(__name__)
|
| 12 |
+
logger.setLevel(logging.INFO)
|
| 13 |
+
|
| 14 |
+
UNSPLASH_API_KEY = settings.UNSPLASH_API_KEY
|
| 15 |
+
UNSPLASH_BASE_URL = "https://api.unsplash.com"
|
| 16 |
+
|
| 17 |
+
def process_image(image_data: bytes, target_width: int, target_height: int) -> bytes:
|
| 18 |
+
img = Image.open(BytesIO(image_data)).convert('RGB')
|
| 19 |
+
original_width, original_height = img.size
|
| 20 |
+
original_ratio = original_width / original_height
|
| 21 |
+
target_ratio = target_width / target_height
|
| 22 |
+
upscale_threshold = max(target_width, target_height) / max(original_width, original_height)
|
| 23 |
+
if upscale_threshold > 1.2:
|
| 24 |
+
scale_factor = min(3, math.ceil(upscale_threshold))
|
| 25 |
+
intermediate_width = original_width * scale_factor
|
| 26 |
+
intermediate_height = original_height * scale_factor
|
| 27 |
+
working_img = img.resize((intermediate_width, intermediate_height), Image.BICUBIC)
|
| 28 |
+
working_img = working_img.filter(ImageFilter.UnsharpMask(radius=1.0, percent=120, threshold=3))
|
| 29 |
+
else:
|
| 30 |
+
working_img = img
|
| 31 |
+
if abs(original_ratio - target_ratio) > 0.1:
|
| 32 |
+
if original_ratio > target_ratio:
|
| 33 |
+
new_width = int(working_img.height * target_ratio)
|
| 34 |
+
left = (working_img.width - new_width) // 2
|
| 35 |
+
working_img = working_img.crop((left, 0, left + new_width, working_img.height))
|
| 36 |
+
else:
|
| 37 |
+
new_height = int(working_img.width / target_ratio)
|
| 38 |
+
top = (working_img.height - new_height) // 2
|
| 39 |
+
working_img = working_img.crop((0, top, working_img.width, top + new_height))
|
| 40 |
+
current_size = max(working_img.size)
|
| 41 |
+
target_size = max(target_width, target_height)
|
| 42 |
+
if current_size > target_size:
|
| 43 |
+
final_img = working_img.resize((target_width, target_height), Image.LANCZOS)
|
| 44 |
+
else:
|
| 45 |
+
final_img = working_img.resize((target_width, target_height), Image.BICUBIC)
|
| 46 |
+
target_pixels = target_width * target_height
|
| 47 |
+
if target_pixels < 500000:
|
| 48 |
+
final_img = ImageEnhance.Sharpness(final_img).enhance(1.4)
|
| 49 |
+
final_img = ImageEnhance.Contrast(final_img).enhance(1.15)
|
| 50 |
+
final_img = ImageEnhance.Color(final_img).enhance(1.05)
|
| 51 |
+
elif target_pixels < 1500000:
|
| 52 |
+
final_img = ImageEnhance.Sharpness(final_img).enhance(1.2)
|
| 53 |
+
final_img = ImageEnhance.Contrast(final_img).enhance(1.1)
|
| 54 |
+
final_img = ImageEnhance.Color(final_img).enhance(1.08)
|
| 55 |
+
else:
|
| 56 |
+
final_img = ImageEnhance.Sharpness(final_img).enhance(1.1)
|
| 57 |
+
final_img = ImageEnhance.Contrast(final_img).enhance(1.05)
|
| 58 |
+
final_img = ImageEnhance.Color(final_img).enhance(1.03)
|
| 59 |
+
buffer = BytesIO()
|
| 60 |
+
quality = 98
|
| 61 |
+
max_file_size = 500 * 1024
|
| 62 |
+
while quality >= 75:
|
| 63 |
+
buffer.seek(0)
|
| 64 |
+
buffer.truncate()
|
| 65 |
+
if quality >= 95:
|
| 66 |
+
subsampling = 0
|
| 67 |
+
elif quality >= 85:
|
| 68 |
+
subsampling = 1
|
| 69 |
+
else:
|
| 70 |
+
subsampling = 2
|
| 71 |
+
final_img.save(
|
| 72 |
+
buffer,
|
| 73 |
+
format='JPEG',
|
| 74 |
+
quality=quality,
|
| 75 |
+
optimize=True,
|
| 76 |
+
progressive=True,
|
| 77 |
+
subsampling=subsampling
|
| 78 |
+
)
|
| 79 |
+
current_size = buffer.tell()
|
| 80 |
+
if current_size <= max_file_size or quality <= 80:
|
| 81 |
+
break
|
| 82 |
+
overage_ratio = current_size / max_file_size
|
| 83 |
+
if overage_ratio > 2:
|
| 84 |
+
quality -= 8
|
| 85 |
+
elif overage_ratio > 1.5:
|
| 86 |
+
quality -= 5
|
| 87 |
+
else:
|
| 88 |
+
quality -= 3
|
| 89 |
+
return buffer.getvalue()
|
| 90 |
+
|
| 91 |
+
def get_unsplash_ipad_banners(search_query: str) -> Dict:
|
| 92 |
+
headers = {"Authorization": f"Client-ID {UNSPLASH_API_KEY}"}
|
| 93 |
+
search_url = f"{UNSPLASH_BASE_URL}/search/photos"
|
| 94 |
+
random_page = random.randint(1, 10)
|
| 95 |
+
params = {"query": search_query, "per_page": 2, "orientation": "landscape", "page": random_page, "order_by": "random", "content_filter": "high"}
|
| 96 |
+
logger.info(f"Fetching Unsplash images for query: '{search_query}', page: {random_page}")
|
| 97 |
+
response = requests.get(search_url, headers=headers, params=params)
|
| 98 |
+
if response.status_code != 200:
|
| 99 |
+
logger.error(f"Unsplash API error: {response.status_code} - {response.text}")
|
| 100 |
+
raise Exception("Failed to fetch images from Unsplash")
|
| 101 |
+
results = response.json().get("results", [])
|
| 102 |
+
all_banner_results = []
|
| 103 |
+
for idx, image in enumerate(results, start=1):
|
| 104 |
+
try:
|
| 105 |
+
image_url = image["urls"]["regular"]
|
| 106 |
+
img_response = requests.get(image_url)
|
| 107 |
+
if img_response.status_code != 200:
|
| 108 |
+
logger.warning(f"Failed to download image {idx} from Unsplash")
|
| 109 |
+
continue
|
| 110 |
+
image_data = img_response.content
|
| 111 |
+
processed_image = process_image(image_data, 768, 500)
|
| 112 |
+
result = upload_to_reach(
|
| 113 |
+
processed_image,
|
| 114 |
+
f"unsplash_ipad_banner_v{idx}",
|
| 115 |
+
"jpeg",
|
| 116 |
+
idx,
|
| 117 |
+
"IPAD_IMAGE"
|
| 118 |
+
)
|
| 119 |
+
all_banner_results.append({
|
| 120 |
+
"variation": idx,
|
| 121 |
+
"banner": result['url']
|
| 122 |
+
})
|
| 123 |
+
logger.info(f"Processed and uploaded Unsplash iPad image variation {idx}")
|
| 124 |
+
except Exception as e:
|
| 125 |
+
logger.error(f"Error processing image {idx}: {str(e)}")
|
| 126 |
+
continue
|
| 127 |
+
if not all_banner_results:
|
| 128 |
+
logger.error("No images were processed successfully from Unsplash")
|
| 129 |
+
raise Exception("No images were processed successfully")
|
| 130 |
+
return {"variations": all_banner_results}
|
app/services/banner_unsplash_mobile_service.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import random
|
| 3 |
+
from typing import Dict
|
| 4 |
+
import requests
|
| 5 |
+
from app.config.settings import settings
|
| 6 |
+
from app.utils.reach_upload import upload_to_reach
|
| 7 |
+
from PIL import Image, ImageEnhance, ImageOps, ImageFilter
|
| 8 |
+
from io import BytesIO
|
| 9 |
+
import math
|
| 10 |
+
|
| 11 |
+
logger = logging.getLogger(__name__)
|
| 12 |
+
logger.setLevel(logging.INFO)
|
| 13 |
+
|
| 14 |
+
UNSPLASH_API_KEY = settings.UNSPLASH_API_KEY
|
| 15 |
+
UNSPLASH_BASE_URL = "https://api.unsplash.com"
|
| 16 |
+
|
| 17 |
+
def process_image(image_data: bytes, target_width: int, target_height: int) -> bytes:
|
| 18 |
+
img = Image.open(BytesIO(image_data)).convert('RGB')
|
| 19 |
+
original_width, original_height = img.size
|
| 20 |
+
original_ratio = original_width / original_height
|
| 21 |
+
target_ratio = target_width / target_height
|
| 22 |
+
upscale_threshold = max(target_width, target_height) / max(original_width, original_height)
|
| 23 |
+
if upscale_threshold > 1.2:
|
| 24 |
+
scale_factor = min(3, math.ceil(upscale_threshold))
|
| 25 |
+
intermediate_width = original_width * scale_factor
|
| 26 |
+
intermediate_height = original_height * scale_factor
|
| 27 |
+
working_img = img.resize((intermediate_width, intermediate_height), Image.BICUBIC)
|
| 28 |
+
working_img = working_img.filter(ImageFilter.UnsharpMask(radius=1.0, percent=120, threshold=3))
|
| 29 |
+
else:
|
| 30 |
+
working_img = img
|
| 31 |
+
if abs(original_ratio - target_ratio) > 0.1:
|
| 32 |
+
if original_ratio > target_ratio:
|
| 33 |
+
new_width = int(working_img.height * target_ratio)
|
| 34 |
+
left = (working_img.width - new_width) // 2
|
| 35 |
+
working_img = working_img.crop((left, 0, left + new_width, working_img.height))
|
| 36 |
+
else:
|
| 37 |
+
new_height = int(working_img.width / target_ratio)
|
| 38 |
+
top = (working_img.height - new_height) // 2
|
| 39 |
+
working_img = working_img.crop((0, top, working_img.width, top + new_height))
|
| 40 |
+
current_size = max(working_img.size)
|
| 41 |
+
target_size = max(target_width, target_height)
|
| 42 |
+
if current_size > target_size:
|
| 43 |
+
final_img = working_img.resize((target_width, target_height), Image.LANCZOS)
|
| 44 |
+
else:
|
| 45 |
+
final_img = working_img.resize((target_width, target_height), Image.BICUBIC)
|
| 46 |
+
target_pixels = target_width * target_height
|
| 47 |
+
if target_pixels < 500000:
|
| 48 |
+
final_img = ImageEnhance.Sharpness(final_img).enhance(1.4)
|
| 49 |
+
final_img = ImageEnhance.Contrast(final_img).enhance(1.15)
|
| 50 |
+
final_img = ImageEnhance.Color(final_img).enhance(1.05)
|
| 51 |
+
elif target_pixels < 1500000:
|
| 52 |
+
final_img = ImageEnhance.Sharpness(final_img).enhance(1.2)
|
| 53 |
+
final_img = ImageEnhance.Contrast(final_img).enhance(1.1)
|
| 54 |
+
final_img = ImageEnhance.Color(final_img).enhance(1.08)
|
| 55 |
+
else:
|
| 56 |
+
final_img = ImageEnhance.Sharpness(final_img).enhance(1.1)
|
| 57 |
+
final_img = ImageEnhance.Contrast(final_img).enhance(1.05)
|
| 58 |
+
final_img = ImageEnhance.Color(final_img).enhance(1.03)
|
| 59 |
+
buffer = BytesIO()
|
| 60 |
+
quality = 98
|
| 61 |
+
max_file_size = 500 * 1024
|
| 62 |
+
while quality >= 75:
|
| 63 |
+
buffer.seek(0)
|
| 64 |
+
buffer.truncate()
|
| 65 |
+
if quality >= 95:
|
| 66 |
+
subsampling = 0
|
| 67 |
+
elif quality >= 85:
|
| 68 |
+
subsampling = 1
|
| 69 |
+
else:
|
| 70 |
+
subsampling = 2
|
| 71 |
+
final_img.save(
|
| 72 |
+
buffer,
|
| 73 |
+
format='JPEG',
|
| 74 |
+
quality=quality,
|
| 75 |
+
optimize=True,
|
| 76 |
+
progressive=True,
|
| 77 |
+
subsampling=subsampling
|
| 78 |
+
)
|
| 79 |
+
current_size = buffer.tell()
|
| 80 |
+
if current_size <= max_file_size or quality <= 80:
|
| 81 |
+
break
|
| 82 |
+
overage_ratio = current_size / max_file_size
|
| 83 |
+
if overage_ratio > 2:
|
| 84 |
+
quality -= 8
|
| 85 |
+
elif overage_ratio > 1.5:
|
| 86 |
+
quality -= 5
|
| 87 |
+
else:
|
| 88 |
+
quality -= 3
|
| 89 |
+
return buffer.getvalue()
|
| 90 |
+
|
| 91 |
+
def get_unsplash_mobile_banners(search_query: str) -> Dict:
|
| 92 |
+
headers = {"Authorization": f"Client-ID {UNSPLASH_API_KEY}"}
|
| 93 |
+
search_url = f"{UNSPLASH_BASE_URL}/search/photos"
|
| 94 |
+
random_page = random.randint(1, 10)
|
| 95 |
+
params = {"query": search_query, "per_page": 2, "orientation": "landscape", "page": random_page, "order_by": "random", "content_filter": "high"}
|
| 96 |
+
logger.info(f"Fetching Unsplash images for query: '{search_query}', page: {random_page}")
|
| 97 |
+
response = requests.get(search_url, headers=headers, params=params)
|
| 98 |
+
if response.status_code != 200:
|
| 99 |
+
logger.error(f"Unsplash API error: {response.status_code} - {response.text}")
|
| 100 |
+
raise Exception("Failed to fetch images from Unsplash")
|
| 101 |
+
results = response.json().get("results", [])
|
| 102 |
+
all_banner_results = []
|
| 103 |
+
for idx, image in enumerate(results, start=1):
|
| 104 |
+
try:
|
| 105 |
+
image_url = image["urls"]["regular"]
|
| 106 |
+
img_response = requests.get(image_url)
|
| 107 |
+
if img_response.status_code != 200:
|
| 108 |
+
logger.warning(f"Failed to download image {idx} from Unsplash")
|
| 109 |
+
continue
|
| 110 |
+
image_data = img_response.content
|
| 111 |
+
processed_image = process_image(image_data, 375, 500)
|
| 112 |
+
result = upload_to_reach(
|
| 113 |
+
processed_image,
|
| 114 |
+
f"unsplash_mobile_banner_v{idx}",
|
| 115 |
+
"jpeg",
|
| 116 |
+
idx,
|
| 117 |
+
"WEB_IMAGE"
|
| 118 |
+
)
|
| 119 |
+
all_banner_results.append({
|
| 120 |
+
"variation": idx,
|
| 121 |
+
"banner": result['url']
|
| 122 |
+
})
|
| 123 |
+
logger.info(f"Processed and uploaded Unsplash mobile image variation {idx}")
|
| 124 |
+
except Exception as e:
|
| 125 |
+
logger.error(f"Error processing image {idx}: {str(e)}")
|
| 126 |
+
continue
|
| 127 |
+
if not all_banner_results:
|
| 128 |
+
logger.error("No images were processed successfully from Unsplash")
|
| 129 |
+
raise Exception("No images were processed successfully")
|
| 130 |
+
return {"variations": all_banner_results}
|
app/services/bestnetwork_service.py
CHANGED
|
@@ -15,7 +15,9 @@ logger = logging.getLogger(__name__)
|
|
| 15 |
logging.basicConfig(level=logging.INFO)
|
| 16 |
|
| 17 |
def get_network_prompts(brand_details: str) -> str:
|
| 18 |
-
prompt = f
|
|
|
|
|
|
|
| 19 |
return prompt
|
| 20 |
|
| 21 |
def process_image(image_data: bytes, width: int = 530, height: int = 352) -> bytes:
|
|
@@ -95,7 +97,7 @@ def generate_network_banner(brand_details: str) -> Dict:
|
|
| 95 |
try:
|
| 96 |
logger.info(f"Sending prompt to Gemini API for variation {variation}.")
|
| 97 |
response = client.models.generate_content(
|
| 98 |
-
model="gemini-2.0-flash-
|
| 99 |
contents=prompt,
|
| 100 |
config=types.GenerateContentConfig(
|
| 101 |
response_modalities=['TEXT', 'IMAGE']
|
|
@@ -150,4 +152,4 @@ def generate_network_banner(brand_details: str) -> Dict:
|
|
| 150 |
raise Exception("No images were generated")
|
| 151 |
|
| 152 |
logger.info(f"Generated {len(all_banner_results)} banner variations successfully.")
|
| 153 |
-
return {"variations": all_banner_results}
|
|
|
|
| 15 |
logging.basicConfig(level=logging.INFO)
|
| 16 |
|
| 17 |
def get_network_prompts(brand_details: str) -> str:
|
| 18 |
+
prompt = f'''Generate a realistic representation of a mobile virtual network operator brand:
|
| 19 |
+
{brand_details}
|
| 20 |
+
image should reflect themes like global wireless communication, interconnected devices, reliable connectivity and wide coverage. Ensure elements are centered or balanced. DO NOT INCLUDE ANY TEXT IN THE IMAGE.'''
|
| 21 |
return prompt
|
| 22 |
|
| 23 |
def process_image(image_data: bytes, width: int = 530, height: int = 352) -> bytes:
|
|
|
|
| 97 |
try:
|
| 98 |
logger.info(f"Sending prompt to Gemini API for variation {variation}.")
|
| 99 |
response = client.models.generate_content(
|
| 100 |
+
model="gemini-2.0-flash-preview-image-generation",
|
| 101 |
contents=prompt,
|
| 102 |
config=types.GenerateContentConfig(
|
| 103 |
response_modalities=['TEXT', 'IMAGE']
|
|
|
|
| 152 |
raise Exception("No images were generated")
|
| 153 |
|
| 154 |
logger.info(f"Generated {len(all_banner_results)} banner variations successfully.")
|
| 155 |
+
return {"variations": all_banner_results}
|
app/services/byop_service.py
CHANGED
|
@@ -15,7 +15,9 @@ logger.setLevel(logging.INFO)
|
|
| 15 |
|
| 16 |
|
| 17 |
def get_byop_prompts(brand_details: str) -> str:
|
| 18 |
-
prompt = f
|
|
|
|
|
|
|
| 19 |
return prompt
|
| 20 |
|
| 21 |
def process_image(image_data: bytes, width: int = 530, height: int = 352) -> bytes:
|
|
@@ -99,7 +101,7 @@ def generate_byop_banner(brand_details: str) -> Dict:
|
|
| 99 |
try:
|
| 100 |
logger.info(f"Sending prompt to Gemini API for variation {variation}")
|
| 101 |
response = client.models.generate_content(
|
| 102 |
-
model="gemini-2.0-flash-
|
| 103 |
contents=prompt,
|
| 104 |
config=types.GenerateContentConfig(
|
| 105 |
response_modalities=['TEXT', 'IMAGE']
|
|
@@ -153,4 +155,4 @@ def generate_byop_banner(brand_details: str) -> Dict:
|
|
| 153 |
raise Exception("No images were generated")
|
| 154 |
|
| 155 |
logger.info(f"Generated {len(all_banner_results)} BYOP banner(s) successfully")
|
| 156 |
-
return {"variations": all_banner_results}
|
|
|
|
| 15 |
|
| 16 |
|
| 17 |
def get_byop_prompts(brand_details: str) -> str:
|
| 18 |
+
prompt = f'''Generate a photorealistic representation for a brand :
|
| 19 |
+
{brand_details}
|
| 20 |
+
Convey clean and modern themes of compatibility. include elements like phones, network towers etc. Ensure elements are centered or balanced. DO NOT INCLUDE ANY TEXT IN THE IMAGE.'''
|
| 21 |
return prompt
|
| 22 |
|
| 23 |
def process_image(image_data: bytes, width: int = 530, height: int = 352) -> bytes:
|
|
|
|
| 101 |
try:
|
| 102 |
logger.info(f"Sending prompt to Gemini API for variation {variation}")
|
| 103 |
response = client.models.generate_content(
|
| 104 |
+
model="gemini-2.0-flash-preview-image-generation",
|
| 105 |
contents=prompt,
|
| 106 |
config=types.GenerateContentConfig(
|
| 107 |
response_modalities=['TEXT', 'IMAGE']
|
|
|
|
| 155 |
raise Exception("No images were generated")
|
| 156 |
|
| 157 |
logger.info(f"Generated {len(all_banner_results)} BYOP banner(s) successfully")
|
| 158 |
+
return {"variations": all_banner_results}
|
app/services/byop_unsplash_desktop_service.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import random
|
| 3 |
+
from typing import Dict
|
| 4 |
+
import requests
|
| 5 |
+
from app.config.settings import settings
|
| 6 |
+
from app.utils.reach_upload import upload_to_reach
|
| 7 |
+
from PIL import Image, ImageEnhance, ImageOps
|
| 8 |
+
from io import BytesIO
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
logger.setLevel(logging.INFO)
|
| 12 |
+
|
| 13 |
+
UNSPLASH_API_KEY = settings.UNSPLASH_API_KEY
|
| 14 |
+
UNSPLASH_BASE_URL = "https://api.unsplash.com"
|
| 15 |
+
|
| 16 |
+
def process_image(image_data: bytes, target_width: int, target_height: int) -> bytes:
|
| 17 |
+
img = Image.open(BytesIO(image_data)).convert("RGB")
|
| 18 |
+
intermediate_size = (target_width * 4, target_height * 4)
|
| 19 |
+
upscaled = ImageOps.fit(img, intermediate_size, method=Image.LANCZOS, centering=(0.5, 0.5))
|
| 20 |
+
upscaled = ImageEnhance.Sharpness(upscaled).enhance(1.3)
|
| 21 |
+
upscaled = ImageEnhance.Contrast(upscaled).enhance(1.1)
|
| 22 |
+
final = ImageOps.fit(upscaled, (target_width, target_height), method=Image.LANCZOS, centering=(0.5, 0.5))
|
| 23 |
+
final = ImageEnhance.Sharpness(final).enhance(1.1)
|
| 24 |
+
final = ImageEnhance.Color(final).enhance(1.1)
|
| 25 |
+
buffer = BytesIO()
|
| 26 |
+
quality = 95
|
| 27 |
+
while True:
|
| 28 |
+
buffer.seek(0)
|
| 29 |
+
buffer.truncate()
|
| 30 |
+
final.save(buffer, format="JPEG", quality=quality, optimize=True, progressive=True, subsampling=0 if quality >= 90 else 1)
|
| 31 |
+
if buffer.tell() <= 500 * 1024 or quality <= 80:
|
| 32 |
+
break
|
| 33 |
+
quality -= 3
|
| 34 |
+
return buffer.getvalue()
|
| 35 |
+
|
| 36 |
+
def get_unsplash_byop_desktop_images(query: str) -> Dict:
|
| 37 |
+
headers = {"Authorization": f"Client-ID {UNSPLASH_API_KEY}"}
|
| 38 |
+
search_url = f"{UNSPLASH_BASE_URL}/search/photos"
|
| 39 |
+
random_page = random.randint(1, 10)
|
| 40 |
+
params = {"query": query, "per_page": 2, "orientation": "landscape", "page": random_page, "order_by": "random", "content_filter": "high"}
|
| 41 |
+
logger.info(f"Fetching Unsplash images for query: '{query}', page: {random_page}")
|
| 42 |
+
response = requests.get(search_url, headers=headers, params=params)
|
| 43 |
+
if response.status_code != 200:
|
| 44 |
+
logger.error(f"Unsplash API error: {response.status_code} - {response.text}")
|
| 45 |
+
raise Exception("Failed to fetch images from Unsplash")
|
| 46 |
+
results = response.json().get("results", [])
|
| 47 |
+
all_image_results = []
|
| 48 |
+
for idx, image in enumerate(results, start=1):
|
| 49 |
+
try:
|
| 50 |
+
image_url = image["urls"]["regular"]
|
| 51 |
+
img_response = requests.get(image_url)
|
| 52 |
+
if img_response.status_code != 200:
|
| 53 |
+
logger.warning(f"Failed to download image {idx} from Unsplash")
|
| 54 |
+
continue
|
| 55 |
+
image_data = img_response.content
|
| 56 |
+
processed_image = process_image(image_data, 520, 352)
|
| 57 |
+
result = upload_to_reach(
|
| 58 |
+
processed_image,
|
| 59 |
+
f"byop_unsplash_desktop_banner_v{idx}",
|
| 60 |
+
"jpeg",
|
| 61 |
+
idx,
|
| 62 |
+
'BYOD_IMAGE'
|
| 63 |
+
)
|
| 64 |
+
all_image_results.append({
|
| 65 |
+
"variation": idx,
|
| 66 |
+
"banner": result['url']
|
| 67 |
+
})
|
| 68 |
+
logger.info(f"Processed and uploaded Unsplash desktop image variation {idx}")
|
| 69 |
+
except Exception as e:
|
| 70 |
+
logger.error(f"Error processing image {idx}: {str(e)}")
|
| 71 |
+
continue
|
| 72 |
+
if not all_image_results:
|
| 73 |
+
logger.error("No images were processed successfully from Unsplash")
|
| 74 |
+
raise Exception("No images were processed successfully")
|
| 75 |
+
return {"variations": all_image_results}
|
app/services/byop_unsplash_ipad_service.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import random
|
| 3 |
+
from typing import Dict
|
| 4 |
+
import requests
|
| 5 |
+
from app.config.settings import settings
|
| 6 |
+
from app.utils.reach_upload import upload_to_reach
|
| 7 |
+
from PIL import Image, ImageEnhance, ImageOps
|
| 8 |
+
from io import BytesIO
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
logger.setLevel(logging.INFO)
|
| 12 |
+
|
| 13 |
+
UNSPLASH_API_KEY = settings.UNSPLASH_API_KEY
|
| 14 |
+
UNSPLASH_BASE_URL = "https://api.unsplash.com"
|
| 15 |
+
|
| 16 |
+
def process_image(image_data: bytes, target_width: int, target_height: int) -> bytes:
|
| 17 |
+
img = Image.open(BytesIO(image_data)).convert("RGB")
|
| 18 |
+
intermediate_size = (target_width * 4, target_height * 4)
|
| 19 |
+
upscaled = ImageOps.fit(img, intermediate_size, method=Image.LANCZOS, centering=(0.5, 0.5))
|
| 20 |
+
upscaled = ImageEnhance.Sharpness(upscaled).enhance(1.3)
|
| 21 |
+
upscaled = ImageEnhance.Contrast(upscaled).enhance(1.1)
|
| 22 |
+
final = ImageOps.fit(upscaled, (target_width, target_height), method=Image.LANCZOS, centering=(0.5, 0.5))
|
| 23 |
+
final = ImageEnhance.Sharpness(final).enhance(1.1)
|
| 24 |
+
final = ImageEnhance.Color(final).enhance(1.1)
|
| 25 |
+
buffer = BytesIO()
|
| 26 |
+
quality = 95
|
| 27 |
+
while True:
|
| 28 |
+
buffer.seek(0)
|
| 29 |
+
buffer.truncate()
|
| 30 |
+
final.save(buffer, format="JPEG", quality=quality, optimize=True, progressive=True, subsampling=0 if quality >= 90 else 1)
|
| 31 |
+
if buffer.tell() <= 500 * 1024 or quality <= 80:
|
| 32 |
+
break
|
| 33 |
+
quality -= 3
|
| 34 |
+
return buffer.getvalue()
|
| 35 |
+
|
| 36 |
+
def get_unsplash_byop_ipad_images(query: str) -> Dict:
|
| 37 |
+
headers = {"Authorization": f"Client-ID {UNSPLASH_API_KEY}"}
|
| 38 |
+
search_url = f"{UNSPLASH_BASE_URL}/search/photos"
|
| 39 |
+
random_page = random.randint(1, 10)
|
| 40 |
+
params = {"query": query, "per_page": 2, "orientation": "landscape", "page": random_page, "order_by": "random", "content_filter": "high"}
|
| 41 |
+
logger.info(f"Fetching Unsplash images for query: '{query}', page: {random_page}")
|
| 42 |
+
response = requests.get(search_url, headers=headers, params=params)
|
| 43 |
+
if response.status_code != 200:
|
| 44 |
+
logger.error(f"Unsplash API error: {response.status_code} - {response.text}")
|
| 45 |
+
raise Exception("Failed to fetch images from Unsplash")
|
| 46 |
+
results = response.json().get("results", [])
|
| 47 |
+
all_image_results = []
|
| 48 |
+
for idx, image in enumerate(results, start=1):
|
| 49 |
+
try:
|
| 50 |
+
image_url = image["urls"]["regular"]
|
| 51 |
+
img_response = requests.get(image_url)
|
| 52 |
+
if img_response.status_code != 200:
|
| 53 |
+
logger.warning(f"Failed to download image {idx} from Unsplash")
|
| 54 |
+
continue
|
| 55 |
+
image_data = img_response.content
|
| 56 |
+
processed_image = process_image(image_data, 768, 500)
|
| 57 |
+
result = upload_to_reach(
|
| 58 |
+
processed_image,
|
| 59 |
+
f"byop_unsplash_ipad_banner_v{idx}",
|
| 60 |
+
"jpeg",
|
| 61 |
+
idx,
|
| 62 |
+
'BYOD_IMAGE'
|
| 63 |
+
)
|
| 64 |
+
all_image_results.append({
|
| 65 |
+
"variation": idx,
|
| 66 |
+
"banner": result['url']
|
| 67 |
+
})
|
| 68 |
+
logger.info(f"Processed and uploaded Unsplash iPad image variation {idx}")
|
| 69 |
+
except Exception as e:
|
| 70 |
+
logger.error(f"Error processing image {idx}: {str(e)}")
|
| 71 |
+
continue
|
| 72 |
+
if not all_image_results:
|
| 73 |
+
logger.error("No images were processed successfully from Unsplash")
|
| 74 |
+
raise Exception("No images were processed successfully")
|
| 75 |
+
return {"variations": all_image_results}
|
app/services/byop_unsplash_mobile_service.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import random
|
| 3 |
+
from typing import Dict
|
| 4 |
+
import requests
|
| 5 |
+
from app.config.settings import settings
|
| 6 |
+
from app.utils.reach_upload import upload_to_reach
|
| 7 |
+
from PIL import Image, ImageEnhance, ImageOps
|
| 8 |
+
from io import BytesIO
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
logger.setLevel(logging.INFO)
|
| 12 |
+
|
| 13 |
+
UNSPLASH_API_KEY = settings.UNSPLASH_API_KEY
|
| 14 |
+
UNSPLASH_BASE_URL = "https://api.unsplash.com"
|
| 15 |
+
|
| 16 |
+
def process_image(image_data: bytes, target_width: int, target_height: int) -> bytes:
|
| 17 |
+
img = Image.open(BytesIO(image_data)).convert("RGB")
|
| 18 |
+
intermediate_size = (target_width * 4, target_height * 4)
|
| 19 |
+
upscaled = ImageOps.fit(img, intermediate_size, method=Image.LANCZOS, centering=(0.5, 0.5))
|
| 20 |
+
upscaled = ImageEnhance.Sharpness(upscaled).enhance(1.3)
|
| 21 |
+
upscaled = ImageEnhance.Contrast(upscaled).enhance(1.1)
|
| 22 |
+
final = ImageOps.fit(upscaled, (target_width, target_height), method=Image.LANCZOS, centering=(0.5, 0.5))
|
| 23 |
+
final = ImageEnhance.Sharpness(final).enhance(1.1)
|
| 24 |
+
final = ImageEnhance.Color(final).enhance(1.1)
|
| 25 |
+
buffer = BytesIO()
|
| 26 |
+
quality = 95
|
| 27 |
+
while True:
|
| 28 |
+
buffer.seek(0)
|
| 29 |
+
buffer.truncate()
|
| 30 |
+
final.save(buffer, format="JPEG", quality=quality, optimize=True, progressive=True, subsampling=0 if quality >= 90 else 1)
|
| 31 |
+
if buffer.tell() <= 500 * 1024 or quality <= 80:
|
| 32 |
+
break
|
| 33 |
+
quality -= 3
|
| 34 |
+
return buffer.getvalue()
|
| 35 |
+
|
| 36 |
+
def get_unsplash_byop_mobile_images(query: str) -> Dict:
|
| 37 |
+
headers = {"Authorization": f"Client-ID {UNSPLASH_API_KEY}"}
|
| 38 |
+
search_url = f"{UNSPLASH_BASE_URL}/search/photos"
|
| 39 |
+
random_page = random.randint(1, 10)
|
| 40 |
+
params = {"query": query, "per_page": 2, "orientation": "landscape", "page": random_page, "order_by": "random", "content_filter": "high"}
|
| 41 |
+
logger.info(f"Fetching Unsplash images for query: '{query}', page: {random_page}")
|
| 42 |
+
response = requests.get(search_url, headers=headers, params=params)
|
| 43 |
+
if response.status_code != 200:
|
| 44 |
+
logger.error(f"Unsplash API error: {response.status_code} - {response.text}")
|
| 45 |
+
raise Exception("Failed to fetch images from Unsplash")
|
| 46 |
+
results = response.json().get("results", [])
|
| 47 |
+
all_image_results = []
|
| 48 |
+
for idx, image in enumerate(results, start=1):
|
| 49 |
+
try:
|
| 50 |
+
image_url = image["urls"]["regular"]
|
| 51 |
+
img_response = requests.get(image_url)
|
| 52 |
+
if img_response.status_code != 200:
|
| 53 |
+
logger.warning(f"Failed to download image {idx} from Unsplash")
|
| 54 |
+
continue
|
| 55 |
+
image_data = img_response.content
|
| 56 |
+
processed_image = process_image(image_data, 375, 500)
|
| 57 |
+
result = upload_to_reach(
|
| 58 |
+
processed_image,
|
| 59 |
+
f"byop_unsplash_mobile_banner_v{idx}",
|
| 60 |
+
"jpeg",
|
| 61 |
+
idx,
|
| 62 |
+
'BYOD_IMAGE'
|
| 63 |
+
)
|
| 64 |
+
all_image_results.append({
|
| 65 |
+
"variation": idx,
|
| 66 |
+
"banner": result['url']
|
| 67 |
+
})
|
| 68 |
+
logger.info(f"Processed and uploaded Unsplash mobile image variation {idx}")
|
| 69 |
+
except Exception as e:
|
| 70 |
+
logger.error(f"Error processing image {idx}: {str(e)}")
|
| 71 |
+
continue
|
| 72 |
+
if not all_image_results:
|
| 73 |
+
logger.error("No images were processed successfully from Unsplash")
|
| 74 |
+
raise Exception("No images were processed successfully")
|
| 75 |
+
return {"variations": all_image_results}
|
app/services/custom_banner_desktop_service.py
CHANGED
|
@@ -13,15 +13,16 @@ from app.utils.name_generator import generate_brand_name
|
|
| 13 |
logger = logging.getLogger(__name__)
|
| 14 |
|
| 15 |
def get_desktop_prompt(
|
| 16 |
-
prompt: str, brand_details: str
|
| 17 |
) -> str:
|
| 18 |
return f'''
|
| 19 |
-
Based on the prompt: {prompt}
|
| 20 |
-
|
| 21 |
Create an realistic image that reflects this brand:
|
| 22 |
{brand_details}
|
|
|
|
|
|
|
| 23 |
|
| 24 |
-
The image must be professional and realistic, and must not contain any text, typographic or alphanumeric elements.
|
| 25 |
'''
|
| 26 |
|
| 27 |
|
|
@@ -72,8 +73,8 @@ def process_image(image_data: bytes, target_width: int, target_height: int) -> b
|
|
| 72 |
|
| 73 |
return buffer.getvalue()
|
| 74 |
|
| 75 |
-
def
|
| 76 |
-
prompt: str, brand_details: str
|
| 77 |
) -> Dict[str, str]:
|
| 78 |
"""
|
| 79 |
Generate desktop banner using Gemini and upload to Reach platform.
|
|
@@ -86,11 +87,11 @@ def generate_desktop_banner(
|
|
| 86 |
logger.info(f"Starting desktop banner generation with ID: {brand_name}")
|
| 87 |
all_banner_results = []
|
| 88 |
|
| 89 |
-
prompt_text = get_desktop_prompt(prompt, brand_details)
|
| 90 |
for variation in range(1, 3): # Generate two variations
|
| 91 |
try:
|
| 92 |
response = client.models.generate_content(
|
| 93 |
-
model="gemini-2.0-flash-
|
| 94 |
contents=prompt_text,
|
| 95 |
config=types.GenerateContentConfig(response_modalities=["TEXT", "IMAGE"])
|
| 96 |
)
|
|
|
|
| 13 |
logger = logging.getLogger(__name__)
|
| 14 |
|
| 15 |
def get_desktop_prompt(
|
| 16 |
+
prompt: str, brand_details: str, primary_color: str
|
| 17 |
) -> str:
|
| 18 |
return f'''
|
| 19 |
+
Based on the prompt: {prompt}
|
| 20 |
+
|
| 21 |
Create an realistic image that reflects this brand:
|
| 22 |
{brand_details}
|
| 23 |
+
|
| 24 |
+
Exclude using the color {primary_color} in the palette. The image must be professional and realistic, and must not contain any text, typographic or alphanumeric elements.
|
| 25 |
|
|
|
|
| 26 |
'''
|
| 27 |
|
| 28 |
|
|
|
|
| 73 |
|
| 74 |
return buffer.getvalue()
|
| 75 |
|
| 76 |
+
def generate_desktop_banner_v2(
|
| 77 |
+
prompt: str, brand_details: str, primary_color: str
|
| 78 |
) -> Dict[str, str]:
|
| 79 |
"""
|
| 80 |
Generate desktop banner using Gemini and upload to Reach platform.
|
|
|
|
| 87 |
logger.info(f"Starting desktop banner generation with ID: {brand_name}")
|
| 88 |
all_banner_results = []
|
| 89 |
|
| 90 |
+
prompt_text = get_desktop_prompt(prompt, brand_details, primary_color)
|
| 91 |
for variation in range(1, 3): # Generate two variations
|
| 92 |
try:
|
| 93 |
response = client.models.generate_content(
|
| 94 |
+
model="gemini-2.0-flash-preview-image-generation",
|
| 95 |
contents=prompt_text,
|
| 96 |
config=types.GenerateContentConfig(response_modalities=["TEXT", "IMAGE"])
|
| 97 |
)
|
app/services/custom_banner_ipad_service.py
CHANGED
|
@@ -13,16 +13,10 @@ from app.utils.name_generator import generate_brand_name
|
|
| 13 |
logger = logging.getLogger(__name__)
|
| 14 |
|
| 15 |
def get_ipad_prompt(
|
| 16 |
-
prompt: str, brand_details: str
|
| 17 |
) -> str:
|
| 18 |
return f'''
|
| 19 |
-
{prompt}
|
| 20 |
-
|
| 21 |
-
Create an realistic image that reflects this brand:
|
| 22 |
-
{brand_details}
|
| 23 |
-
|
| 24 |
-
The image must be professional and realistic, and must not contain any text, typographic or alphanumeric elements.
|
| 25 |
-
'''
|
| 26 |
|
| 27 |
def process_image(image_data: bytes, target_width: int, target_height: int) -> bytes:
|
| 28 |
"""
|
|
@@ -71,8 +65,8 @@ def process_image(image_data: bytes, target_width: int, target_height: int) -> b
|
|
| 71 |
|
| 72 |
return buffer.getvalue()
|
| 73 |
|
| 74 |
-
def
|
| 75 |
-
prompt: str, brand_details: str
|
| 76 |
) -> Dict[str, str]:
|
| 77 |
"""
|
| 78 |
Generate iPad banner using Gemini and upload to Reach platform.
|
|
@@ -85,11 +79,11 @@ def generate_ipad_banner(
|
|
| 85 |
logger.info(f"Starting iPad banner generation with ID: {brand_name}")
|
| 86 |
all_banner_results = []
|
| 87 |
|
| 88 |
-
prompt_text = get_ipad_prompt(prompt, brand_details)
|
| 89 |
for variation in range(1, 3): # Generate two variations
|
| 90 |
try:
|
| 91 |
response = client.models.generate_content(
|
| 92 |
-
model="gemini-2.0-flash-
|
| 93 |
contents=prompt_text,
|
| 94 |
config=types.GenerateContentConfig(response_modalities=["TEXT", "IMAGE"])
|
| 95 |
)
|
|
|
|
| 13 |
logger = logging.getLogger(__name__)
|
| 14 |
|
| 15 |
def get_ipad_prompt(
|
| 16 |
+
prompt: str, brand_details: str, primary_color: str
|
| 17 |
) -> str:
|
| 18 |
return f'''
|
| 19 |
+
Based on the prompt: {prompt}\n\n Create an realistic image that reflects this brand:\n {brand_details}\n \n Exclude the use of color {primary_color} in the palette. The image must be professional and realistic, and must not contain any text, typographic or alphanumeric elements.\n '''
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
def process_image(image_data: bytes, target_width: int, target_height: int) -> bytes:
|
| 22 |
"""
|
|
|
|
| 65 |
|
| 66 |
return buffer.getvalue()
|
| 67 |
|
| 68 |
+
def generate_ipad_banner_v2(
|
| 69 |
+
prompt: str, brand_details: str, primary_color: str
|
| 70 |
) -> Dict[str, str]:
|
| 71 |
"""
|
| 72 |
Generate iPad banner using Gemini and upload to Reach platform.
|
|
|
|
| 79 |
logger.info(f"Starting iPad banner generation with ID: {brand_name}")
|
| 80 |
all_banner_results = []
|
| 81 |
|
| 82 |
+
prompt_text = get_ipad_prompt(prompt, brand_details, primary_color)
|
| 83 |
for variation in range(1, 3): # Generate two variations
|
| 84 |
try:
|
| 85 |
response = client.models.generate_content(
|
| 86 |
+
model="gemini-2.0-flash-preview-image-generation",
|
| 87 |
contents=prompt_text,
|
| 88 |
config=types.GenerateContentConfig(response_modalities=["TEXT", "IMAGE"])
|
| 89 |
)
|
app/services/custom_banner_mobile_service.py
CHANGED
|
@@ -13,15 +13,16 @@ from app.utils.name_generator import generate_brand_name
|
|
| 13 |
logger = logging.getLogger(__name__)
|
| 14 |
|
| 15 |
def get_mobile_prompt(
|
| 16 |
-
prompt: str, brand_details: str
|
| 17 |
) -> str:
|
| 18 |
return f'''
|
| 19 |
-
{prompt}
|
| 20 |
|
| 21 |
Create an realistic image that reflects this brand:
|
| 22 |
{brand_details}
|
|
|
|
|
|
|
| 23 |
|
| 24 |
-
The image must be professional and realistic, and must not contain any text, typographic or alphanumeric elements.
|
| 25 |
'''
|
| 26 |
|
| 27 |
def process_image(image_data: bytes, target_width: int, target_height: int) -> bytes:
|
|
@@ -71,8 +72,8 @@ def process_image(image_data: bytes, target_width: int, target_height: int) -> b
|
|
| 71 |
|
| 72 |
return buffer.getvalue()
|
| 73 |
|
| 74 |
-
def
|
| 75 |
-
prompt: str, brand_details: str
|
| 76 |
) -> Dict[str, str]:
|
| 77 |
"""
|
| 78 |
Generate mobile banner using Gemini and upload to Reach platform.
|
|
@@ -85,11 +86,11 @@ def generate_mobile_banner(
|
|
| 85 |
logger.info(f"Starting mobile banner generation with ID: {brand_name}")
|
| 86 |
all_banner_results = []
|
| 87 |
|
| 88 |
-
prompt_text = get_mobile_prompt(prompt, brand_details)
|
| 89 |
for variation in range(1, 3): # Generate two variations
|
| 90 |
try:
|
| 91 |
response = client.models.generate_content(
|
| 92 |
-
model="gemini-2.0-flash-
|
| 93 |
contents=prompt_text,
|
| 94 |
config=types.GenerateContentConfig(response_modalities=["TEXT", "IMAGE"])
|
| 95 |
)
|
|
|
|
| 13 |
logger = logging.getLogger(__name__)
|
| 14 |
|
| 15 |
def get_mobile_prompt(
|
| 16 |
+
prompt: str, brand_details: str, primary_color: str
|
| 17 |
) -> str:
|
| 18 |
return f'''
|
| 19 |
+
Based on the prompt: {prompt}
|
| 20 |
|
| 21 |
Create an realistic image that reflects this brand:
|
| 22 |
{brand_details}
|
| 23 |
+
|
| 24 |
+
Exclude using the color {primary_color} in the palette. The image must be professional and realistic, and must not contain any text, typographic or alphanumeric elements.
|
| 25 |
|
|
|
|
| 26 |
'''
|
| 27 |
|
| 28 |
def process_image(image_data: bytes, target_width: int, target_height: int) -> bytes:
|
|
|
|
| 72 |
|
| 73 |
return buffer.getvalue()
|
| 74 |
|
| 75 |
+
def generate_mobile_banner_v2(
|
| 76 |
+
prompt: str, brand_details: str, primary_color: str
|
| 77 |
) -> Dict[str, str]:
|
| 78 |
"""
|
| 79 |
Generate mobile banner using Gemini and upload to Reach platform.
|
|
|
|
| 86 |
logger.info(f"Starting mobile banner generation with ID: {brand_name}")
|
| 87 |
all_banner_results = []
|
| 88 |
|
| 89 |
+
prompt_text = get_mobile_prompt(prompt, brand_details, primary_color)
|
| 90 |
for variation in range(1, 3): # Generate two variations
|
| 91 |
try:
|
| 92 |
response = client.models.generate_content(
|
| 93 |
+
model="gemini-2.0-flash-preview-image-generation",
|
| 94 |
contents=prompt_text,
|
| 95 |
config=types.GenerateContentConfig(response_modalities=["TEXT", "IMAGE"])
|
| 96 |
)
|
app/services/custom_byop_service.py
CHANGED
|
@@ -28,12 +28,11 @@ def get_custom_byop_prompts(
|
|
| 28 |
str: Prompt to send to the image generation API.
|
| 29 |
"""
|
| 30 |
return f'''
|
| 31 |
-
{prompt}
|
| 32 |
|
| 33 |
-
Create an realistic image that reflects this brand:
|
| 34 |
{brand_details}
|
| 35 |
|
| 36 |
-
The image must be professional and realistic, and must not contain any text, typographic or alphanumeric elements.
|
| 37 |
'''
|
| 38 |
|
| 39 |
|
|
@@ -141,7 +140,7 @@ def generate_custom_byop_banner(
|
|
| 141 |
try:
|
| 142 |
# Request image generation from Gemini API
|
| 143 |
response = client.models.generate_content(
|
| 144 |
-
model="gemini-2.0-flash-
|
| 145 |
contents=prompt_text,
|
| 146 |
config=types.GenerateContentConfig(
|
| 147 |
response_modalities=['TEXT', 'IMAGE']
|
|
|
|
| 28 |
str: Prompt to send to the image generation API.
|
| 29 |
"""
|
| 30 |
return f'''
|
| 31 |
+
{prompt} for a brand:
|
| 32 |
|
|
|
|
| 33 |
{brand_details}
|
| 34 |
|
| 35 |
+
Add elements like phones and connectivity. The image must be professional and realistic, and must not contain any text, typographic or alphanumeric elements.
|
| 36 |
'''
|
| 37 |
|
| 38 |
|
|
|
|
| 140 |
try:
|
| 141 |
# Request image generation from Gemini API
|
| 142 |
response = client.models.generate_content(
|
| 143 |
+
model="gemini-2.0-flash-preview-image-generation",
|
| 144 |
contents=prompt_text,
|
| 145 |
config=types.GenerateContentConfig(
|
| 146 |
response_modalities=['TEXT', 'IMAGE']
|
app/services/custom_network_service.py
CHANGED
|
@@ -17,12 +17,11 @@ def get_custom_network_prompts(
|
|
| 17 |
prompt: str, brand_details: str
|
| 18 |
) -> str:
|
| 19 |
return f'''
|
| 20 |
-
{prompt}
|
| 21 |
|
| 22 |
-
Create an realistic image that reflects this brand:
|
| 23 |
{brand_details}
|
| 24 |
|
| 25 |
-
The image must be professional and realistic, and must not contain any text, typographic or alphanumeric elements.
|
| 26 |
'''
|
| 27 |
|
| 28 |
def process_image(image_data: bytes, width: int = 530, height: int = 352) -> bytes:
|
|
@@ -126,7 +125,7 @@ def generate_custom_network_banner(
|
|
| 126 |
banner_result = None
|
| 127 |
try:
|
| 128 |
response = client.models.generate_content(
|
| 129 |
-
model="gemini-2.0-flash-
|
| 130 |
contents=prompt_text,
|
| 131 |
config=types.GenerateContentConfig(
|
| 132 |
response_modalities=['TEXT', 'IMAGE']
|
|
@@ -178,4 +177,4 @@ def generate_custom_network_banner(
|
|
| 178 |
error_msg = "No images were generated for network banners"
|
| 179 |
logger.error(error_msg)
|
| 180 |
raise Exception(error_msg)
|
| 181 |
-
return {"variations": all_banner_results}
|
|
|
|
| 17 |
prompt: str, brand_details: str
|
| 18 |
) -> str:
|
| 19 |
return f'''
|
| 20 |
+
{prompt} for a brand:
|
| 21 |
|
|
|
|
| 22 |
{brand_details}
|
| 23 |
|
| 24 |
+
Add elements connection towers, showing themes of connections. The image must be professional and realistic, and must not contain any text, typographic or alphanumeric elements.
|
| 25 |
'''
|
| 26 |
|
| 27 |
def process_image(image_data: bytes, width: int = 530, height: int = 352) -> bytes:
|
|
|
|
| 125 |
banner_result = None
|
| 126 |
try:
|
| 127 |
response = client.models.generate_content(
|
| 128 |
+
model="gemini-2.0-flash-preview-image-generation",
|
| 129 |
contents=prompt_text,
|
| 130 |
config=types.GenerateContentConfig(
|
| 131 |
response_modalities=['TEXT', 'IMAGE']
|
|
|
|
| 177 |
error_msg = "No images were generated for network banners"
|
| 178 |
logger.error(error_msg)
|
| 179 |
raise Exception(error_msg)
|
| 180 |
+
return {"variations": all_banner_results}
|
app/services/logo_service.py
CHANGED
|
@@ -34,7 +34,6 @@ def get_logo_prompts(
|
|
| 34 |
return [
|
| 35 |
f'''Create a graphic, abstract icon that visually conveys the essence and feel of the brand '{brand_name}', while also clearly suggesting involvement in the {domain} field. {color_scheme}
|
| 36 |
Strict requirements:
|
| 37 |
-
- The ratio must be 1024:384
|
| 38 |
- The icon must be entirely visual and abstract.
|
| 39 |
- Absolutely no text, letters, numbers, symbols, or any written elements of any kind should appear in the image.
|
| 40 |
- The image should not contain any watermark, signature, or typographic marks.
|
|
@@ -77,17 +76,17 @@ def optimize_logo_image(image: Image.Image) -> Image.Image:
|
|
| 77 |
Resize and optimize the logo image to meet specifications:
|
| 78 |
- Width: 120px
|
| 79 |
- Height: 45px
|
| 80 |
-
- File size: up to
|
| 81 |
"""
|
| 82 |
# Resize image to specified dimensions
|
| 83 |
resized_image = image.resize((120, 45), Image.Resampling.LANCZOS)
|
| 84 |
|
| 85 |
-
# Start with high quality and reduce until file size is under
|
| 86 |
quality = 95
|
| 87 |
while True:
|
| 88 |
buffer = io.BytesIO()
|
| 89 |
resized_image.save(buffer, format='PNG', optimize=True, quality=quality)
|
| 90 |
-
if len(buffer.getvalue()) <=
|
| 91 |
break
|
| 92 |
quality -= 5
|
| 93 |
|
|
|
|
| 34 |
return [
|
| 35 |
f'''Create a graphic, abstract icon that visually conveys the essence and feel of the brand '{brand_name}', while also clearly suggesting involvement in the {domain} field. {color_scheme}
|
| 36 |
Strict requirements:
|
|
|
|
| 37 |
- The icon must be entirely visual and abstract.
|
| 38 |
- Absolutely no text, letters, numbers, symbols, or any written elements of any kind should appear in the image.
|
| 39 |
- The image should not contain any watermark, signature, or typographic marks.
|
|
|
|
| 76 |
Resize and optimize the logo image to meet specifications:
|
| 77 |
- Width: 120px
|
| 78 |
- Height: 45px
|
| 79 |
+
- File size: up to 30KB
|
| 80 |
"""
|
| 81 |
# Resize image to specified dimensions
|
| 82 |
resized_image = image.resize((120, 45), Image.Resampling.LANCZOS)
|
| 83 |
|
| 84 |
+
# Start with high quality and reduce until file size is under 30KB
|
| 85 |
quality = 95
|
| 86 |
while True:
|
| 87 |
buffer = io.BytesIO()
|
| 88 |
resized_image.save(buffer, format='PNG', optimize=True, quality=quality)
|
| 89 |
+
if len(buffer.getvalue()) <= 30720 or quality <= 5: # 30KB = 30720 bytes
|
| 90 |
break
|
| 91 |
quality -= 5
|
| 92 |
|
app/services/network_unsplash_desktop_service.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import random
|
| 3 |
+
from typing import Dict
|
| 4 |
+
import requests
|
| 5 |
+
from app.config.settings import settings
|
| 6 |
+
from app.utils.reach_upload import upload_to_reach
|
| 7 |
+
from PIL import Image, ImageEnhance, ImageOps
|
| 8 |
+
from io import BytesIO
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
logger.setLevel(logging.INFO)
|
| 12 |
+
|
| 13 |
+
UNSPLASH_API_KEY = settings.UNSPLASH_API_KEY
|
| 14 |
+
UNSPLASH_BASE_URL = "https://api.unsplash.com"
|
| 15 |
+
|
| 16 |
+
def process_image(image_data: bytes, target_width: int, target_height: int) -> bytes:
|
| 17 |
+
img = Image.open(BytesIO(image_data)).convert("RGB")
|
| 18 |
+
intermediate_size = (target_width * 4, target_height * 4)
|
| 19 |
+
upscaled = ImageOps.fit(img, intermediate_size, method=Image.LANCZOS, centering=(0.5, 0.5))
|
| 20 |
+
upscaled = ImageEnhance.Sharpness(upscaled).enhance(1.3)
|
| 21 |
+
upscaled = ImageEnhance.Contrast(upscaled).enhance(1.1)
|
| 22 |
+
final = ImageOps.fit(upscaled, (target_width, target_height), method=Image.LANCZOS, centering=(0.5, 0.5))
|
| 23 |
+
final = ImageEnhance.Sharpness(final).enhance(1.1)
|
| 24 |
+
final = ImageEnhance.Color(final).enhance(1.1)
|
| 25 |
+
buffer = BytesIO()
|
| 26 |
+
quality = 95
|
| 27 |
+
while True:
|
| 28 |
+
buffer.seek(0)
|
| 29 |
+
buffer.truncate()
|
| 30 |
+
final.save(buffer, format="JPEG", quality=quality, optimize=True, progressive=True, subsampling=0 if quality >= 90 else 1)
|
| 31 |
+
if buffer.tell() <= 500 * 1024 or quality <= 80:
|
| 32 |
+
break
|
| 33 |
+
quality -= 3
|
| 34 |
+
return buffer.getvalue()
|
| 35 |
+
|
| 36 |
+
def get_unsplash_network_desktop_images(query: str) -> Dict:
|
| 37 |
+
headers = {"Authorization": f"Client-ID {UNSPLASH_API_KEY}"}
|
| 38 |
+
search_url = f"{UNSPLASH_BASE_URL}/search/photos"
|
| 39 |
+
random_page = random.randint(1, 10)
|
| 40 |
+
params = {"query": query, "per_page": 2, "orientation": "landscape", "page": random_page, "order_by": "random", "content_filter": "high"}
|
| 41 |
+
logger.info(f"Fetching Unsplash images for query: '{query}', page: {random_page}")
|
| 42 |
+
response = requests.get(search_url, headers=headers, params=params)
|
| 43 |
+
if response.status_code != 200:
|
| 44 |
+
logger.error(f"Unsplash API error: {response.status_code} - {response.text}")
|
| 45 |
+
raise Exception("Failed to fetch images from Unsplash")
|
| 46 |
+
results = response.json().get("results", [])
|
| 47 |
+
all_image_results = []
|
| 48 |
+
for idx, image in enumerate(results, start=1):
|
| 49 |
+
try:
|
| 50 |
+
image_url = image["urls"]["regular"]
|
| 51 |
+
img_response = requests.get(image_url)
|
| 52 |
+
if img_response.status_code != 200:
|
| 53 |
+
logger.warning(f"Failed to download image {idx} from Unsplash")
|
| 54 |
+
continue
|
| 55 |
+
image_data = img_response.content
|
| 56 |
+
processed_image = process_image(image_data, 520, 352)
|
| 57 |
+
result = upload_to_reach(
|
| 58 |
+
processed_image,
|
| 59 |
+
f"network_unsplash_desktop_banner_v{idx}",
|
| 60 |
+
"jpeg",
|
| 61 |
+
idx,
|
| 62 |
+
'BEST_NETWORK_IMAGE'
|
| 63 |
+
)
|
| 64 |
+
all_image_results.append({
|
| 65 |
+
"variation": idx,
|
| 66 |
+
"banner": result['url']
|
| 67 |
+
})
|
| 68 |
+
logger.info(f"Processed and uploaded Unsplash desktop image variation {idx}")
|
| 69 |
+
except Exception as e:
|
| 70 |
+
logger.error(f"Error processing image {idx}: {str(e)}")
|
| 71 |
+
continue
|
| 72 |
+
if not all_image_results:
|
| 73 |
+
logger.error("No images were processed successfully from Unsplash")
|
| 74 |
+
raise Exception("No images were processed successfully")
|
| 75 |
+
return {"variations": all_image_results}
|
app/services/network_unsplash_ipad_service.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import random
|
| 3 |
+
from typing import Dict
|
| 4 |
+
import requests
|
| 5 |
+
from app.config.settings import settings
|
| 6 |
+
from app.utils.reach_upload import upload_to_reach
|
| 7 |
+
from PIL import Image, ImageEnhance, ImageOps
|
| 8 |
+
from io import BytesIO
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
logger.setLevel(logging.INFO)
|
| 12 |
+
|
| 13 |
+
UNSPLASH_API_KEY = settings.UNSPLASH_API_KEY
|
| 14 |
+
UNSPLASH_BASE_URL = "https://api.unsplash.com"
|
| 15 |
+
|
| 16 |
+
def process_image(image_data: bytes, target_width: int, target_height: int) -> bytes:
|
| 17 |
+
img = Image.open(BytesIO(image_data)).convert("RGB")
|
| 18 |
+
intermediate_size = (target_width * 4, target_height * 4)
|
| 19 |
+
upscaled = ImageOps.fit(img, intermediate_size, method=Image.LANCZOS, centering=(0.5, 0.5))
|
| 20 |
+
upscaled = ImageEnhance.Sharpness(upscaled).enhance(1.3)
|
| 21 |
+
upscaled = ImageEnhance.Contrast(upscaled).enhance(1.1)
|
| 22 |
+
final = ImageOps.fit(upscaled, (target_width, target_height), method=Image.LANCZOS, centering=(0.5, 0.5))
|
| 23 |
+
final = ImageEnhance.Sharpness(final).enhance(1.1)
|
| 24 |
+
final = ImageEnhance.Color(final).enhance(1.1)
|
| 25 |
+
buffer = BytesIO()
|
| 26 |
+
quality = 95
|
| 27 |
+
while True:
|
| 28 |
+
buffer.seek(0)
|
| 29 |
+
buffer.truncate()
|
| 30 |
+
final.save(buffer, format="JPEG", quality=quality, optimize=True, progressive=True, subsampling=0 if quality >= 90 else 1)
|
| 31 |
+
if buffer.tell() <= 500 * 1024 or quality <= 80:
|
| 32 |
+
break
|
| 33 |
+
quality -= 3
|
| 34 |
+
return buffer.getvalue()
|
| 35 |
+
|
| 36 |
+
def get_unsplash_network_ipad_images(query: str) -> Dict:
|
| 37 |
+
headers = {"Authorization": f"Client-ID {UNSPLASH_API_KEY}"}
|
| 38 |
+
search_url = f"{UNSPLASH_BASE_URL}/search/photos"
|
| 39 |
+
random_page = random.randint(1, 10)
|
| 40 |
+
params = {"query": query, "per_page": 2, "orientation": "landscape", "page": random_page, "order_by": "random", "content_filter": "high"}
|
| 41 |
+
logger.info(f"Fetching Unsplash images for query: '{query}', page: {random_page}")
|
| 42 |
+
response = requests.get(search_url, headers=headers, params=params)
|
| 43 |
+
if response.status_code != 200:
|
| 44 |
+
logger.error(f"Unsplash API error: {response.status_code} - {response.text}")
|
| 45 |
+
raise Exception("Failed to fetch images from Unsplash")
|
| 46 |
+
results = response.json().get("results", [])
|
| 47 |
+
all_image_results = []
|
| 48 |
+
for idx, image in enumerate(results, start=1):
|
| 49 |
+
try:
|
| 50 |
+
image_url = image["urls"]["regular"]
|
| 51 |
+
img_response = requests.get(image_url)
|
| 52 |
+
if img_response.status_code != 0:
|
| 53 |
+
logger.warning(f"Failed to download image {idx} from Unsplash")
|
| 54 |
+
continue
|
| 55 |
+
image_data = img_response.content
|
| 56 |
+
processed_image = process_image(image_data, 768, 500)
|
| 57 |
+
result = upload_to_reach(
|
| 58 |
+
processed_image,
|
| 59 |
+
f"network_unsplash_ipad_banner_v{idx}",
|
| 60 |
+
"jpeg",
|
| 61 |
+
idx,
|
| 62 |
+
'BEST_NETWORK_IMAGE'
|
| 63 |
+
)
|
| 64 |
+
all_image_results.append({
|
| 65 |
+
"variation": idx,
|
| 66 |
+
"banner": result['url']
|
| 67 |
+
})
|
| 68 |
+
logger.info(f"Processed and uploaded Unsplash iPad image variation {idx}")
|
| 69 |
+
except Exception as e:
|
| 70 |
+
logger.error(f"Error processing image {idx}: {str(e)}")
|
| 71 |
+
continue
|
| 72 |
+
if not all_image_results:
|
| 73 |
+
logger.error("No images were processed successfully from Unsplash")
|
| 74 |
+
raise Exception("No images were processed successfully")
|
| 75 |
+
return {"variations": all_image_results}
|
app/services/network_unsplash_mobile_service.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import random
|
| 3 |
+
from typing import Dict
|
| 4 |
+
import requests
|
| 5 |
+
from app.config.settings import settings
|
| 6 |
+
from app.utils.reach_upload import upload_to_reach
|
| 7 |
+
from PIL import Image, ImageEnhance, ImageOps
|
| 8 |
+
from io import BytesIO
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
logger.setLevel(logging.INFO)
|
| 12 |
+
|
| 13 |
+
UNSPLASH_API_KEY = settings.UNSPLASH_API_KEY
|
| 14 |
+
UNSPLASH_BASE_URL = "https://api.unsplash.com"
|
| 15 |
+
|
| 16 |
+
def process_image(image_data: bytes, target_width: int, target_height: int) -> bytes:
|
| 17 |
+
img = Image.open(BytesIO(image_data)).convert("RGB")
|
| 18 |
+
intermediate_size = (target_width * 4, target_height * 4)
|
| 19 |
+
upscaled = ImageOps.fit(img, intermediate_size, method=Image.LANCZOS, centering=(0.5, 0.5))
|
| 20 |
+
upscaled = ImageEnhance.Sharpness(upscaled).enhance(1.3)
|
| 21 |
+
upscaled = ImageEnhance.Contrast(upscaled).enhance(1.1)
|
| 22 |
+
final = ImageOps.fit(upscaled, (target_width, target_height), method=Image.LANCZOS, centering=(0.5, 0.5))
|
| 23 |
+
final = ImageEnhance.Sharpness(final).enhance(1.1)
|
| 24 |
+
final = ImageEnhance.Color(final).enhance(1.1)
|
| 25 |
+
buffer = BytesIO()
|
| 26 |
+
quality = 95
|
| 27 |
+
while True:
|
| 28 |
+
buffer.seek(0)
|
| 29 |
+
buffer.truncate()
|
| 30 |
+
final.save(buffer, format="JPEG", quality=quality, optimize=True, progressive=True, subsampling=0 if quality >= 90 else 1)
|
| 31 |
+
if buffer.tell() <= 500 * 1024 or quality <= 80:
|
| 32 |
+
break
|
| 33 |
+
quality -= 3
|
| 34 |
+
return buffer.getvalue()
|
| 35 |
+
|
| 36 |
+
def get_unsplash_network_mobile_images(query: str) -> Dict:
|
| 37 |
+
headers = {"Authorization": f"Client-ID {UNSPLASH_API_KEY}"}
|
| 38 |
+
search_url = f"{UNSPLASH_BASE_URL}/search/photos"
|
| 39 |
+
random_page = random.randint(1, 10)
|
| 40 |
+
params = {"query": query, "per_page": 2, "orientation": "landscape", "page": random_page, "order_by": "random", "content_filter": "high"}
|
| 41 |
+
logger.info(f"Fetching Unsplash images for query: '{query}', page: {random_page}")
|
| 42 |
+
response = requests.get(search_url, headers=headers, params=params)
|
| 43 |
+
if response.status_code != 200:
|
| 44 |
+
logger.error(f"Unsplash API error: {response.status_code} - {response.text}")
|
| 45 |
+
raise Exception("Failed to fetch images from Unsplash")
|
| 46 |
+
results = response.json().get("results", [])
|
| 47 |
+
all_image_results = []
|
| 48 |
+
for idx, image in enumerate(results, start=1):
|
| 49 |
+
try:
|
| 50 |
+
image_url = image["urls"]["regular"]
|
| 51 |
+
img_response = requests.get(image_url)
|
| 52 |
+
if img_response.status_code != 200:
|
| 53 |
+
logger.warning(f"Failed to download image {idx} from Unsplash")
|
| 54 |
+
continue
|
| 55 |
+
image_data = img_response.content
|
| 56 |
+
processed_image = process_image(image_data, 375, 500)
|
| 57 |
+
result = upload_to_reach(
|
| 58 |
+
processed_image,
|
| 59 |
+
f"network_unsplash_mobile_banner_v{idx}",
|
| 60 |
+
"jpeg",
|
| 61 |
+
idx,
|
| 62 |
+
'BEST_NETWORK_IMAGE'
|
| 63 |
+
)
|
| 64 |
+
all_image_results.append({
|
| 65 |
+
"variation": idx,
|
| 66 |
+
"banner": result['url']
|
| 67 |
+
})
|
| 68 |
+
logger.info(f"Processed and uploaded Unsplash mobile image variation {idx}")
|
| 69 |
+
except Exception as e:
|
| 70 |
+
logger.error(f"Error processing image {idx}: {str(e)}")
|
| 71 |
+
continue
|
| 72 |
+
if not all_image_results:
|
| 73 |
+
logger.error("No images were processed successfully from Unsplash")
|
| 74 |
+
raise Exception("No images were processed successfully")
|
| 75 |
+
return {"variations": all_image_results}
|
app/services/single_icon_logo_service.py
CHANGED
|
@@ -63,7 +63,7 @@ def generate_single_icon_logo(
|
|
| 63 |
logger.info(f"Generating single icon logo for brand: {brand_name}")
|
| 64 |
try:
|
| 65 |
response = client.models.generate_content(
|
| 66 |
-
model="gemini-2.0-flash-
|
| 67 |
contents=prompt,
|
| 68 |
config=types.GenerateContentConfig(response_modalities=['TEXT', 'IMAGE'])
|
| 69 |
)
|
|
|
|
| 63 |
logger.info(f"Generating single icon logo for brand: {brand_name}")
|
| 64 |
try:
|
| 65 |
response = client.models.generate_content(
|
| 66 |
+
model="gemini-2.0-flash-preview-image-generation",
|
| 67 |
contents=prompt,
|
| 68 |
config=types.GenerateContentConfig(response_modalities=['TEXT', 'IMAGE'])
|
| 69 |
)
|
app/services/single_text_logo_service.py
CHANGED
|
@@ -62,7 +62,7 @@ def generate_single_text_logo(
|
|
| 62 |
logger.info(f"Generating single text logo for brand: {brand_name}")
|
| 63 |
try:
|
| 64 |
response = client.models.generate_content(
|
| 65 |
-
model="gemini-2.0-flash-
|
| 66 |
contents=prompt,
|
| 67 |
config=types.GenerateContentConfig(response_modalities=['TEXT', 'IMAGE'])
|
| 68 |
)
|
|
|
|
| 62 |
logger.info(f"Generating single text logo for brand: {brand_name}")
|
| 63 |
try:
|
| 64 |
response = client.models.generate_content(
|
| 65 |
+
model="gemini-2.0-flash-preview-image-generation",
|
| 66 |
contents=prompt,
|
| 67 |
config=types.GenerateContentConfig(response_modalities=['TEXT', 'IMAGE'])
|
| 68 |
)
|
app/services/text_logo_service.py
CHANGED
|
@@ -18,17 +18,17 @@ def optimize_logo_image(image: Image.Image) -> Image.Image:
|
|
| 18 |
Resize and optimize the logo image to meet specifications:
|
| 19 |
- Width: 120px
|
| 20 |
- Height: 45px
|
| 21 |
-
- File size: up to
|
| 22 |
"""
|
| 23 |
# Resize image to specified dimensions
|
| 24 |
resized_image = image.resize((120, 45), Image.Resampling.LANCZOS)
|
| 25 |
|
| 26 |
-
# Start with high quality and reduce until file size is under
|
| 27 |
quality = 95
|
| 28 |
while True:
|
| 29 |
buffer = io.BytesIO()
|
| 30 |
resized_image.save(buffer, format='PNG', optimize=True, quality=quality)
|
| 31 |
-
if len(buffer.getvalue()) <=
|
| 32 |
break
|
| 33 |
quality -= 5
|
| 34 |
|
|
@@ -48,28 +48,28 @@ def get_text_logo_prompts(brand_name: str, domain: str, primary_color: str, seco
|
|
| 48 |
background = f"{tertiary_color} background"
|
| 49 |
|
| 50 |
return [
|
| 51 |
-
f'''Design a sophisticated
|
| 52 |
Use only the brand name as the sole visual element—do not include any icons, symbols, images, shapes, or graphic embellishments of any kind.
|
| 53 |
The logo must feature {text_color} text on a {background}.
|
| 54 |
Employ elegant, modern typography and refined font styling to convey the brand's personality.
|
| 55 |
Focus on creative use of font, spacing, capitalization, and layout to achieve a distinctive and memorable wordmark.
|
| 56 |
No decorative graphics, pictorial elements, or non-text visuals should appear in the design—only stylized text is allowed.
|
| 57 |
The result should be a clean, timeless, and visually striking text logo.''',
|
| 58 |
-
f'''Design a sophisticated
|
| 59 |
Use only the brand name as the sole visual element—do not include any icons, symbols, images, shapes, or graphic embellishments of any kind.
|
| 60 |
The logo must feature {text_color} text on a {background}.
|
| 61 |
Employ elegant, modern typography and refined font styling to convey the brand's personality.
|
| 62 |
Focus on creative use of font, spacing, capitalization, and layout to achieve a distinctive and memorable wordmark.
|
| 63 |
No decorative graphics, pictorial elements, or non-text visuals should appear in the design—only stylized text is allowed.
|
| 64 |
The result should be a clean, timeless, and visually striking text logo.''',
|
| 65 |
-
f'''Design a sophisticated
|
| 66 |
Use only the brand name as the sole visual element—do not include any icons, symbols, images, shapes, or graphic embellishments of any kind.
|
| 67 |
The logo must feature {text_color} text on a {background}.
|
| 68 |
Employ elegant, modern typography and refined font styling to convey the brand's personality.
|
| 69 |
Focus on creative use of font, spacing, capitalization, and layout to achieve a distinctive and memorable wordmark.
|
| 70 |
No decorative graphics, pictorial elements, or non-text visuals should appear in the design—only stylized text is allowed.
|
| 71 |
The result should be a clean, timeless, and visually striking text logo.''',
|
| 72 |
-
f'''Design a sophisticated
|
| 73 |
Use only the brand name as the sole visual element—do not include any icons, symbols, images, shapes, or graphic embellishments of any kind.
|
| 74 |
The logo must feature {text_color} text on a {background}.
|
| 75 |
Employ elegant, modern typography and refined font styling to convey the brand's personality.
|
|
@@ -102,7 +102,7 @@ def generate_text_logos(
|
|
| 102 |
logger.info(f"Generating logo variation {idx} using Gemini model.")
|
| 103 |
try:
|
| 104 |
response = client.models.generate_content(
|
| 105 |
-
model="gemini-2.0-flash-
|
| 106 |
contents=prompt,
|
| 107 |
config=types.GenerateContentConfig(
|
| 108 |
response_modalities=['TEXT', 'IMAGE']
|
|
|
|
| 18 |
Resize and optimize the logo image to meet specifications:
|
| 19 |
- Width: 120px
|
| 20 |
- Height: 45px
|
| 21 |
+
- File size: up to 30KB
|
| 22 |
"""
|
| 23 |
# Resize image to specified dimensions
|
| 24 |
resized_image = image.resize((120, 45), Image.Resampling.LANCZOS)
|
| 25 |
|
| 26 |
+
# Start with high quality and reduce until file size is under 30KB
|
| 27 |
quality = 95
|
| 28 |
while True:
|
| 29 |
buffer = io.BytesIO()
|
| 30 |
resized_image.save(buffer, format='PNG', optimize=True, quality=quality)
|
| 31 |
+
if len(buffer.getvalue()) <= 30720 or quality <= 5: # 30KB = 30720 bytes
|
| 32 |
break
|
| 33 |
quality -= 5
|
| 34 |
|
|
|
|
| 48 |
background = f"{tertiary_color} background"
|
| 49 |
|
| 50 |
return [
|
| 51 |
+
f'''Design a sophisticated 4:3 text-only logo for {brand_name}.
|
| 52 |
Use only the brand name as the sole visual element—do not include any icons, symbols, images, shapes, or graphic embellishments of any kind.
|
| 53 |
The logo must feature {text_color} text on a {background}.
|
| 54 |
Employ elegant, modern typography and refined font styling to convey the brand's personality.
|
| 55 |
Focus on creative use of font, spacing, capitalization, and layout to achieve a distinctive and memorable wordmark.
|
| 56 |
No decorative graphics, pictorial elements, or non-text visuals should appear in the design—only stylized text is allowed.
|
| 57 |
The result should be a clean, timeless, and visually striking text logo.''',
|
| 58 |
+
f'''Design a sophisticated 4:3 text-only logo for {brand_name}.
|
| 59 |
Use only the brand name as the sole visual element—do not include any icons, symbols, images, shapes, or graphic embellishments of any kind.
|
| 60 |
The logo must feature {text_color} text on a {background}.
|
| 61 |
Employ elegant, modern typography and refined font styling to convey the brand's personality.
|
| 62 |
Focus on creative use of font, spacing, capitalization, and layout to achieve a distinctive and memorable wordmark.
|
| 63 |
No decorative graphics, pictorial elements, or non-text visuals should appear in the design—only stylized text is allowed.
|
| 64 |
The result should be a clean, timeless, and visually striking text logo.''',
|
| 65 |
+
f'''Design a sophisticated 4:3 text-only logo for {brand_name}.
|
| 66 |
Use only the brand name as the sole visual element—do not include any icons, symbols, images, shapes, or graphic embellishments of any kind.
|
| 67 |
The logo must feature {text_color} text on a {background}.
|
| 68 |
Employ elegant, modern typography and refined font styling to convey the brand's personality.
|
| 69 |
Focus on creative use of font, spacing, capitalization, and layout to achieve a distinctive and memorable wordmark.
|
| 70 |
No decorative graphics, pictorial elements, or non-text visuals should appear in the design—only stylized text is allowed.
|
| 71 |
The result should be a clean, timeless, and visually striking text logo.''',
|
| 72 |
+
f'''Design a sophisticated 4:3 text-only logo for {brand_name}.
|
| 73 |
Use only the brand name as the sole visual element—do not include any icons, symbols, images, shapes, or graphic embellishments of any kind.
|
| 74 |
The logo must feature {text_color} text on a {background}.
|
| 75 |
Employ elegant, modern typography and refined font styling to convey the brand's personality.
|
|
|
|
| 102 |
logger.info(f"Generating logo variation {idx} using Gemini model.")
|
| 103 |
try:
|
| 104 |
response = client.models.generate_content(
|
| 105 |
+
model="gemini-2.0-flash-preview-image-generation",
|
| 106 |
contents=prompt,
|
| 107 |
config=types.GenerateContentConfig(
|
| 108 |
response_modalities=['TEXT', 'IMAGE']
|
app/services/upload_image_service.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
from typing import Dict
|
| 3 |
+
from fastapi import UploadFile
|
| 4 |
+
|
| 5 |
+
from app.utils.reach_upload import upload_to_reach
|
| 6 |
+
|
| 7 |
+
# Configure logging
|
| 8 |
+
logging.basicConfig(level=logging.INFO)
|
| 9 |
+
logger = logging.getLogger(__name__)
|
| 10 |
+
|
| 11 |
+
def get_file_extension(filename: str) -> str:
|
| 12 |
+
return filename.split('.')[-1].lower()
|
| 13 |
+
|
| 14 |
+
async def upload_file_as_is(file: UploadFile, file_type: str) -> Dict:
|
| 15 |
+
"""
|
| 16 |
+
Upload the file as-is to the Reach platform without any processing.
|
| 17 |
+
|
| 18 |
+
Args:
|
| 19 |
+
file: UploadFile object
|
| 20 |
+
file_type: str, the type of file to be sent to upload_to_reach
|
| 21 |
+
|
| 22 |
+
Returns:
|
| 23 |
+
Dict containing the upload result with URL
|
| 24 |
+
"""
|
| 25 |
+
try:
|
| 26 |
+
# Read file content as-is
|
| 27 |
+
file_data = await file.read()
|
| 28 |
+
|
| 29 |
+
# Extract file extension (e.g., png, jpg, jpeg)
|
| 30 |
+
file_ext = get_file_extension(file.filename)
|
| 31 |
+
|
| 32 |
+
# Upload directly to Reach platform with correct file type
|
| 33 |
+
result = upload_to_reach(file_data, file.filename, file_ext, 1, file_type=file_type)
|
| 34 |
+
|
| 35 |
+
logger.info(f"Successfully uploaded file as-is: {file.filename} with type {file_ext} and file_type {file_type}")
|
| 36 |
+
|
| 37 |
+
return {
|
| 38 |
+
'img_url': result['url']
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
except Exception as e:
|
| 42 |
+
logger.error(f"Error uploading file: {str(e)}", exc_info=True)
|
| 43 |
+
raise Exception(f"Failed to upload file: {str(e)}")
|