Daniel251 commited on
Commit
21a4bcd
·
verified ·
1 Parent(s): 002e90d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +704 -384
app.py CHANGED
@@ -6,9 +6,15 @@ import torch
6
  from transformers import AutoModelForImageSegmentation
7
  import io
8
  import tempfile
9
- from typing import List, Tuple
 
10
  import warnings
11
  warnings.filterwarnings("ignore")
 
 
 
 
 
12
 
13
  # Configurações
14
  MODEL_NAME = "briaai/RMBG-1.4"
@@ -43,453 +49,718 @@ BORDER_STYLES = {
43
  class CollagePosterGenerator:
44
  def __init__(self):
45
  self.device = "cuda" if torch.cuda.is_available() else "cpu"
46
- print(f"🚀 Inicializando no dispositivo: {self.device}")
47
 
48
  # Carregar modelo de remoção de fundo
 
49
  try:
50
- print("📥 Carregando modelo RMBG-1.4...")
51
  self.model = AutoModelForImageSegmentation.from_pretrained(
52
  MODEL_NAME,
53
  trust_remote_code=True
54
  )
 
55
  self.model.to(self.device)
56
  self.model.eval()
57
- print("✅ Modelo carregado com sucesso!")
58
  except Exception as e:
59
- print(f"⚠️ Erro ao carregar modelo: {e}")
 
60
  self.model = None
61
 
62
  def remove_background(self, image: Image.Image) -> Image.Image:
63
  """Remove o fundo da imagem usando o modelo RMBG"""
 
 
64
  try:
65
  if self.model is None:
66
- # Fallback simples se o modelo não carregar
67
  return self._simple_bg_removal(image)
68
 
69
  # Preparar imagem
70
  original_size = image.size
71
- image_resized = image.resize((1024, 1024), Image.LANCZOS)
 
 
 
 
72
 
73
  # Converter para tensor
74
  img_array = np.array(image_resized)
 
 
 
 
 
 
 
 
75
  img_tensor = torch.from_numpy(img_array).permute(2, 0, 1).unsqueeze(0).float() / 255.0
76
  img_tensor = img_tensor.to(self.device)
 
77
 
78
  # Processar
79
  with torch.no_grad():
 
80
  result = self.model(img_tensor)[-1].sigmoid()
 
81
 
82
  # Converter máscara de volta
83
  mask = result[0].cpu().numpy().squeeze()
 
 
84
  mask = (mask * 255).astype(np.uint8)
85
- mask_img = Image.fromarray(mask).resize(original_size, Image.LANCZOS)
 
86
 
87
  # Aplicar máscara
88
  result_img = image.convert("RGBA")
 
 
 
 
 
 
89
  result_img.putalpha(mask_img)
 
90
 
91
  return result_img
92
 
93
  except Exception as e:
94
- print(f"⚠️ Erro na remoção de fundo: {e}")
 
 
95
  return self._simple_bg_removal(image)
96
 
97
  def _simple_bg_removal(self, image: Image.Image) -> Image.Image:
98
  """Remoção de fundo simples como fallback"""
99
- img = image.convert("RGBA")
100
- data = np.array(img)
101
-
102
- # Detectar pixels próximos ao branco
103
- white_threshold = 200
104
- mask = (data[:, :, 0] > white_threshold) & \
105
- (data[:, :, 1] > white_threshold) & \
106
- (data[:, :, 2] > white_threshold)
107
 
108
- data[:, :, 3] = np.where(mask, 0, 255)
109
- return Image.fromarray(data, 'RGBA')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
 
111
  def apply_border_effect(self, image: Image.Image, style: str, color: str) -> Image.Image:
112
  """Aplica efeitos de borda estilizados"""
 
 
113
  if style == "none":
 
114
  return image
115
 
116
- if image.mode != 'RGBA':
117
- image = image.convert('RGBA')
118
-
119
- if style == "soft_shadow":
120
- # Criar sombra suave
121
- shadow_size = 15
122
- expanded = Image.new('RGBA',
123
- (image.width + shadow_size*2, image.height + shadow_size*2),
124
- (0, 0, 0, 0))
125
-
126
- # Criar camada de sombra
127
- shadow = Image.new('RGBA', expanded.size, (0, 0, 0, 0))
128
- shadow_draw = ImageDraw.Draw(shadow)
129
-
130
- for i in range(shadow_size):
131
- alpha = int(100 * (1 - i/shadow_size))
132
- temp = Image.new('RGBA', image.size, (0, 0, 0, alpha))
133
- shadow.paste(temp, (shadow_size + i, shadow_size + i), temp)
134
-
135
- # Aplicar blur
136
- shadow = shadow.filter(ImageFilter.GaussianBlur(radius=shadow_size//2))
137
-
138
- # Combinar
139
- expanded.paste(shadow, (0, 0), shadow)
140
- expanded.paste(image, (shadow_size, shadow_size), image)
141
- return expanded
142
-
143
- elif style == "neon_glow":
144
- # Efeito de brilho neon
145
- glow_size = 20
146
- expanded = Image.new('RGBA',
147
- (image.width + glow_size*2, image.height + glow_size*2),
148
- (0, 0, 0, 0))
149
-
150
- # Criar brilho
151
- glow = Image.new('RGBA', expanded.size, (0, 0, 0, 0))
152
-
153
- # Extrair contorno da imagem
154
- alpha = image.split()[-1]
155
- alpha_resized = alpha.resize(expanded.size, Image.LANCZOS)
156
-
157
- # Aplicar cor ao brilho
158
- hex_color = color.lstrip('#')
159
- rgb = tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
160
-
161
- for i in range(5):
162
- blur_alpha = alpha_resized.filter(ImageFilter.GaussianBlur(radius=glow_size - i*3))
163
- colored = Image.new('RGBA', expanded.size, rgb + (100 - i*20,))
164
- colored.putalpha(blur_alpha)
165
- glow.paste(colored, (0, 0), colored)
166
-
167
- expanded.paste(glow, (0, 0), glow)
168
- expanded.paste(image, (glow_size, glow_size), image)
169
- return expanded
170
-
171
- elif style == "double_line":
172
- # Borda dupla
173
- border = 15
174
- expanded = Image.new('RGBA',
175
- (image.width + border*2, image.height + border*2),
176
- (0, 0, 0, 0))
177
-
178
- draw = ImageDraw.Draw(expanded)
179
-
180
- # Cor hex para RGB
181
- hex_color = color.lstrip('#')
182
- rgb = tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
183
-
184
- # Borda externa
185
- draw.rectangle([0, 0, expanded.width-1, expanded.height-1],
186
- outline=rgb, width=border//2)
187
- # Borda interna
188
- draw.rectangle([border//2, border//2,
189
- expanded.width-border//2-1, expanded.height-border//2-1],
190
- outline=(255, 255, 255), width=border//4)
191
-
192
- expanded.paste(image, (border, border), image)
193
- return expanded
194
-
195
- elif style == "colored_outline":
196
- # Contorno colorido
197
- outline_size = 8
198
- expanded = Image.new('RGBA',
199
- (image.width + outline_size*2, image.height + outline_size*2),
200
- (0, 0, 0, 0))
201
-
202
- # Criar contorno
203
- alpha = image.split()[-1]
204
-
205
- # Dilatar a máscara
206
- alpha_np = np.array(alpha)
207
- kernel = np.ones((outline_size*2, outline_size*2), np.uint8)
208
- dilated = cv2.dilate(alpha_np, kernel, iterations=1)
209
-
210
- outline_mask = Image.fromarray(dilated)
211
-
212
- # Aplicar cor
213
- hex_color = color.lstrip('#')
214
- rgb = tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
215
-
216
- outline = Image.new('RGBA', expanded.size, rgb)
217
- outline.putalpha(outline_mask)
218
-
219
- expanded.paste(outline, (0, 0), outline)
220
- expanded.paste(image, (outline_size, outline_size), image)
221
- return expanded
222
-
223
- else: # inner_glow
224
- # Brilho interno
225
- glow_img = image.copy()
226
-
227
- # Criar máscara de brilho interno
228
- alpha = image.split()[-1]
229
- alpha_np = np.array(alpha)
230
-
231
- # Erodir para criar borda interna
232
- kernel = np.ones((5, 5), np.uint8)
233
- eroded = cv2.erode(alpha_np, kernel, iterations=2)
234
-
235
- # Diferença entre original e erodida
236
- inner_border = alpha_np - eroded
237
-
238
- # Aplicar cor
239
- hex_color = color.lstrip('#')
240
- rgb = tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
241
-
242
- glow_layer = Image.new('RGBA', image.size, rgb + (150,))
243
- glow_layer.putalpha(Image.fromarray(inner_border))
244
-
245
- result = Image.alpha_composite(image, glow_layer)
246
- return result
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
247
 
248
  def create_gradient_background(self, size: Tuple[int, int], color1: str, color2: str) -> Image.Image:
249
  """Cria fundo degradê"""
250
- width, height = size
251
-
252
- # Converter hex para RGB
253
- def hex_to_rgb(hex_color):
254
- hex_color = hex_color.lstrip('#')
255
- return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
256
-
257
- rgb1 = hex_to_rgb(color1)
258
- rgb2 = hex_to_rgb(color2)
259
-
260
- # Criar degradê
261
- background = Image.new('RGB', size)
262
- draw = ImageDraw.Draw(background)
263
-
264
- for i in range(height):
265
- ratio = i / height
266
- r = int(rgb1[0] * (1 - ratio) + rgb2[0] * ratio)
267
- g = int(rgb1[1] * (1 - ratio) + rgb2[1] * ratio)
268
- b = int(rgb1[2] * (1 - ratio) + rgb2[2] * ratio)
269
- draw.line([(0, i), (width, i)], fill=(r, g, b))
270
 
271
- return background
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
272
 
273
  def add_text_with_effects(self, image: Image.Image, title: str, description: str,
274
  text_color: str) -> Image.Image:
275
  """Adiciona texto com efeitos visuais"""
 
 
276
  if not title and not description:
 
277
  return image
278
 
279
- # Converter para RGBA se necessário
280
- if image.mode != 'RGBA':
281
- image = image.convert('RGBA')
282
-
283
- # Criar camada de texto
284
- text_layer = Image.new('RGBA', image.size, (0, 0, 0, 0))
285
- draw = ImageDraw.Draw(text_layer)
286
-
287
- width, height = image.size
288
- margin = int(min(width, height) * 0.05) # 5% de margem
289
-
290
- # Carregar fontes
291
  try:
292
- title_size = int(min(width, height) * 0.08)
293
- desc_size = int(min(width, height) * 0.04)
294
- title_font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", title_size)
295
- desc_font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", desc_size)
296
- except:
297
- title_font = ImageFont.load_default()
298
- desc_font = ImageFont.load_default()
299
-
300
- # Cor do texto
301
- hex_color = text_color.lstrip('#')
302
- text_rgb = tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
303
-
304
- # Processar título
305
- y_offset = height - margin
306
-
307
- if description:
308
- # Quebrar descrição em linhas
309
- desc_lines = []
310
- words = description.split()
311
- current_line = []
312
-
313
- for word in words:
314
- test_line = ' '.join(current_line + [word])
315
- bbox = draw.textbbox((0, 0), test_line, font=desc_font)
316
- if bbox[2] - bbox[0] > width - 2*margin:
317
- if current_line:
318
- desc_lines.append(' '.join(current_line))
319
- current_line = [word]
320
- else:
321
- desc_lines.append(word)
322
- else:
323
- current_line.append(word)
324
-
325
- if current_line:
326
- desc_lines.append(' '.join(current_line))
327
-
328
- # Desenhar descrição
329
- for line in reversed(desc_lines):
330
- bbox = draw.textbbox((0, 0), line, font=desc_font)
331
- text_width = bbox[2] - bbox[0]
332
- text_height = bbox[3] - bbox[1]
333
- x = (width - text_width) // 2
334
- y_offset -= text_height + 10
335
-
336
- # Sombra colorida
337
- shadow_color = (255, 100, 150, 180)
338
- for dx, dy in [(3, 3), (-2, 2), (2, -2)]:
339
- draw.text((x + dx, y_offset + dy), line, font=desc_font, fill=shadow_color)
340
-
341
- # Texto principal
342
- draw.text((x, y_offset), line, font=desc_font, fill=text_rgb)
343
-
344
- if title:
345
- # Quebrar título em linhas
346
- title_lines = []
347
- words = title.split()
348
- current_line = []
349
-
350
- for word in words:
351
- test_line = ' '.join(current_line + [word])
352
- bbox = draw.textbbox((0, 0), test_line, font=title_font)
353
- if bbox[2] - bbox[0] > width - 2*margin:
354
- if current_line:
355
- title_lines.append(' '.join(current_line))
356
- current_line = [word]
357
- else:
358
- title_lines.append(word)
359
- else:
360
- current_line.append(word)
361
-
362
- if current_line:
363
- title_lines.append(' '.join(current_line))
364
-
365
- # Desenhar título
366
- y_offset -= 30 # Espaço entre título e descrição
367
-
368
- for line in reversed(title_lines):
369
- bbox = draw.textbbox((0, 0), line, font=title_font)
370
- text_width = bbox[2] - bbox[0]
371
- text_height = bbox[3] - bbox[1]
372
- x = (width - text_width) // 2
373
- y_offset -= text_height + 15
374
-
375
- # Sombra colorida mais forte
376
- shadow_color = (100, 150, 255, 200)
377
- for dx, dy in [(4, 4), (-3, 3), (3, -3), (-3, -3)]:
378
- draw.text((x + dx, y_offset + dy), line, font=title_font, fill=shadow_color)
379
-
380
- # Texto principal
381
- draw.text((x, y_offset), line, font=title_font, fill=text_rgb)
382
-
383
- # Combinar camadas
384
- result = Image.alpha_composite(image, text_layer)
385
- return result
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
386
 
387
  def compose_collage(self, images: List[Image.Image], background: Image.Image) -> Image.Image:
388
  """Compõe as imagens em um collage"""
389
- result = background.copy().convert('RGBA')
390
- bg_width, bg_height = background.size
391
-
392
- if not images:
393
- return result.convert('RGB')
394
-
395
- num_images = len(images)
396
-
397
- # Organização em grade
398
- cols = int(np.ceil(np.sqrt(num_images)))
399
- rows = int(np.ceil(num_images / cols))
400
-
401
- # Deixar espaço para texto (30% inferior)
402
- usable_height = int(bg_height * 0.7)
403
-
404
- cell_width = bg_width // (cols + 1)
405
- cell_height = usable_height // (rows + 1)
406
 
407
- for idx, img in enumerate(images):
408
- row = idx // cols
409
- col = idx % cols
 
410
 
411
- # Redimensionar mantendo proporção
412
- max_size = (int(cell_width * 0.85), int(cell_height * 0.85))
413
- img.thumbnail(max_size, Image.LANCZOS)
414
 
415
- # Calcular posição centralizada
416
- x = int((col + 0.5) * cell_width + (cell_width - img.width) / 2)
417
- y = int((row + 0.5) * cell_height + (cell_height - img.height) / 2)
418
 
419
- # Colar imagem
420
- result.paste(img, (x, y), img)
421
-
422
- return result.convert('RGB')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
423
 
424
  def optimize_file_size(self, image: Image.Image, max_size_mb: float = 1.5) -> Image.Image:
425
  """Otimiza o tamanho do arquivo"""
426
- if image.mode == 'RGBA':
427
- image = image.convert('RGB')
428
 
429
- for quality in range(95, 50, -5):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
430
  output = io.BytesIO()
431
- image.save(output, format='JPEG', quality=quality, optimize=True)
432
- size_mb = len(output.getvalue()) / (1024 * 1024)
 
433
 
434
- if size_mb <= max_size_mb:
435
- output.seek(0)
436
- return Image.open(output).copy()
437
-
438
- return image
439
 
440
  def generate_poster(self, images: List, resolution_preset: str,
441
  custom_width: int, custom_height: int,
442
  border_style: str, border_color: str,
443
  gradient_color1: str, gradient_color2: str,
444
- title: str, description: str, text_color: str) -> Tuple[Image.Image, str]:
445
  """Gera o pôster final"""
446
 
447
- if not images:
448
- return None, "❌ Por favor, faça upload de pelo menos uma imagem"
449
-
450
- # Determinar resolução
451
- if resolution_preset == "Custom":
452
- if not custom_width or not custom_height:
453
- return None, "❌ Por favor, defina largura e altura customizadas"
454
- size = (int(custom_width), int(custom_height))
455
- else:
456
- size = RESOLUTION_PRESETS[resolution_preset]
457
-
458
- print(f"📐 Resolução: {size}")
459
 
460
- # Processar imagens
461
- processed_images = []
462
- for idx, img in enumerate(images):
463
- print(f"🖼️ Processando imagem {idx + 1}/{len(images)}...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
464
 
465
- # Converter para PIL
466
- pil_img = Image.fromarray(img)
 
467
 
468
- # Remover fundo
469
- pil_img = self.remove_background(pil_img)
470
 
471
- # Aplicar borda
472
- pil_img = self.apply_border_effect(pil_img, BORDER_STYLES[border_style], border_color)
 
473
 
474
- processed_images.append(pil_img)
475
-
476
- print("🎨 Criando fundo degradê...")
477
- background = self.create_gradient_background(size, gradient_color1, gradient_color2)
478
-
479
- print("📸 Compondo collage...")
480
- collage = self.compose_collage(processed_images, background)
481
-
482
- print("✍️ Adicionando texto...")
483
- if title or description:
484
- collage = self.add_text_with_effects(collage, title, description, text_color)
485
-
486
- print("🗜️ Otimizando tamanho do arquivo...")
487
- collage = self.optimize_file_size(collage, OUTPUT_MAX_SIZE_MB)
488
-
489
- return collage, f"✅ Pôster gerado com sucesso! Resolução: {size[0]}x{size[1]}px"
 
 
 
 
 
 
 
 
490
 
491
  # Inicializar gerador
492
- print("🎨 Inicializando Gerador de Pôster de Colagem...")
493
  generator = CollagePosterGenerator()
494
 
495
  # Interface Gradio
@@ -499,6 +770,8 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Gerador de Pôster de Colagem") as
499
 
500
  Crie pôsteres incríveis com múltiplas imagens, remoção de fundo automática e efeitos especiais!
501
  Powered by **RMBG-1.4** AI Model 🤖
 
 
502
  """)
503
 
504
  with gr.Row():
@@ -520,8 +793,8 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Gerador de Pôster de Colagem") as
520
  )
521
 
522
  with gr.Row(visible=False) as custom_row:
523
- custom_width = gr.Number(label="Largura (px)", value=1080)
524
- custom_height = gr.Number(label="Altura (px)", value=1080)
525
 
526
  def toggle_custom(choice):
527
  return gr.update(visible=choice == "Custom")
@@ -568,6 +841,16 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Gerador de Pôster de Colagem") as
568
  )
569
 
570
  process_btn = gr.Button("🚀 Gerar Pôster", variant="primary", size="lg")
 
 
 
 
 
 
 
 
 
 
571
 
572
  with gr.Column(scale=2):
573
  gr.Markdown("### 👁️ Preview do Pôster")
@@ -578,19 +861,45 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Gerador de Pôster de Colagem") as
578
  height=600
579
  )
580
 
581
- status_text = gr.Markdown("💡 **Dica:** Faça upload de imagens e clique em Gerar Pôster")
582
 
583
  with gr.Row():
584
  download_btn = gr.DownloadButton(
585
  label="💾 Download (Alta Resolução)",
586
  size="lg",
587
- variant="primary"
 
588
  )
589
 
590
  # Processamento
591
- def process_wrapper(*args):
592
- result, message = generator.generate_poster(*args)
593
- return result, message
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
594
 
595
  process_btn.click(
596
  fn=process_wrapper,
@@ -599,21 +908,25 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Gerador de Pôster de Colagem") as
599
  border_style, border_color, gradient_color1, gradient_color2,
600
  title_input, description_input, text_color
601
  ],
602
- outputs=[output_image, status_text]
603
  )
604
 
605
- # Download
606
- def prepare_download(img):
607
- if img is None:
608
- return None
609
- temp_path = tempfile.NamedTemporaryFile(delete=False, suffix='.jpg').name
610
- img.save(temp_path, 'JPEG', quality=95, optimize=True)
611
- return temp_path
612
 
613
- output_image.change(
614
- fn=prepare_download,
615
- inputs=[output_image],
616
- outputs=[download_btn]
 
 
 
 
617
  )
618
 
619
  gr.Markdown("""
@@ -626,14 +939,12 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Gerador de Pôster de Colagem") as
626
  4. **🚀 Gere**: Clique no botão para processar
627
  5. **💾 Baixe**: Download automático em alta qualidade
628
 
629
- ### ⚡ Recursos Premium:
630
 
631
- - ✅ **Remoção de Fundo com IA** - Modelo RMBG-1.4
632
- - ✅ **Efeitos de Borda Profissionais** - 6 estilos diferentes
633
- - ✅ **Fundos Degradê Customizáveis** - Cores à sua escolha
634
- - ✅ **Texto Estilizado** - Com sombras coloridas modernas
635
- - ✅ **Múltiplas Resoluções** - Redes sociais e impressão
636
- - ✅ **Otimização Automática** - Arquivos até 1.5MB
637
 
638
  ### 🎯 Casos de Uso:
639
 
@@ -645,4 +956,13 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Gerador de Pôster de Colagem") as
645
  """)
646
 
647
  if __name__ == "__main__":
648
- demo.launch()
 
 
 
 
 
 
 
 
 
 
6
  from transformers import AutoModelForImageSegmentation
7
  import io
8
  import tempfile
9
+ import traceback
10
+ from typing import List, Tuple, Optional
11
  import warnings
12
  warnings.filterwarnings("ignore")
13
+ import logging
14
+
15
+ # Configurar logging
16
+ logging.basicConfig(level=logging.INFO)
17
+ logger = logging.getLogger(__name__)
18
 
19
  # Configurações
20
  MODEL_NAME = "briaai/RMBG-1.4"
 
49
  class CollagePosterGenerator:
50
  def __init__(self):
51
  self.device = "cuda" if torch.cuda.is_available() else "cpu"
52
+ logger.info(f"🚀 Inicializando no dispositivo: {self.device}")
53
 
54
  # Carregar modelo de remoção de fundo
55
+ self.model = None
56
  try:
57
+ logger.info(f"📥 Tentando carregar modelo {MODEL_NAME}...")
58
  self.model = AutoModelForImageSegmentation.from_pretrained(
59
  MODEL_NAME,
60
  trust_remote_code=True
61
  )
62
+ logger.info("✅ Modelo carregado com sucesso!")
63
  self.model.to(self.device)
64
  self.model.eval()
65
+ logger.info(f"✅ Modelo movido para {self.device} e em modo eval")
66
  except Exception as e:
67
+ logger.error(f"❌ Erro ao carregar modelo: {e}")
68
+ logger.error(traceback.format_exc())
69
  self.model = None
70
 
71
  def remove_background(self, image: Image.Image) -> Image.Image:
72
  """Remove o fundo da imagem usando o modelo RMBG"""
73
+ logger.info(f"🔄 Iniciando remoção de fundo - Image mode: {image.mode}, Size: {image.size}")
74
+
75
  try:
76
  if self.model is None:
77
+ logger.warning("⚠️ Modelo não disponível, usando fallback simples")
78
  return self._simple_bg_removal(image)
79
 
80
  # Preparar imagem
81
  original_size = image.size
82
+ logger.info(f"📏 Tamanho original: {original_size}")
83
+
84
+ # Redimensionar para o tamanho esperado pelo modelo
85
+ image_resized = image.resize((1024, 1024), Image.Resampling.LANCZOS)
86
+ logger.info(f"📐 Imagem redimensionada para: {image_resized.size}")
87
 
88
  # Converter para tensor
89
  img_array = np.array(image_resized)
90
+ logger.info(f"🔢 Array shape: {img_array.shape}, dtype: {img_array.dtype}")
91
+
92
+ # Verificar se a imagem tem canal alpha
93
+ if img_array.shape[2] == 4:
94
+ logger.info("🌊 Imagem tem canal alpha, removendo...")
95
+ img_array = img_array[:, :, :3]
96
+
97
+ # Normalizar e converter para tensor
98
  img_tensor = torch.from_numpy(img_array).permute(2, 0, 1).unsqueeze(0).float() / 255.0
99
  img_tensor = img_tensor.to(self.device)
100
+ logger.info(f"⚡ Tensor shape: {img_tensor.shape}, device: {img_tensor.device}")
101
 
102
  # Processar
103
  with torch.no_grad():
104
+ logger.info("🧠 Processando com modelo...")
105
  result = self.model(img_tensor)[-1].sigmoid()
106
+ logger.info(f"✅ Processamento concluído - Result shape: {result.shape}")
107
 
108
  # Converter máscara de volta
109
  mask = result[0].cpu().numpy().squeeze()
110
+ logger.info(f"🎭 Máscara shape: {mask.shape}, min: {mask.min()}, max: {mask.max()}")
111
+
112
  mask = (mask * 255).astype(np.uint8)
113
+ mask_img = Image.fromarray(mask).resize(original_size, Image.Resampling.LANCZOS)
114
+ logger.info(f"🖼️ Máscara redimensionada para: {mask_img.size}")
115
 
116
  # Aplicar máscara
117
  result_img = image.convert("RGBA")
118
+
119
+ # Garantir que a máscara tenha o mesmo tamanho
120
+ if mask_img.size != result_img.size:
121
+ logger.warning(f"⚠️ Tamanhos diferentes: imagem={result_img.size}, máscara={mask_img.size}")
122
+ mask_img = mask_img.resize(result_img.size, Image.Resampling.LANCZOS)
123
+
124
  result_img.putalpha(mask_img)
125
+ logger.info("✅ Máscara aplicada com sucesso")
126
 
127
  return result_img
128
 
129
  except Exception as e:
130
+ logger.error(f"❌ Erro na remoção de fundo: {e}")
131
+ logger.error(traceback.format_exc())
132
+ logger.info("🔄 Usando fallback simples...")
133
  return self._simple_bg_removal(image)
134
 
135
  def _simple_bg_removal(self, image: Image.Image) -> Image.Image:
136
  """Remoção de fundo simples como fallback"""
137
+ logger.info("🔄 Usando remoção de fundo simples (fallback)")
 
 
 
 
 
 
 
138
 
139
+ try:
140
+ img = image.convert("RGBA")
141
+ data = np.array(img)
142
+ logger.info(f"📊 Dados da imagem - Shape: {data.shape}, dtype: {data.dtype}")
143
+
144
+ # Detectar pixels próximos ao branco (assumindo fundo claro)
145
+ white_threshold = 200
146
+ logger.info(f"🎚️ Threshold: {white_threshold}")
147
+
148
+ # Calcular luminosidade
149
+ if len(data.shape) == 3 and data.shape[2] >= 3:
150
+ # Calcular luminosidade média
151
+ luminosity = np.mean(data[:, :, :3], axis=2)
152
+ mask = luminosity > white_threshold
153
+ logger.info(f"☀️ Pixels claros detectados: {np.sum(mask)}/{mask.size}")
154
+ else:
155
+ mask = np.zeros(data.shape[:2], dtype=bool)
156
+ logger.warning("⚠️ Não foi possível calcular luminosidade")
157
+
158
+ data[:, :, 3] = np.where(mask, 0, 255)
159
+
160
+ result = Image.fromarray(data, 'RGBA')
161
+ logger.info("✅ Fallback concluído com sucesso")
162
+ return result
163
+
164
+ except Exception as e:
165
+ logger.error(f"❌ Erro no fallback: {e}")
166
+ # Retornar imagem original com fundo transparente
167
+ result = image.convert("RGBA")
168
+ return result
169
 
170
  def apply_border_effect(self, image: Image.Image, style: str, color: str) -> Image.Image:
171
  """Aplica efeitos de borda estilizados"""
172
+ logger.info(f"🎨 Aplicando efeito de borda: {style}, cor: {color}")
173
+
174
  if style == "none":
175
+ logger.info("⏩ Pulando efeito de borda")
176
  return image
177
 
178
+ try:
179
+ if image.mode != 'RGBA':
180
+ logger.info(f"🔄 Convertendo de {image.mode} para RGBA")
181
+ image = image.convert('RGBA')
182
+
183
+ if style == "soft_shadow":
184
+ logger.info("🌫️ Criando sombra suave...")
185
+ shadow_size = 15
186
+ expanded = Image.new('RGBA',
187
+ (image.width + shadow_size*2, image.height + shadow_size*2),
188
+ (0, 0, 0, 0))
189
+
190
+ # Criar camada de sombra
191
+ shadow = Image.new('RGBA', expanded.size, (0, 0, 0, 0))
192
+
193
+ for i in range(shadow_size):
194
+ alpha = int(100 * (1 - i/shadow_size))
195
+ temp = Image.new('RGBA', image.size, (0, 0, 0, alpha))
196
+ shadow.paste(temp, (shadow_size + i, shadow_size + i), temp)
197
+
198
+ # Aplicar blur
199
+ shadow = shadow.filter(ImageFilter.GaussianBlur(radius=shadow_size//2))
200
+
201
+ # Combinar
202
+ expanded.paste(shadow, (0, 0), shadow)
203
+ expanded.paste(image, (shadow_size, shadow_size), image)
204
+ logger.info("✅ Sombra suave aplicada")
205
+ return expanded
206
+
207
+ elif style == "neon_glow":
208
+ logger.info("💡 Criando brilho neon...")
209
+ glow_size = 20
210
+ expanded = Image.new('RGBA',
211
+ (image.width + glow_size*2, image.height + glow_size*2),
212
+ (0, 0, 0, 0))
213
+
214
+ # Criar brilho
215
+ glow = Image.new('RGBA', expanded.size, (0, 0, 0, 0))
216
+
217
+ # Extrair contorno da imagem
218
+ alpha = image.split()[-1]
219
+ alpha_resized = alpha.resize(expanded.size, Image.Resampling.LANCZOS)
220
+
221
+ # Converter cor hex para RGB
222
+ try:
223
+ hex_color = color.lstrip('#')
224
+ rgb = tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
225
+ logger.info(f"🌈 Cor convertida: {rgb}")
226
+ except:
227
+ rgb = (0, 255, 255) # Ciano como fallback
228
+ logger.warning(f"⚠️ Erro ao converter cor {color}, usando fallback {rgb}")
229
+
230
+ for i in range(5):
231
+ blur_alpha = alpha_resized.filter(ImageFilter.GaussianBlur(radius=glow_size - i*3))
232
+ colored = Image.new('RGBA', expanded.size, rgb + (100 - i*20,))
233
+ colored.putalpha(blur_alpha)
234
+ glow.paste(colored, (0, 0), colored)
235
+
236
+ expanded.paste(glow, (0, 0), glow)
237
+ expanded.paste(image, (glow_size, glow_size), image)
238
+ logger.info("✅ Brilho neon aplicado")
239
+ return expanded
240
+
241
+ elif style == "double_line":
242
+ logger.info("🔄 Criando borda dupla...")
243
+ border = 15
244
+ expanded = Image.new('RGBA',
245
+ (image.width + border*2, image.height + border*2),
246
+ (0, 0, 0, 0))
247
+
248
+ draw = ImageDraw.Draw(expanded)
249
+
250
+ # Converter cor hex para RGB
251
+ try:
252
+ hex_color = color.lstrip('#')
253
+ rgb = tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
254
+ except:
255
+ rgb = (255, 255, 255) # Branco como fallback
256
+
257
+ # Borda externa
258
+ draw.rectangle([0, 0, expanded.width-1, expanded.height-1],
259
+ outline=rgb, width=border//2)
260
+ # Borda interna
261
+ draw.rectangle([border//2, border//2,
262
+ expanded.width-border//2-1, expanded.height-border//2-1],
263
+ outline=(255, 255, 255), width=border//4)
264
+
265
+ expanded.paste(image, (border, border), image)
266
+ logger.info("✅ Borda dupla aplicada")
267
+ return expanded
268
+
269
+ elif style == "colored_outline":
270
+ logger.info("🎨 Criando contorno colorido...")
271
+ outline_size = 8
272
+ expanded = Image.new('RGBA',
273
+ (image.width + outline_size*2, image.height + outline_size*2),
274
+ (0, 0, 0, 0))
275
+
276
+ # Criar contorno
277
+ alpha = image.split()[-1]
278
+ alpha_np = np.array(alpha)
279
+ logger.info(f"📊 Alpha shape: {alpha_np.shape}")
280
+
281
+ # Dilatar a máscara
282
+ kernel = np.ones((outline_size*2, outline_size*2), np.uint8)
283
+ dilated = cv2.dilate(alpha_np, kernel, iterations=1)
284
+
285
+ outline_mask = Image.fromarray(dilated)
286
+
287
+ # Converter cor hex para RGB
288
+ try:
289
+ hex_color = color.lstrip('#')
290
+ rgb = tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
291
+ except:
292
+ rgb = (255, 0, 0) # Vermelho como fallback
293
+
294
+ outline = Image.new('RGBA', expanded.size, rgb)
295
+ outline.putalpha(outline_mask)
296
+
297
+ expanded.paste(outline, (0, 0), outline)
298
+ expanded.paste(image, (outline_size, outline_size), image)
299
+ logger.info("✅ Contorno colorido aplicado")
300
+ return expanded
301
+
302
+ else: # inner_glow
303
+ logger.info("🌟 Criando brilho interno...")
304
+ glow_img = image.copy()
305
+
306
+ # Criar máscara de brilho interno
307
+ alpha = image.split()[-1]
308
+ alpha_np = np.array(alpha)
309
+
310
+ # Erodir para criar borda interna
311
+ kernel = np.ones((5, 5), np.uint8)
312
+ eroded = cv2.erode(alpha_np, kernel, iterations=2)
313
+
314
+ # Diferença entre original e erodida
315
+ inner_border = alpha_np - eroded
316
+
317
+ # Converter cor hex para RGB
318
+ try:
319
+ hex_color = color.lstrip('#')
320
+ rgb = tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
321
+ except:
322
+ rgb = (255, 255, 0) # Amarelo como fallback
323
+
324
+ glow_layer = Image.new('RGBA', image.size, rgb + (150,))
325
+ glow_layer.putalpha(Image.fromarray(inner_border))
326
+
327
+ result = Image.alpha_composite(image, glow_layer)
328
+ logger.info("✅ Brilho interno aplicado")
329
+ return result
330
+
331
+ except Exception as e:
332
+ logger.error(f"❌ Erro ao aplicar efeito de borda: {e}")
333
+ logger.error(traceback.format_exc())
334
+ return image
335
 
336
  def create_gradient_background(self, size: Tuple[int, int], color1: str, color2: str) -> Image.Image:
337
  """Cria fundo degradê"""
338
+ logger.info(f"🌈 Criando fundo degradê - Tamanho: {size}, Cores: {color1} -> {color2}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
339
 
340
+ try:
341
+ width, height = size
342
+
343
+ # Converter hex para RGB
344
+ def hex_to_rgb(hex_color):
345
+ hex_color = hex_color.lstrip('#')
346
+ return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
347
+
348
+ try:
349
+ rgb1 = hex_to_rgb(color1)
350
+ rgb2 = hex_to_rgb(color2)
351
+ logger.info(f"🎨 Cores convertidas: {rgb1} -> {rgb2}")
352
+ except:
353
+ logger.warning("⚠️ Erro ao converter cores, usando padrão")
354
+ rgb1 = (102, 126, 234) # Azul padrão
355
+ rgb2 = (118, 75, 162) # Roxo padrão
356
+
357
+ # Criar degradê
358
+ background = Image.new('RGB', size)
359
+ draw = ImageDraw.Draw(background)
360
+
361
+ for i in range(height):
362
+ ratio = i / height
363
+ r = int(rgb1[0] * (1 - ratio) + rgb2[0] * ratio)
364
+ g = int(rgb1[1] * (1 - ratio) + rgb2[1] * ratio)
365
+ b = int(rgb1[2] * (1 - ratio) + rgb2[2] * ratio)
366
+ draw.line([(0, i), (width, i)], fill=(r, g, b))
367
+
368
+ logger.info("✅ Fundo degradê criado com sucesso")
369
+ return background
370
+
371
+ except Exception as e:
372
+ logger.error(f"❌ Erro ao criar fundo degradê: {e}")
373
+ # Retornar fundo preto como fallback
374
+ return Image.new('RGB', size, (0, 0, 0))
375
 
376
  def add_text_with_effects(self, image: Image.Image, title: str, description: str,
377
  text_color: str) -> Image.Image:
378
  """Adiciona texto com efeitos visuais"""
379
+ logger.info(f"✍️ Adicionando texto - Título: {title[:20]}..., Descrição: {description[:20]}...")
380
+
381
  if not title and not description:
382
+ logger.info("⏩ Sem texto para adicionar")
383
  return image
384
 
 
 
 
 
 
 
 
 
 
 
 
 
385
  try:
386
+ # Converter para RGBA se necessário
387
+ if image.mode != 'RGBA':
388
+ logger.info(f"🔄 Convertendo de {image.mode} para RGBA")
389
+ image = image.convert('RGBA')
390
+
391
+ # Criar camada de texto
392
+ text_layer = Image.new('RGBA', image.size, (0, 0, 0, 0))
393
+ draw = ImageDraw.Draw(text_layer)
394
+
395
+ width, height = image.size
396
+ margin = int(min(width, height) * 0.05) # 5% de margem
397
+ logger.info(f"📐 Margem calculada: {margin}px")
398
+
399
+ # Carregar fontes
400
+ try:
401
+ title_size = int(min(width, height) * 0.08)
402
+ desc_size = int(min(width, height) * 0.04)
403
+ logger.info(f"🔤 Tamanhos de fonte - Título: {title_size}, Descrição: {desc_size}")
404
+
405
+ # Tentar fontes comuns
406
+ font_paths = [
407
+ "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
408
+ "/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf",
409
+ "/usr/share/fonts/truetype/ubuntu/Ubuntu-B.ttf",
410
+ "arialbd.ttf"
411
+ ]
412
+
413
+ title_font = None
414
+ desc_font = None
415
+
416
+ for font_path in font_paths:
417
+ try:
418
+ if title_font is None:
419
+ title_font = ImageFont.truetype(font_path, title_size)
420
+ logger.info(f"✅ Fonte de título carregada: {font_path}")
421
+ if desc_font is None:
422
+ desc_font = ImageFont.truetype(font_path.replace("-Bold", "").replace("Bold", ""), desc_size)
423
+ logger.info(f"✅ Fonte de descrição carregada: {font_path}")
424
+ if title_font and desc_font:
425
+ break
426
+ except:
427
+ continue
428
+
429
+ if title_font is None:
430
+ logger.warning("⚠️ Não foi possível carregar fonte TrueType, usando padrão")
431
+ title_font = ImageFont.load_default()
432
+ desc_font = ImageFont.load_default()
433
+
434
+ except Exception as e:
435
+ logger.warning(f"⚠️ Erro ao carregar fontes: {e}, usando padrão")
436
+ title_font = ImageFont.load_default()
437
+ desc_font = ImageFont.load_default()
438
+
439
+ # Cor do texto
440
+ try:
441
+ hex_color = text_color.lstrip('#')
442
+ text_rgb = tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
443
+ logger.info(f"🎨 Cor do texto: {text_rgb}")
444
+ except:
445
+ text_rgb = (255, 255, 255) # Branco como fallback
446
+ logger.warning(f"⚠️ Erro ao converter cor {text_color}, usando branco")
447
+
448
+ # Processar título
449
+ y_offset = height - margin
450
+
451
+ if description and description.strip():
452
+ logger.info("📝 Processando descrição...")
453
+ # Quebrar descrição em linhas
454
+ desc_lines = []
455
+ words = description.split()
456
+ current_line = []
457
+
458
+ for word in words:
459
+ test_line = ' '.join(current_line + [word])
460
+ try:
461
+ bbox = draw.textbbox((0, 0), test_line, font=desc_font)
462
+ if bbox[2] - bbox[0] > width - 2*margin:
463
+ if current_line:
464
+ desc_lines.append(' '.join(current_line))
465
+ current_line = [word]
466
+ else:
467
+ desc_lines.append(word)
468
+ else:
469
+ current_line.append(word)
470
+ except:
471
+ # Fallback para fontes padrão
472
+ if len(test_line) > 30:
473
+ if current_line:
474
+ desc_lines.append(' '.join(current_line))
475
+ current_line = [word]
476
+ else:
477
+ desc_lines.append(word)
478
+ else:
479
+ current_line.append(word)
480
+
481
+ if current_line:
482
+ desc_lines.append(' '.join(current_line))
483
+
484
+ logger.info(f"📋 Descrição dividida em {len(desc_lines)} linhas")
485
+
486
+ # Desenhar descrição
487
+ for line in reversed(desc_lines):
488
+ try:
489
+ bbox = draw.textbbox((0, 0), line, font=desc_font)
490
+ text_width = bbox[2] - bbox[0]
491
+ text_height = bbox[3] - bbox[1]
492
+ except:
493
+ # Estimativa simples
494
+ text_width = len(line) * desc_size * 0.6
495
+ text_height = desc_size * 1.2
496
+
497
+ x = (width - int(text_width)) // 2
498
+ y_offset -= int(text_height) + 10
499
+
500
+ # Sombra colorida
501
+ shadow_color = (255, 100, 150, 180)
502
+ for dx, dy in [(3, 3), (-2, 2), (2, -2)]:
503
+ draw.text((x + dx, y_offset + dy), line, font=desc_font, fill=shadow_color)
504
+
505
+ # Texto principal
506
+ draw.text((x, y_offset), line, font=desc_font, fill=text_rgb)
507
+
508
+ if title and title.strip():
509
+ logger.info("🏷️ Processando título...")
510
+ # Quebrar título em linhas
511
+ title_lines = []
512
+ words = title.split()
513
+ current_line = []
514
+
515
+ for word in words:
516
+ test_line = ' '.join(current_line + [word])
517
+ try:
518
+ bbox = draw.textbbox((0, 0), test_line, font=title_font)
519
+ if bbox[2] - bbox[0] > width - 2*margin:
520
+ if current_line:
521
+ title_lines.append(' '.join(current_line))
522
+ current_line = [word]
523
+ else:
524
+ title_lines.append(word)
525
+ else:
526
+ current_line.append(word)
527
+ except:
528
+ # Fallback para fontes padrão
529
+ if len(test_line) > 20:
530
+ if current_line:
531
+ title_lines.append(' '.join(current_line))
532
+ current_line = [word]
533
+ else:
534
+ title_lines.append(word)
535
+ else:
536
+ current_line.append(word)
537
+
538
+ if current_line:
539
+ title_lines.append(' '.join(current_line))
540
+
541
+ logger.info(f"📋 Título dividido em {len(title_lines)} linhas")
542
+
543
+ # Desenhar título
544
+ y_offset -= 30 # Espaço entre título e descrição
545
+
546
+ for line in reversed(title_lines):
547
+ try:
548
+ bbox = draw.textbbox((0, 0), line, font=title_font)
549
+ text_width = bbox[2] - bbox[0]
550
+ text_height = bbox[3] - bbox[1]
551
+ except:
552
+ # Estimativa simples
553
+ text_width = len(line) * title_size * 0.6
554
+ text_height = title_size * 1.2
555
+
556
+ x = (width - int(text_width)) // 2
557
+ y_offset -= int(text_height) + 15
558
+
559
+ # Sombra colorida mais forte
560
+ shadow_color = (100, 150, 255, 200)
561
+ for dx, dy in [(4, 4), (-3, 3), (3, -3), (-3, -3)]:
562
+ draw.text((x + dx, y_offset + dy), line, font=title_font, fill=shadow_color)
563
+
564
+ # Texto principal
565
+ draw.text((x, y_offset), line, font=title_font, fill=text_rgb)
566
+
567
+ # Combinar camadas
568
+ result = Image.alpha_composite(image, text_layer)
569
+ logger.info("✅ Texto adicionado com sucesso")
570
+ return result
571
+
572
+ except Exception as e:
573
+ logger.error(f"❌ Erro ao adicionar texto: {e}")
574
+ logger.error(traceback.format_exc())
575
+ return image
576
 
577
  def compose_collage(self, images: List[Image.Image], background: Image.Image) -> Image.Image:
578
  """Compõe as imagens em um collage"""
579
+ logger.info(f"🎭 Compondo collage com {len(images)} imagens")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
580
 
581
+ try:
582
+ result = background.copy().convert('RGBA')
583
+ bg_width, bg_height = background.size
584
+ logger.info(f"📐 Tamanho do fundo: {bg_width}x{bg_height}")
585
 
586
+ if not images:
587
+ logger.warning("⚠️ Nenhuma imagem para compor")
588
+ return result.convert('RGB')
589
 
590
+ num_images = len(images)
 
 
591
 
592
+ # Organização em grade
593
+ cols = int(np.ceil(np.sqrt(num_images)))
594
+ rows = int(np.ceil(num_images / cols))
595
+ logger.info(f"📊 Layout: {rows} linhas x {cols} colunas")
596
+
597
+ # Deixar espaço para texto (30% inferior)
598
+ usable_height = int(bg_height * 0.7)
599
+ logger.info(f"📏 Altura útil: {usable_height}px")
600
+
601
+ cell_width = bg_width // (cols + 1)
602
+ cell_height = usable_height // (rows + 1)
603
+ logger.info(f"📐 Tamanho da célula: {cell_width}x{cell_height}")
604
+
605
+ for idx, img in enumerate(images):
606
+ logger.info(f"🖼️ Processando imagem {idx + 1}/{num_images}...")
607
+
608
+ # Redimensionar mantendo proporção
609
+ max_size = (int(cell_width * 0.85), int(cell_height * 0.85))
610
+ img.thumbnail(max_size, Image.Resampling.LANCZOS)
611
+ logger.info(f"📏 Imagem redimensionada para: {img.size}")
612
+
613
+ # Calcular posição centralizada
614
+ x = int((col + 0.5) * cell_width + (cell_width - img.width) / 2)
615
+ y = int((row + 0.5) * cell_height + (cell_height - img.height) / 2)
616
+ logger.info(f"📍 Posição: ({x}, {y})")
617
+
618
+ # Colar imagem
619
+ result.paste(img, (x, y), img)
620
+
621
+ logger.info("✅ Collage composta com sucesso")
622
+ return result.convert('RGB')
623
+
624
+ except Exception as e:
625
+ logger.error(f"❌ Erro ao compor collage: {e}")
626
+ logger.error(traceback.format_exc())
627
+ return background.convert('RGB')
628
 
629
  def optimize_file_size(self, image: Image.Image, max_size_mb: float = 1.5) -> Image.Image:
630
  """Otimiza o tamanho do arquivo"""
631
+ logger.info(f"🗜️ Otimizando tamanho do arquivo (max: {max_size_mb}MB)...")
 
632
 
633
+ try:
634
+ if image.mode == 'RGBA':
635
+ logger.info("🔄 Convertendo de RGBA para RGB")
636
+ image = image.convert('RGB')
637
+
638
+ for quality in range(95, 50, -5):
639
+ output = io.BytesIO()
640
+ image.save(output, format='JPEG', quality=quality, optimize=True)
641
+ size_mb = len(output.getvalue()) / (1024 * 1024)
642
+ logger.info(f"📊 Qualidade {quality}%: {size_mb:.2f}MB")
643
+
644
+ if size_mb <= max_size_mb:
645
+ output.seek(0)
646
+ result = Image.open(output).copy()
647
+ logger.info(f"✅ Otimizado para {quality}% - {size_mb:.2f}MB")
648
+ return result
649
+
650
+ # Se não conseguir abaixo do limite, usar qualidade mínima
651
+ logger.warning("⚠️ Não conseguiu atingir o limite, usando qualidade 50%")
652
  output = io.BytesIO()
653
+ image.save(output, format='JPEG', quality=50, optimize=True)
654
+ output.seek(0)
655
+ return Image.open(output).copy()
656
 
657
+ except Exception as e:
658
+ logger.error(f"❌ Erro ao otimizar tamanho: {e}")
659
+ return image
 
 
660
 
661
  def generate_poster(self, images: List, resolution_preset: str,
662
  custom_width: int, custom_height: int,
663
  border_style: str, border_color: str,
664
  gradient_color1: str, gradient_color2: str,
665
+ title: str, description: str, text_color: str) -> Tuple[Optional[Image.Image], str]:
666
  """Gera o pôster final"""
667
 
668
+ logger.info("=" * 50)
669
+ logger.info("🎬 INICIANDO GERAÇÃO DE PÔSTER")
670
+ logger.info("=" * 50)
 
 
 
 
 
 
 
 
 
671
 
672
+ try:
673
+ if not images:
674
+ logger.error("❌ Nenhuma imagem fornecida")
675
+ return None, "❌ Por favor, faça upload de pelo menos uma imagem"
676
+
677
+ logger.info(f"📸 Imagens recebidas: {len(images)}")
678
+
679
+ # Determinar resolução
680
+ if resolution_preset == "Custom":
681
+ if not custom_width or not custom_height:
682
+ logger.error("❌ Dimensões customizadas não fornecidas")
683
+ return None, "❌ Por favor, defina largura e altura customizadas"
684
+
685
+ try:
686
+ size = (int(custom_width), int(custom_height))
687
+ logger.info(f"📐 Resolução customizada: {size}")
688
+ except:
689
+ logger.error(f"❌ Dimensões inválidas: {custom_width}x{custom_height}")
690
+ return None, "❌ Dimensões inválidas. Use números inteiros."
691
+ else:
692
+ size = RESOLUTION_PRESETS.get(resolution_preset, (1080, 1080))
693
+ logger.info(f"📐 Resolução preset: {resolution_preset} -> {size}")
694
+
695
+ logger.info(f"⚙️ Configurações:")
696
+ logger.info(f" • Bordas: {border_style}")
697
+ logger.info(f" • Cor borda: {border_color}")
698
+ logger.info(f" • Cores fundo: {gradient_color1} -> {gradient_color2}")
699
+ logger.info(f" • Título: {title}")
700
+ logger.info(f" • Descrição: {description}")
701
+ logger.info(f" • Cor texto: {text_color}")
702
+
703
+ # Processar imagens
704
+ processed_images = []
705
+ for idx, img_array in enumerate(images):
706
+ logger.info(f"🖼️ PROCESSANDO IMAGEM {idx + 1}/{len(images)}")
707
+
708
+ # Converter para PIL
709
+ try:
710
+ pil_img = Image.fromarray(img_array)
711
+ logger.info(f" ✅ Convertido para PIL - Tamanho: {pil_img.size}, Modo: {pil_img.mode}")
712
+ except Exception as e:
713
+ logger.error(f" ❌ Erro ao converter imagem {idx}: {e}")
714
+ continue
715
+
716
+ # Remover fundo
717
+ pil_img = self.remove_background(pil_img)
718
+ logger.info(f" ✅ Fundo removido - Novo modo: {pil_img.mode}")
719
+
720
+ # Aplicar borda
721
+ border_style_key = BORDER_STYLES.get(border_style, "none")
722
+ pil_img = self.apply_border_effect(pil_img, border_style_key, border_color)
723
+ logger.info(f" ✅ Borda aplicada")
724
+
725
+ processed_images.append(pil_img)
726
 
727
+ if not processed_images:
728
+ logger.error("❌ Nenhuma imagem processada com sucesso")
729
+ return None, "❌ Erro ao processar imagens. Tente novamente."
730
 
731
+ logger.info(f"✅ {len(processed_images)} imagens processadas com sucesso")
 
732
 
733
+ # Criar fundo
734
+ logger.info("🌈 CRIANDO FUNDO DEGRADÊ")
735
+ background = self.create_gradient_background(size, gradient_color1, gradient_color2)
736
 
737
+ # Criar collage
738
+ logger.info("🎭 COMPONDO COLLAGE")
739
+ collage = self.compose_collage(processed_images, background)
740
+
741
+ # Adicionar texto
742
+ if title or description:
743
+ logger.info("✍️ ADICIONANDO TEXTO")
744
+ collage = self.add_text_with_effects(collage, title, description, text_color)
745
+
746
+ # Otimizar tamanho
747
+ logger.info("🗜️ OTIMIZANDO TAMANHO DO ARQUIVO")
748
+ collage = self.optimize_file_size(collage, OUTPUT_MAX_SIZE_MB)
749
+
750
+ logger.info("=" * 50)
751
+ logger.info("✅ PÔSTER GERADO COM SUCESSO!")
752
+ logger.info("=" * 50)
753
+
754
+ return collage, f"✅ Pôster gerado com sucesso! Resolução: {size[0]}x{size[1]}px"
755
+
756
+ except Exception as e:
757
+ logger.error("❌ ERRO CRÍTICO NA GERAÇÃO DO PÔSTER")
758
+ logger.error(f"Erro: {e}")
759
+ logger.error(traceback.format_exc())
760
+ return None, f"❌ Erro ao gerar pôster: {str(e)}"
761
 
762
  # Inicializar gerador
763
+ logger.info("🎨 INICIALIZANDO GERADOR DE PÔSTER DE COLAGEM")
764
  generator = CollagePosterGenerator()
765
 
766
  # Interface Gradio
 
770
 
771
  Crie pôsteres incríveis com múltiplas imagens, remoção de fundo automática e efeitos especiais!
772
  Powered by **RMBG-1.4** AI Model 🤖
773
+
774
+ *Consulte os logs no console para ver o progresso em tempo real*
775
  """)
776
 
777
  with gr.Row():
 
793
  )
794
 
795
  with gr.Row(visible=False) as custom_row:
796
+ custom_width = gr.Number(label="Largura (px)", value=1080, minimum=100, maximum=10000)
797
+ custom_height = gr.Number(label="Altura (px)", value=1080, minimum=100, maximum=10000)
798
 
799
  def toggle_custom(choice):
800
  return gr.update(visible=choice == "Custom")
 
841
  )
842
 
843
  process_btn = gr.Button("🚀 Gerar Pôster", variant="primary", size="lg")
844
+
845
+ # Adicionar botão para limpar logs
846
+ clear_logs_btn = gr.Button("🗑️ Limpar Console", variant="secondary")
847
+
848
+ def clear_logs():
849
+ # Esta função limparia os logs no frontend
850
+ # Em produção, você pode querer implementar um sistema de logs diferente
851
+ return "✅ Console limpo"
852
+
853
+ clear_logs_btn.click(clear_logs, outputs=[gr.Textbox(visible=False)])
854
 
855
  with gr.Column(scale=2):
856
  gr.Markdown("### 👁️ Preview do Pôster")
 
861
  height=600
862
  )
863
 
864
+ status_text = gr.Markdown("💡 **Status:** Aguardando entrada...")
865
 
866
  with gr.Row():
867
  download_btn = gr.DownloadButton(
868
  label="💾 Download (Alta Resolução)",
869
  size="lg",
870
+ variant="primary",
871
+ visible=False
872
  )
873
 
874
  # Processamento
875
+ def process_wrapper(images, *args):
876
+ logger.info("🔄 Botão 'Gerar Pôster' clicado")
877
+
878
+ if not images:
879
+ logger.warning("⚠️ Nenhuma imagem fornecida")
880
+ return None, "❌ Por favor, faça upload de pelo menos uma imagem", gr.update(visible=False)
881
+
882
+ logger.info("🔄 Chamando função de geração...")
883
+ result, message = generator.generate_poster(images, *args)
884
+
885
+ if result is not None:
886
+ logger.info("✅ Pôster gerado com sucesso, preparando download...")
887
+ # Salvar em arquivo temporário para download
888
+ try:
889
+ temp_path = tempfile.NamedTemporaryFile(delete=False, suffix='.jpg').name
890
+ result.save(temp_path, 'JPEG', quality=95, optimize=True)
891
+ logger.info(f"💾 Arquivo salvo em: {temp_path}")
892
+
893
+ # Criar botão de download
894
+ download_file = gr.File(value=temp_path, visible=True, label="Baixar Pôster")
895
+
896
+ return result, message, gr.update(visible=True, value=temp_path)
897
+ except Exception as e:
898
+ logger.error(f"❌ Erro ao salvar arquivo: {e}")
899
+ return result, message, gr.update(visible=False)
900
+ else:
901
+ logger.error(f"❌ Geração falhou: {message}")
902
+ return None, message, gr.update(visible=False)
903
 
904
  process_btn.click(
905
  fn=process_wrapper,
 
908
  border_style, border_color, gradient_color1, gradient_color2,
909
  title_input, description_input, text_color
910
  ],
911
+ outputs=[output_image, status_text, download_btn]
912
  )
913
 
914
+ # Adicionar área de logs (opcional, para debug)
915
+ gr.Markdown("""
916
+ ---
917
+ ### 🔍 Logs de Debug (Apenas para Desenvolvimento)
918
+
919
+ *Os logs abaixo mostram o que está acontecendo nos bastidores:*
920
+ """)
921
 
922
+ # Esta seria uma área de logs no frontend
923
+ # Em um ambiente real, você pode querer implementar um sistema de logging melhor
924
+ debug_output = gr.Textbox(
925
+ label="Logs do Sistema",
926
+ lines=10,
927
+ max_lines=20,
928
+ interactive=False,
929
+ value="Os logs aparecerão aqui durante o processamento...\n\n"
930
  )
931
 
932
  gr.Markdown("""
 
939
  4. **🚀 Gere**: Clique no botão para processar
940
  5. **💾 Baixe**: Download automático em alta qualidade
941
 
942
+ ### 🐛 Solução de Problemas:
943
 
944
+ - **Erro ao carregar modelo**: O app usará um método de fallback
945
+ - **Imagens não aparecem**: Verifique se as imagens são JPG/PNG válidos
946
+ - **Processamento lento**: Reduza o número de imagens ou resolução
947
+ - **Download não funciona**: Recarregue a página e tente novamente
 
 
948
 
949
  ### 🎯 Casos de Uso:
950
 
 
956
  """)
957
 
958
  if __name__ == "__main__":
959
+ logger.info("🚀 Iniciando aplicação Gradio...")
960
+
961
+ # Configurações adicionais para Hugging Face Spaces
962
+ demo.launch(
963
+ server_name="0.0.0.0",
964
+ server_port=7860,
965
+ share=False,
966
+ debug=True,
967
+ show_error=True
968
+ )