utkarsh134 commited on
Commit
0452017
·
verified ·
1 Parent(s): b55a760

Upload 29 files

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