Spaces:
Running
Running
File size: 15,472 Bytes
02d4d4d c5d76a1 02d4d4d c5d76a1 d5c98f4 c5d76a1 02d4d4d c5d76a1 d5c98f4 c5d76a1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 |
from abc import ABC, abstractmethod
from typing import Dict, Any
from PIL import Image, ImageDraw, ImageFont
import requests
from io import BytesIO
import tempfile
class Template(ABC):
"""
Abstract base class for image templates.
Each template defines its own configuration for box sizes, positions, colors, and fonts.
"""
def __init__(self, template_path: str = None):
self.template_path = template_path
@abstractmethod
def get_box_config(self) -> Dict[str, Any]:
"""Return box configuration including size and position for product image."""
pass
@abstractmethod
def get_text_config(self) -> Dict[str, Dict[str, Any]]:
"""Return text configuration including positions, colors, and fonts for all text elements."""
pass
@abstractmethod
def get_font_config(self) -> Dict[str, Dict[str, Any]]:
"""Return font configuration for different text elements."""
pass
def load_template_image(self) -> Image.Image:
"""Load and return the template image."""
return Image.open(self.template_path).convert("RGBA")
def load_fonts(self) -> Dict[str, ImageFont.FreeTypeFont]:
"""Load and return all required fonts."""
fonts = {}
font_config = self.get_font_config()
for font_name, config in font_config.items():
try:
fonts[font_name] = ImageFont.truetype(config['path'], config['size'])
except IOError:
print(f"Font {config['path']} not found. Using default font.")
fonts[font_name] = ImageFont.load_default()
return fonts
def generate_image(self, product_image_url: str, product_name: str,
original_price: str, final_price: str, coupon_code: str) -> str:
"""
Generate the promotional image using this template's configuration.
Args:
product_image_url: URL of the product image
product_name: Name of the product
original_price: Original price of the product
final_price: Final price of the product
coupon_code: Coupon code to display
Returns:
Path to the generated image file
"""
try:
# Load template and fonts
template_image = self.load_template_image()
fonts = self.load_fonts()
# Fetch and process product image
response = requests.get(product_image_url)
product_image_data = BytesIO(response.content)
product_image = Image.open(product_image_data).convert("RGBA")
# Get box configuration
box_config = self.get_box_config()
box_size = box_config['size']
box_position = box_config['position']
# Resize product image to fit within box while preserving aspect ratio
product_image_resized = product_image.copy()
product_image_resized.thumbnail(box_size)
# Calculate position to center the image in the box
paste_x = box_position[0] + (box_size[0] - product_image_resized.width) // 2
paste_y = box_position[1] + (box_size[1] - product_image_resized.height) // 2
paste_position = (paste_x, paste_y)
# Paste product image onto template
template_image.paste(product_image_resized, paste_position, product_image_resized)
# Draw text elements
draw = ImageDraw.Draw(template_image)
text_config = self.get_text_config()
# Draw each text element
for element_name, config in text_config.items():
text_content = self._get_text_content(element_name, product_name,
original_price, final_price, coupon_code)
position = config['position']
color = config['color']
font_name = config['font']
anchor = config.get('anchor', 'ms')
draw.text(position, text_content, font=fonts[font_name],
fill=color, anchor=anchor)
# Save the result
with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as temp_file:
template_image.save(temp_file.name)
return temp_file.name
except FileNotFoundError:
return f"Error: The template file '{self.template_path}' was not found."
except Exception as e:
return f"An error occurred: {e}"
def _get_text_content(self, element_name: str, product_name: str,
original_price: str, final_price: str, coupon_code: str) -> str:
"""Get the actual text content for each text element."""
content_map = {
'product_name': product_name,
'original_price': f"De: R$ {original_price}",
'final_price': f"Por: R$ {final_price}",
'coupon_code': coupon_code
}
return content_map.get(element_name, '')
class TemplateRegistry:
"""Registry for managing different template types."""
_templates = {}
@classmethod
def register(cls, name: str, template_class):
"""Register a template class."""
cls._templates[name] = template_class
@classmethod
def get_template(cls, name: str) -> Template:
"""Get a template instance by name."""
if name not in cls._templates:
raise ValueError(f"Template '{name}' not found")
template_instance = cls._templates[name]()
return template_instance
@classmethod
def list_templates(cls) -> list:
"""List all registered template names."""
return list(cls._templates.keys())
class LidiPromoTemplate(Template):
"""
Template implementation for Lidi promotional images.
Uses the original hardcoded values from the existing implementation.
"""
def __init__(self, template_path: str = None):
super().__init__(template_path or "assets/template_1.png")
def get_box_config(self) -> Dict[str, Any]:
"""Return box configuration for product image."""
return {
'size': (442, 353),
'position': (140, 280) # (x, y) from top-left corner
}
def get_text_config(self) -> Dict[str, Dict[str, Any]]:
"""Return text configuration for all text elements."""
return {
'product_name': {
'position': (360, 710),
'color': '#FFFFFF',
'font': 'font_name',
'anchor': 'ms'
},
'original_price': {
'position': (360, 800),
'color': '#FFFFFF',
'font': 'font_price_from',
'anchor': 'ms'
},
'final_price': {
'position': (360, 860),
'color': '#FEE161', # Yellow color from original design
'font': 'font_price',
'anchor': 'ms'
},
'coupon_code': {
'position': (360, 993),
'color': '#000000',
'font': 'font_cupom',
'anchor': 'ms'
}
}
def get_font_config(self) -> Dict[str, Dict[str, Any]]:
"""Return font configuration for different text elements."""
return {
'font_name': {
'path': 'assets/Montserrat-Bold.ttf',
'size': 47
},
'font_price_from': {
'path': 'assets/Montserrat-Regular.ttf',
'size': 28
},
'font_price': {
'path': 'assets/Montserrat-Bold.ttf',
'size': 47
},
'font_cupom': {
'path': 'assets/Montserrat-Bold.ttf',
'size': 33
}
}
class NaturaClienteTemplate(Template):
"""
Template implementation for Natura promotional images.
Uses template_b_natura.png with different configuration.
"""
def __init__(self, template_path: str = None):
super().__init__(template_path or "assets/template_b_natura.png")
def get_box_config(self) -> Dict[str, Any]:
"""Return box configuration for product image."""
return {
'size': (602, 424),
'position': (54, 254) # (x, y) from top-left corner
}
def get_text_config(self) -> Dict[str, Dict[str, Any]]:
"""Return text configuration for all text elements."""
return {
'product_name': {
'position': (72, 727),
'color': '#000000',
'font': 'font_name',
'anchor': 'ls'
},
'original_price': {
'position': (72, 765),
'color': '#666666',
'font': 'font_price_from',
'anchor': 'ls'
},
'final_price': {
'position': (90, 837),
'color': '#FFFFFF',
'font': 'font_price',
'anchor': 'lm'
},
'coupon_code': {
'position': (461, 957),
'color': '#FFFFFF',
'font': 'font_cupom',
'anchor': 'ms'
}
}
def get_font_config(self) -> Dict[str, Dict[str, Any]]:
"""Return font configuration for different text elements."""
return {
'font_name': {
'path': 'assets/Montserrat-Bold.ttf',
'size': 32
},
'font_price_from': {
'path': 'assets/Montserrat-Regular.ttf',
'size': 22
},
'font_price': {
'path': 'assets/Montserrat-Bold.ttf',
'size': 40
},
'font_cupom': {
'path': 'assets/Montserrat-Bold.ttf',
'size': 42
}
}
class AvonTemplate(Template):
"""
Template implementation for Avon promotional images.
Uses template_b_avon.png with Avon-specific configuration.
"""
def __init__(self, template_path: str = None):
super().__init__(template_path or "assets/template_b_avon.png")
def get_box_config(self) -> Dict[str, Any]:
"""Return box configuration for product image."""
return {
'size': (602, 424),
'position': (54, 254) # (x, y) from top-left corner
}
def get_text_config(self) -> Dict[str, Dict[str, Any]]:
"""Return text configuration for all text elements."""
return {
'product_name': {
'position': (72, 727),
'color': '#000000',
'font': 'font_name',
'anchor': 'ls'
},
'original_price': {
'position': (72, 765),
'color': '#666666',
'font': 'font_price_from',
'anchor': 'ls'
},
'final_price': {
'position': (90, 837),
'color': '#FFFFFF',
'font': 'font_price',
'anchor': 'lm'
},
'coupon_code': {
'position': (461, 957),
'color': '#FFFFFF',
'font': 'font_cupom',
'anchor': 'ms'
}
}
def get_font_config(self) -> Dict[str, Dict[str, Any]]:
"""Return font configuration for different text elements."""
return {
'font_name': {
'path': 'assets/Montserrat-Bold.ttf',
'size': 32
},
'font_price_from': {
'path': 'assets/Montserrat-Regular.ttf',
'size': 22
},
'font_price': {
'path': 'assets/Montserrat-Bold.ttf',
'size': 40
},
'font_cupom': {
'path': 'assets/Montserrat-Bold.ttf',
'size': 42
}
}
class TemplateC(Template):
"""
Template implementation for Avon promotional images.
Uses template_b_avon.png with Avon-specific configuration.
"""
def __init__(self, template_path: str):
super().__init__(template_path)
def get_box_config(self) -> Dict[str, Any]:
"""Return box configuration for product image."""
return {
'size': (602, 434),
'position': (54, 304) # (x, y) from top-left corner
}
def get_text_config(self) -> Dict[str, Dict[str, Any]]:
"""Return text configuration for all text elements."""
return {
'product_name': {
'position': (72, 777),
'color': '#000000',
'font': 'font_name',
'anchor': 'ls'
},
'original_price': {
'position': (72, 815),
'color': '#666666',
'font': 'font_price_from',
'anchor': 'ls'
},
'final_price': {
'position': (90, 887),
'color': '#FFFFFF',
'font': 'font_price',
'anchor': 'lm'
},
'coupon_code': {
'position': (471, 1020),
'color': '#FFFFFF',
'font': 'font_cupom',
'anchor': 'ms'
}
}
def get_font_config(self) -> Dict[str, Dict[str, Any]]:
"""Return font configuration for different text elements."""
return {
'font_name': {
'path': 'assets/Montserrat-Bold.ttf',
'size': 32
},
'font_price_from': {
'path': 'assets/Montserrat-Regular.ttf',
'size': 22
},
'font_price': {
'path': 'assets/Montserrat-Bold.ttf',
'size': 40
},
'font_cupom': {
'path': 'assets/Montserrat-Bold.ttf',
'size': 42
}
}
class TemplateOutros(TemplateC):
def __init__(self, template_path: str = None):
super().__init__("assets/template_c_outros.png")
class TemplateOutrosSemCupom(TemplateC):
def __init__(self, template_path: str = None):
super().__init__("assets/template_c_outros_sem_cupom.png")
class TemplateNatura(TemplateC):
def __init__(self, template_path: str = None):
super().__init__("assets/template_c_natura.png")
class TemplateAvonSemCupom(TemplateC):
def __init__(self, template_path: str = None):
super().__init__("assets/template_b_avon.png")
# Register additional templates
TemplateRegistry.register('lidi_promo', LidiPromoTemplate)
TemplateRegistry.register('natura', TemplateNatura)
TemplateRegistry.register('avon', TemplateAvonSemCupom)
TemplateRegistry.register('outros', TemplateOutros)
TemplateRegistry.register('outros_sem_cupom', TemplateOutrosSemCupom)
TemplateRegistry.register('natura_cliente', NaturaClienteTemplate) |