utkarsh134 commited on
Commit
fcfd506
·
verified ·
1 Parent(s): ddbcfaf

Upload 23 files

Browse files
app/services/banner_service.py CHANGED
@@ -11,20 +11,11 @@ from app.utils.reach_upload import upload_to_reach
11
  logger = logging.getLogger(__name__)
12
  logging.basicConfig(level=logging.INFO)
13
 
14
- def get_banner_prompts(brand_name: str, domain: str, primary_color: str) -> Dict[str, list[str]]:
15
  device_prompts = {
16
- 'desktop': [
17
- f"Generate a wide-format banner (1440x500) for {domain} composed solely of abstract shapes, colors, and textures. Use shades that visually oppose {primary_color}. Design for strong horizontal composition and centered core elements. Exclude all forms of text, typography, and alphanumeric symbols.",
18
- f"Generate a wide-format banner (1440x500) for {domain} composed solely of abstract shapes, colors, and textures. Use shades that visually oppose {primary_color}. Design for strong horizontal composition and centered core elements. Exclude all forms of text, typography, and alphanumeric symbols."
19
- ],
20
- 'ipad': [
21
- f"Generate a tablet banner (768x500) for {domain} space. Use shades that visually oppose {primary_color}. No text, writing, letters, numbers, or typographic elements whatsoever. Design for dual-orientation impact with centered visual weight.",
22
- f"Generate a tablet banner (768x500) for {domain} space. Use shades that visually oppose {primary_color}. No text, writing, letters, numbers, or typographic elements whatsoever. Design for dual-orientation impact with centered visual weight."
23
- ],
24
- 'mobile': [
25
- f"Create a banner (375x500) for {domain} sector. Use bold abstract shapes with colors contrasting {primary_color}, with zero text, writing, lettering, numbers, or typographic marks present. Optimize visual hierarchy for narrow vertical viewing.",
26
- f"Create a banner (375x500) for {domain} sector. Use bold abstract shapes with a color palette complementing and contrasting {primary_color}, with zero text, writing, lettering, numbers, or typographic marks present. Optimize visual hierarchy for narrow vertical viewing."
27
- ]
28
  }
29
  return device_prompts
30
 
@@ -83,12 +74,16 @@ def process_images_for_devices(image_data: bytes) -> Dict[str, bytes]:
83
 
84
  def generate_banner(brand_name: str, domain: str, primary_color: str) -> Dict:
85
  """
86
- Generate separate banner images for each device using Gemini and upload to Reach platform.
87
  Returns a dictionary with URLs for different device sizes and prompt variations.
88
  """
89
  api_key = settings.GEMINI_API_KEY
90
  client = genai.Client(api_key=api_key)
91
- device_prompts = get_banner_prompts(brand_name, domain, primary_color)
 
 
 
 
92
  all_banner_results = []
93
 
94
  logger.info(f"Starting banner generation for brand: {brand_name}")
@@ -100,23 +95,24 @@ def generate_banner(brand_name: str, domain: str, primary_color: str) -> Dict:
100
  'mobile': (375, 500)
101
  }
102
 
103
- # Map of device types to their corresponding file types
104
  device_file_types = {
105
  "desktop": "DESKTOP_IMAGE",
106
  "ipad": "IPAD_IMAGE",
107
  "mobile": "WEB_IMAGE"
108
  }
109
 
110
- for prompt_index, _ in enumerate(next(iter(device_prompts.values())), 1):
 
111
  banner_results = {}
112
 
113
- # Generate separate images for each device
114
- for device, prompts in device_prompts.items():
115
- logger.info(f"Generating {device} banner variation {prompt_index}")
116
  try:
117
  response = client.models.generate_content(
118
  model="gemini-2.0-flash-exp-image-generation",
119
- contents=prompts[prompt_index - 1],
120
  config=types.GenerateContentConfig(response_modalities=['TEXT', 'IMAGE'])
121
  )
122
 
@@ -135,36 +131,38 @@ def generate_banner(brand_name: str, domain: str, primary_color: str) -> Dict:
135
  else:
136
  image_format = "jpeg"
137
 
138
- logger.info(f"Processing {device} banner image from variation {prompt_index} (format: {image_format})")
139
 
140
- # Process image for current device
141
  width, height = device_dimensions[device]
142
  processed_image = process_image(image_data, width, height)
143
 
144
- # Upload to Reach platform
145
  result = upload_to_reach(
146
  processed_image,
147
- f"banner_{brand_name}_{device}_v{prompt_index}",
148
  image_format,
149
- prompt_index,
150
  device_file_types[device]
151
  )
152
  banner_results[device] = result['url']
153
 
154
- logger.info(f"{device} banner variation {prompt_index} uploaded successfully.")
155
 
156
  except Exception as error:
157
- logger.error(f"Error processing {device} banner for variation {prompt_index}: {str(error)}")
158
  raise
159
 
 
 
 
 
160
  all_banner_results.append({
161
- "variation": prompt_index,
162
  "banners": banner_results
163
  })
164
 
165
- if not all_banner_results:
166
- logger.error("No images were generated.")
167
- raise Exception("No images were generated")
168
 
169
- logger.info("Banner generation complete.")
170
- return {"variations": all_banner_results}
 
11
  logger = logging.getLogger(__name__)
12
  logging.basicConfig(level=logging.INFO)
13
 
14
+ def get_banner_prompts(brand_name: str, domain: str, primary_color: str) -> Dict[str, str]:
15
  device_prompts = {
16
+ 'desktop': f"Generate a realistic image which includes real people and shows the essence of the domain {domain}. Use shades that oppose the color {primary_color}. Do not Include any text, typographic or Alphanumeric Elements.",
17
+ 'ipad': f"Generate a realistic image which includes real people and shows the essence of the domain {domain}. Use shades that oppose the color {primary_color}. Do not Include any text, typographic or Alphanumeric Elements.",
18
+ 'mobile': f"Generate a realistic image which includes real people and shows the essence of the domain {domain}. Use shades that oppose the color {primary_color}. Do not Include any text, typographic or Alphanumeric Elements."
 
 
 
 
 
 
 
 
 
19
  }
20
  return device_prompts
21
 
 
74
 
75
  def generate_banner(brand_name: str, domain: str, primary_color: str) -> Dict:
76
  """
77
+ Generate multiple variations of banner images for each device using Gemini and upload to Reach platform.
78
  Returns a dictionary with URLs for different device sizes and prompt variations.
79
  """
80
  api_key = settings.GEMINI_API_KEY
81
  client = genai.Client(api_key=api_key)
82
+
83
+ # For now, we just create one prompt set — extendable later
84
+ base_prompt = get_banner_prompts(brand_name, domain, primary_color)
85
+ all_prompt_sets = [base_prompt] # Add more prompt sets for more variations
86
+
87
  all_banner_results = []
88
 
89
  logger.info(f"Starting banner generation for brand: {brand_name}")
 
95
  'mobile': (375, 500)
96
  }
97
 
98
+ # File types used for uploading
99
  device_file_types = {
100
  "desktop": "DESKTOP_IMAGE",
101
  "ipad": "IPAD_IMAGE",
102
  "mobile": "WEB_IMAGE"
103
  }
104
 
105
+ # Loop through all variations of prompt sets
106
+ for variation_index, device_prompts in enumerate(all_prompt_sets, start=1):
107
  banner_results = {}
108
 
109
+ for device, prompt in device_prompts.items():
110
+ logger.info(f"Generating variation {variation_index}, device: {device}")
111
+
112
  try:
113
  response = client.models.generate_content(
114
  model="gemini-2.0-flash-exp-image-generation",
115
+ contents=prompt,
116
  config=types.GenerateContentConfig(response_modalities=['TEXT', 'IMAGE'])
117
  )
118
 
 
131
  else:
132
  image_format = "jpeg"
133
 
134
+ logger.info(f"Processing image for {device} in variation {variation_index}")
135
 
136
+ # Resize and enhance
137
  width, height = device_dimensions[device]
138
  processed_image = process_image(image_data, width, height)
139
 
140
+ # Upload to Reach
141
  result = upload_to_reach(
142
  processed_image,
143
+ f"banner_{brand_name}_{device}_v{variation_index}",
144
  image_format,
145
+ 1,
146
  device_file_types[device]
147
  )
148
  banner_results[device] = result['url']
149
 
150
+ logger.info(f"{device} banner uploaded successfully for variation {variation_index}")
151
 
152
  except Exception as error:
153
+ logger.error(f"Error processing {device} banner in variation {variation_index}: {str(error)}")
154
  raise
155
 
156
+ if not banner_results:
157
+ logger.error(f"No images were generated for variation {variation_index}")
158
+ raise Exception(f"No images were generated for variation {variation_index}")
159
+
160
  all_banner_results.append({
161
+ "variation": variation_index,
162
  "banners": banner_results
163
  })
164
 
165
+ logger.info("All banner variations generated successfully.")
166
+ return {"variations": all_banner_results}
167
+
168
 
 
 
app/services/bestnetwork_service.py CHANGED
@@ -14,11 +14,8 @@ logger = logging.getLogger(__name__)
14
  logging.basicConfig(level=logging.INFO)
15
 
16
  def get_network_prompts(brand_name: str, domain: str) -> list[str]:
17
- prompts = [
18
- f"Generate a powerful abstract banner for a brand, operating in the {domain} sector. Create a sophisticated visual composition using a modern color scheme that emphasizes reliability and strength. The design should be optimized for 530x352 dimensions while maintaining clarity and visual balance. DO NOT USE TEXT, LETTERS, NUMBERS, OR TYPOGRAPHIC ELEMENTS. USE ONLY VISUAL ELEMENTS."
19
- f"Design an impactful banner for a brand in the {domain} industry. Create a bold, abstract representation . Incorporate subtle depth and dimension. Ensure the design is effective at 530x352 resolution. DO NOT INCLUDE ANY TEXT IN THE IMAGE. "
20
- ]
21
- return prompts
22
 
23
  def process_image(image_data: bytes, width: int = 530, height: int = 352) -> bytes:
24
  """
@@ -85,67 +82,64 @@ def generate_network_banner(brand_name: str, domain: str) -> Dict:
85
  """
86
  Generates image banners based on prompts using Gemini API, processes them, uploads to Reach platform,
87
  and returns URLs for the generated variations.
88
- """
89
  logger.info(f"Generating network banners for brand: {brand_name} in domain: {domain}")
90
-
91
  api_key = settings.GEMINI_API_KEY
92
  client = genai.Client(api_key=api_key)
93
- prompts = get_network_prompts(brand_name, domain)
94
  all_banner_results = []
95
 
96
- for prompt_index, prompt in enumerate(prompts, 1):
97
- try:
98
- logger.info(f"Sending prompt {prompt_index} to Gemini API.")
99
- response = client.models.generate_content(
100
- model="gemini-2.0-flash-exp-image-generation",
101
- contents=prompt,
102
- config=types.GenerateContentConfig(
103
- response_modalities=['TEXT', 'IMAGE']
104
- )
105
  )
 
106
 
107
- for part in response.candidates[0].content.parts:
108
- if part.inline_data is not None:
109
- try:
110
- mime_type = part.inline_data.mime_type
111
- image_data = part.inline_data.data
112
-
113
- # Determine format based on MIME type
114
- if "jpeg" in mime_type or "jpg" in mime_type:
115
- image_format = "jpeg"
116
- elif "png" in mime_type:
117
- image_format = "png"
118
- elif "webp" in mime_type:
119
- image_format = "webp"
120
- else:
121
- logger.warning(f"Unknown image format '{mime_type}', defaulting to jpeg.")
122
- image_format = "jpeg"
123
-
124
- # Process and upload image
125
- logger.info(f"Processing image for variation {prompt_index}")
126
- processed_image = process_image(image_data)
127
-
128
- result = upload_to_reach(
129
- processed_image,
130
- f"network_banner_{brand_name}_v{prompt_index}",
131
- image_format,
132
- prompt_index,
133
- 'BEST_NETWORK_IMAGE'
134
- )
135
-
136
- logger.info(f"Uploaded banner variation {prompt_index} successfully.")
137
- all_banner_results.append({
138
- "variation": prompt_index,
139
- "banner": result['url'] # Only use the URL from the response
140
- })
141
-
142
- except Exception as e:
143
- logger.exception(f"Error processing banner image for variation {prompt_index}: {e}")
144
- raise
145
-
146
- except Exception as e:
147
- logger.exception(f"Error generating banner for variation {prompt_index}: {e}")
148
- raise
149
 
150
  if not all_banner_results:
151
  logger.error("No banner images were generated.")
 
14
  logging.basicConfig(level=logging.INFO)
15
 
16
  def get_network_prompts(brand_name: str, domain: str) -> list[str]:
17
+ prompt = f"Generate a realistic representation of the {domain} industry. Use real objects and people . Ensure elements are centered or balanced. DO NOT INCLUDE ANY TEXT IN THE IMAGE."
18
+ return prompt
 
 
 
19
 
20
  def process_image(image_data: bytes, width: int = 530, height: int = 352) -> bytes:
21
  """
 
82
  """
83
  Generates image banners based on prompts using Gemini API, processes them, uploads to Reach platform,
84
  and returns URLs for the generated variations.
85
+ """
86
  logger.info(f"Generating network banners for brand: {brand_name} in domain: {domain}")
 
87
  api_key = settings.GEMINI_API_KEY
88
  client = genai.Client(api_key=api_key)
89
+ prompt = get_network_prompts(brand_name, domain)
90
  all_banner_results = []
91
 
92
+ try:
93
+ logger.info("Sending prompt to Gemini API.")
94
+ response = client.models.generate_content(
95
+ model="gemini-2.0-flash-exp-image-generation",
96
+ contents=prompt,
97
+ config=types.GenerateContentConfig(
98
+ response_modalities=['TEXT', 'IMAGE']
 
 
99
  )
100
+ )
101
 
102
+ for part in response.candidates[0].content.parts:
103
+ if part.inline_data is not None:
104
+ try:
105
+ mime_type = part.inline_data.mime_type
106
+ image_data = part.inline_data.data
107
+
108
+ # Determine format based on MIME type
109
+ if "jpeg" in mime_type or "jpg" in mime_type:
110
+ image_format = "jpeg"
111
+ elif "png" in mime_type:
112
+ image_format = "png"
113
+ elif "webp" in mime_type:
114
+ image_format = "webp"
115
+ else:
116
+ logger.warning(f"Unknown image format '{mime_type}', defaulting to jpeg.")
117
+ image_format = "jpeg"
118
+
119
+ # Process and upload image
120
+ logger.info("Processing image")
121
+ processed_image = process_image(image_data)
122
+
123
+ result = upload_to_reach(
124
+ processed_image,
125
+ f"network_banner_{brand_name}",
126
+ image_format,
127
+ 1,
128
+ 'BEST_NETWORK_IMAGE'
129
+ )
130
+ logger.info("Uploaded banner successfully.")
131
+ all_banner_results.append({
132
+ "variation": 1,
133
+ "banner": result['url'] # Only use the URL from the response
134
+ })
135
+
136
+ except Exception as e:
137
+ logger.exception("Error processing banner image: {e}")
138
+ raise
139
+
140
+ except Exception as e:
141
+ logger.exception("Error generating banner: {e}")
142
+ raise
 
143
 
144
  if not all_banner_results:
145
  logger.error("No banner images were generated.")
app/services/byop_service.py CHANGED
@@ -15,12 +15,8 @@ logger.setLevel(logging.INFO)
15
 
16
 
17
  def get_byop_prompts(brand_name: str, domain: str) -> list[str]:
18
- prompts = [
19
- f"Create an abstract, high-impact banner for a brand, operating in the {domain} space. The composition should be visually striking and adapt well across desktop, tablet, and mobile crop ratios. Use abstract forms to reflect the brand's essence and values. Core visual elements must be centered or evenly distributed for consistent cropping. DO NOT USE ANY TEXT, LETTERS, NUMBERS, OR TYPOGRAPHIC ELEMENTS.",
20
-
21
- f"Create an minimalistic, high-impact banner for a brand, in the {domain} domain. The design should be visually impactful and adaptable across desktop, tablet, and mobile crop sizes. Use non-literal abstract forms to express the brand's core identity and values. Ensure visual elements are centered or balanced. DO NOT USE ANY TEXT, LETTERS, NUMBERS, OR TYPOGRAPHIC ELEMENTS.",
22
- ]
23
- return prompts
24
 
25
  def process_image(image_data: bytes, width: int = 530, height: int = 352) -> bytes:
26
  """
@@ -91,27 +87,25 @@ def generate_byop_banner(brand_name: str, domain: str) -> Dict:
91
  Generates BYOP banners using Gemini image generation API,
92
  processes them, uploads to Reach platform, and returns their URLs.
93
  """
94
- logger.info(f"Generating BYOP banners for brand: {brand_name}, domain: {domain}")
95
-
96
  api_key = settings.GEMINI_API_KEY
97
  client = genai.Client(api_key=api_key)
98
- prompts = get_byop_prompts(brand_name, domain)
99
  all_banner_results = []
100
-
101
- for prompt_index, prompt in enumerate(prompts, 1):
102
- try:
103
- logger.info(f"Sending prompt {prompt_index} to Gemini API")
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']
109
- )
110
  )
 
111
 
112
- for part in response.candidates[0].content.parts:
113
- if part.inline_data is not None:
114
- try:
115
  mime_type = part.inline_data.mime_type
116
  image_data = part.inline_data.data
117
 
@@ -123,33 +117,29 @@ def generate_byop_banner(brand_name: str, domain: str) -> Dict:
123
  elif "webp" in mime_type:
124
  image_format = "webp"
125
  else:
126
- image_format = "jpeg" # Default to JPEG
127
-
128
- logger.info(f"Processing banner image variation {prompt_index}")
129
  processed_image = process_image(image_data)
130
 
131
  result = upload_to_reach(
132
  processed_image,
133
- f"byop_banner_{brand_name}_v{prompt_index}",
134
  image_format,
135
- prompt_index,
136
  'BYOD_IMAGE'
137
  )
138
 
139
  all_banner_results.append({
140
- "variation": prompt_index,
141
  "banner": result['url'] # Only use the URL from the response
142
  })
143
-
144
- logger.info(f"Banner variation {prompt_index} uploaded successfully")
145
-
146
- except Exception as e:
147
- logger.error(f"Error processing banner image for variation {prompt_index}: {str(e)}")
148
  raise
149
 
150
- except Exception as e:
151
- logger.error(f"Error generating banner for variation {prompt_index}: {str(e)}")
152
- raise
153
 
154
  if not all_banner_results:
155
  logger.error("No images were generated")
 
15
 
16
 
17
  def get_byop_prompts(brand_name: str, domain: str) -> list[str]:
18
+ prompt = f"Generate an realistic image which includes real people and displays the essence of the domain : {domain}. 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:
22
  """
 
87
  Generates BYOP banners using Gemini image generation API,
88
  processes them, uploads to Reach platform, and returns their URLs.
89
  """
90
+ logger.info(f"Generating BYOP banners for brand: {brand_name}, domain: {domain}")
 
91
  api_key = settings.GEMINI_API_KEY
92
  client = genai.Client(api_key=api_key)
93
+ prompt = get_byop_prompts(brand_name, domain)
94
  all_banner_results = []
95
+
96
+ try:
97
+ logger.info("Sending prompt to Gemini API")
98
+ response = client.models.generate_content(
99
+ model="gemini-2.0-flash-exp-image-generation",
100
+ contents=prompt,
101
+ config=types.GenerateContentConfig(
 
102
  response_modalities=['TEXT', 'IMAGE']
 
103
  )
104
+ )
105
 
106
+ for part in response.candidates[0].content.parts:
107
+ if part.inline_data is not None:
108
+ try:
109
  mime_type = part.inline_data.mime_type
110
  image_data = part.inline_data.data
111
 
 
117
  elif "webp" in mime_type:
118
  image_format = "webp"
119
  else:
120
+ image_format = "jpeg" # Default to JPEG logger.info("Processing banner image")
 
 
121
  processed_image = process_image(image_data)
122
 
123
  result = upload_to_reach(
124
  processed_image,
125
+ f"byop_banner_{brand_name}",
126
  image_format,
127
+ 1,
128
  'BYOD_IMAGE'
129
  )
130
 
131
  all_banner_results.append({
132
+ "variation": 1,
133
  "banner": result['url'] # Only use the URL from the response
134
  })
135
+ except Exception as e:
136
+ logger.info("Banner uploaded successfully")
137
+ logger.error(f"Error processing banner image: {str(e)}")
 
 
138
  raise
139
 
140
+ except Exception as e:
141
+ logger.error(f"Error generating banner: {str(e)}")
142
+ raise
143
 
144
  if not all_banner_results:
145
  logger.error("No images were generated")
app/services/custom_banner_desktop_service.py CHANGED
@@ -13,12 +13,7 @@ logger = logging.getLogger(__name__)
13
 
14
  def get_desktop_prompt(brand_name: str, domain: str, primary_color: str, description: str) -> str:
15
  return f'''
16
- Create a wide-format image (1440x500) that visually represents the concept and essence of the domain '{domain}',
17
- and artistically captures the idea: {description}. Avoid using the color {primary_color}.
18
-
19
- The composition should have balanced visual weight with dual-orientation impact and a strong central focus.
20
-
21
- The image must not contain any text, lettering, numbers, symbols, logos, or typographic elements of any kind.
22
  '''
23
 
24
 
 
13
 
14
  def get_desktop_prompt(brand_name: str, domain: str, primary_color: str, description: str) -> str:
15
  return f'''
16
+ Generate a realistic image which includes real people and shows the essence of the domain {domain} and captures the gist of the description : {description}. Use shades that oppose the color {primary_color}. Do not Include any text, typographic or Alphanumeric Elements.
 
 
 
 
 
17
  '''
18
 
19
 
app/services/custom_banner_ipad_service.py CHANGED
@@ -13,14 +13,8 @@ logger = logging.getLogger(__name__)
13
 
14
  def get_ipad_prompt(brand_name: str, domain: str, primary_color: str, description: str) -> str:
15
  return f'''
16
- Generate a banner image suitable for tablets (768x500) that captures the essence of the domain '{domain}'
17
- by expressing the idea: {description}.
18
-
19
- Avoid using the color {primary_color} and rather use complementing ones.
20
- Ensure the design has balanced visual weight suitable for both portrait and landscape orientations.
21
-
22
- The image must not contain any text, writing, letters, numbers, symbols, or typographic elements.
23
- '''
24
  def process_image(image_data: bytes, target_width: int, target_height: int) -> bytes:
25
  """
26
  Resize, sharpen, enhance, and compress image for upload.
 
13
 
14
  def get_ipad_prompt(brand_name: str, domain: str, primary_color: str, description: str) -> str:
15
  return f'''
16
+ Generate a realistic image which includes real people and shows the essence of the domain {domain} and captures the gist of the description : {description}. Use shades that oppose the color {primary_color}. Do not Include any text, typographic or Alphanumeric Elements.
17
+ '''
 
 
 
 
 
 
18
  def process_image(image_data: bytes, target_width: int, target_height: int) -> bytes:
19
  """
20
  Resize, sharpen, enhance, and compress image for upload.
app/services/custom_banner_mobile_service.py CHANGED
@@ -13,13 +13,7 @@ logger = logging.getLogger(__name__)
13
 
14
  def get_mobile_prompt(brand_name: str, domain: str, primary_color: str, description: str) -> str:
15
  return f'''
16
- Create a vertical mobile banner image (375x500) that visually reflects the domain '{domain}'
17
- and brings to life the idea: {description}.
18
-
19
- Avoid using the color {primary_color} and rather use the colors complementing it.
20
- Focus on a clear visual hierarchy optimized for narrow vertical viewing while preserving the description’s emotional and conceptual intent.
21
-
22
- Absolutely no text, writing, lettering, numbers, symbols, or typographic elements of any kind should appear in the image.
23
  '''
24
 
25
  def process_image(image_data: bytes, target_width: int, target_height: int) -> bytes:
 
13
 
14
  def get_mobile_prompt(brand_name: str, domain: str, primary_color: str, description: str) -> str:
15
  return f'''
16
+ Generate a realistic image which includes real people and shows the essence of the domain {domain} and captures the gist of the description : {description}. Use shades that oppose the color {primary_color}. Do not Include any text, typographic or Alphanumeric Elements.
 
 
 
 
 
 
17
  '''
18
 
19
  def process_image(image_data: bytes, target_width: int, target_height: int) -> bytes: