Daniel251 commited on
Commit
a3182d5
·
verified ·
1 Parent(s): 0e9c9cb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +354 -616
app.py CHANGED
@@ -7,6 +7,7 @@ import io
7
  import tempfile
8
  import traceback
9
  import time
 
10
  from typing import List, Tuple, Optional
11
  import warnings
12
  warnings.filterwarnings("ignore")
@@ -16,7 +17,6 @@ warnings.filterwarnings("ignore")
16
  # ============================
17
  MAX_IMAGES = 10
18
  OUTPUT_MAX_SIZE_MB = 1.5
19
- PROCESS_TIMEOUT = 300 # 5 minutos máximo
20
 
21
  # Presets de resolução
22
  RESOLUTION_PRESETS = {
@@ -86,104 +86,65 @@ class CollagePosterGenerator:
86
  def __init__(self):
87
  self.device = "cuda" if torch.cuda.is_available() else "cpu"
88
  self.logger = ProcessingLogger()
89
- self.model_loaded = False
90
-
91
- def load_model(self) -> bool:
92
- """Tenta carregar modelo de remoção de fundo"""
93
- try:
94
- log = self.logger.add_log("Tentando carregar modelo de remoção de fundo...", "processing")
95
-
96
- # Usaremos rembg se disponível, caso contrário fallback
97
- try:
98
- import rembg
99
- from rembg import remove
100
- self.bg_remover = remove
101
- self.model_loaded = True
102
- log = self.logger.add_log("✅ Modelo Rembg carregado com sucesso!", "success")
103
- return True
104
- except ImportError:
105
- log = self.logger.add_log("⚠️ Rembg não disponível, usando método alternativo", "warning")
106
- self.bg_remover = None
107
- self.model_loaded = False
108
- return True # Não é erro crítico
109
-
110
- except Exception as e:
111
- log = self.logger.add_log(f"❌ Erro ao carregar modelo: {str(e)}", "error")
112
- self.bg_remover = None
113
- self.model_loaded = False
114
- return False
115
 
116
- def remove_background(self, image: Image.Image, image_num: int = 1) -> Image.Image:
117
- """Remove o fundo da imagem"""
118
- try:
119
- log = self.logger.add_log(f"Processando imagem {image_num}: Removendo fundo...", "processing")
120
-
121
- if self.bg_remover and self.model_loaded:
122
- # Usar rembg se disponível
123
- result = self.bg_remover(image)
124
- log = self.logger.add_log(f"✅ Imagem {image_num}: Fundo removido com IA", "success")
125
- return result
126
- else:
127
- # Método alternativo simples
128
- return self._simple_bg_removal(image, image_num)
129
-
130
- except Exception as e:
131
- log = self.logger.add_log(f"❌ Imagem {image_num}: Erro na remoção de fundo: {str(e)[:50]}...", "error")
132
- # Fallback: retorna imagem com fundo transparente
133
- return image.convert("RGBA")
134
-
135
- def _simple_bg_removal(self, image: Image.Image, image_num: int) -> Image.Image:
136
- """Método simples de remoção de fundo (fallback)"""
137
  try:
138
  # Converter para RGBA
139
  img = image.convert("RGBA")
140
  data = np.array(img)
141
 
142
- # Método 1: Remover fundos brancos/claros
143
  if len(data.shape) == 3 and data.shape[2] >= 3:
144
- # Calcular luminosidade
145
- luminosity = np.mean(data[:, :, :3], axis=2)
146
 
147
- # Encontrar cor dominante nos cantos (assumindo fundo)
148
  corners = []
149
- h, w = luminosity.shape
150
- for corner in [(0,0), (0,w-1), (h-1,0), (h-1,w-1)]:
151
- if corner[0] < h and corner[1] < w:
152
- corners.append(luminosity[corner])
 
 
 
 
 
 
 
153
 
154
  if corners:
155
- bg_brightness = np.mean(corners)
156
- # Criar máscara baseada na similaridade com o fundo
157
- threshold = bg_brightness * 0.9 # 90% da luminosidade do fundo
158
- mask = luminosity > threshold
 
 
 
 
 
 
 
159
 
160
  # Suavizar máscara
161
  from scipy.ndimage import binary_erosion, binary_dilation
162
-
163
- # Erodir para remover bordas
164
  mask = binary_erosion(mask, structure=np.ones((3,3)))
165
- # Dilatar para recuperar um pouco
166
- mask = binary_dilation(mask, structure=np.ones((3,3)))
167
 
168
- # Aplicar máscara ao canal alpha
169
- data[:, :, 3] = np.where(mask, 0, 255)
170
 
171
- result = Image.fromarray(data, 'RGBA')
172
- log = self.logger.add_log(f"✅ Imagem {image_num}: Fundo removido (método simples)", "success")
173
- return result
174
 
175
  except Exception as e:
176
- log = self.logger.add_log(f"⚠️ Imagem {image_num}: Fallback falhou, mantendo original", "warning")
177
  return image.convert("RGBA")
178
 
179
- def apply_border_effect(self, image: Image.Image, style: str, color: str, image_num: int) -> Image.Image:
180
  """Aplica efeitos de borda estilizados"""
181
  if style == "none":
182
  return image
183
 
184
  try:
185
- log = self.logger.add_log(f"Imagem {image_num}: Aplicando borda '{style}'...", "processing")
186
-
187
  if image.mode != 'RGBA':
188
  image = image.convert('RGBA')
189
 
@@ -205,53 +166,45 @@ class CollagePosterGenerator:
205
  (0, 0, 0, 0))
206
 
207
  # Criar sombra
208
- shadow = Image.new('RGBA', expanded.size, (0, 0, 0, 0))
209
- draw = ImageDraw.Draw(shadow)
210
-
211
- # Desenhar sombra offset
212
- shadow_positions = [(i, i) for i in range(5, shadow_size, 2)]
213
- for pos in shadow_positions:
214
- temp = Image.new('RGBA', image.size, (0, 0, 0, 30))
215
- shadow.paste(temp, pos, temp)
216
 
217
- # Aplicar blur
218
- shadow = shadow.filter(ImageFilter.GaussianBlur(radius=10))
219
-
220
- # Combinar
221
- expanded.paste(shadow, (0, 0), shadow)
222
  expanded.paste(image, (shadow_size//2, shadow_size//2), image)
 
223
 
224
  elif style == "neon_glow":
225
  # Brilho neon
226
- glow_size = 25
227
  expanded = Image.new('RGBA',
228
  (image.width + glow_size*2, image.height + glow_size*2),
229
  (0, 0, 0, 0))
230
 
231
- # Extrair alpha channel
232
  alpha = image.split()[-1]
233
 
234
- # Criar múltiplas camadas de brilho
235
  for i in range(3):
236
- size_factor = 1 + (i * 0.3)
237
- layer_size = (int(image.width * size_factor), int(image.height * size_factor))
238
  layer = alpha.resize(layer_size, Image.Resampling.LANCZOS)
239
 
240
- # Centralizar
241
- offset_x = (expanded.width - layer_size[0]) // 2
242
- offset_y = (expanded.height - layer_size[1]) // 2
243
 
244
- # Aplicar blur e cor
245
- blurred = layer.filter(ImageFilter.GaussianBlur(radius=5 + i*3))
246
  colored = Image.new('RGBA', expanded.size, rgb + (80 - i*20,))
247
  colored.putalpha(blurred)
248
 
249
- expanded.paste(colored, (offset_x, offset_y), colored)
250
 
251
- # Colar imagem original no centro
252
  center_x = (expanded.width - image.width) // 2
253
  center_y = (expanded.height - image.height) // 2
254
  expanded.paste(image, (center_x, center_y), image)
 
255
 
256
  elif style == "double_line":
257
  # Borda dupla
@@ -262,27 +215,29 @@ class CollagePosterGenerator:
262
 
263
  draw = ImageDraw.Draw(expanded)
264
 
265
- # Borda externa
266
  draw.rectangle([0, 0, expanded.width-1, expanded.height-1],
267
  outline=rgb, width=border//2)
268
- # Borda interna
 
269
  draw.rectangle([border//2, border//2,
270
  expanded.width-border//2-1, expanded.height-border//2-1],
271
  outline=(255, 255, 255), width=border//4)
272
 
273
  expanded.paste(image, (border, border), image)
 
274
 
275
  elif style == "colored_outline":
276
  # Contorno colorido
277
- outline_size = 10
278
  expanded = Image.new('RGBA',
279
  (image.width + outline_size*2, image.height + outline_size*2),
280
  (0, 0, 0, 0))
281
 
282
- # Criar contorno dilatando a máscara
283
  alpha = np.array(image.split()[-1])
284
 
285
- # Dilatar
286
  kernel = np.ones((outline_size, outline_size), np.uint8)
287
  dilated = cv2.dilate(alpha, kernel, iterations=1)
288
 
@@ -290,40 +245,28 @@ class CollagePosterGenerator:
290
  outline = dilated - alpha
291
 
292
  # Criar imagem do contorno
293
- outline_img = Image.new('RGBA', expanded.size, (0, 0, 0, 0))
294
- outline_data = np.array(outline_img)
295
- outline_data[:, :, :3] = rgb # Aplicar cor
296
- outline_data[:, :, 3] = outline # Aplicar máscara
297
-
298
- outline_img = Image.fromarray(outline_data, 'RGBA')
299
 
300
- # Combinar
301
  expanded.paste(outline_img, (0, 0), outline_img)
302
  expanded.paste(image, (outline_size, outline_size), image)
303
-
304
- log = self.logger.add_log(f"✅ Imagem {image_num}: Borda '{style}' aplicada", "success")
305
- return expanded
306
-
307
  except Exception as e:
308
- log = self.logger.add_log(f"⚠️ Imagem {image_num}: Erro na borda, mantendo original", "warning")
309
  return image
310
 
311
  def create_gradient_background(self, size: Tuple[int, int], color1: str, color2: str) -> Image.Image:
312
  """Cria fundo degradê"""
313
  try:
314
- log = self.logger.add_log("Criando fundo degradê...", "processing")
315
-
316
  width, height = size
317
 
318
- # Converter cores
319
  def hex_to_rgb(hex_color):
320
  hex_color = hex_color.lstrip('#')
321
  if len(hex_color) == 6:
322
  return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
323
- elif len(hex_color) == 3:
324
- return tuple(int(hex_color[i]*2, 16) for i in (0, 1, 2))
325
- else:
326
- return (100, 100, 200) # Azul padrão
327
 
328
  try:
329
  rgb1 = hex_to_rgb(color1)
@@ -332,11 +275,10 @@ class CollagePosterGenerator:
332
  rgb1 = (102, 126, 234)
333
  rgb2 = (118, 75, 162)
334
 
335
- # Criar degradê
336
  background = Image.new('RGB', size)
337
  draw = ImageDraw.Draw(background)
338
 
339
- # Gradiente vertical
340
  for y in range(height):
341
  ratio = y / height
342
  r = int(rgb1[0] * (1 - ratio) + rgb2[0] * ratio)
@@ -344,12 +286,10 @@ class CollagePosterGenerator:
344
  b = int(rgb1[2] * (1 - ratio) + rgb2[2] * ratio)
345
  draw.line([(0, y), (width, y)], fill=(r, g, b))
346
 
347
- log = self.logger.add_log("✅ Fundo degradê criado", "success")
348
  return background
349
 
350
  except Exception as e:
351
- log = self.logger.add_log(f"❌ Erro no fundo: {str(e)[:50]}", "error")
352
- # Fallback: fundo cinza
353
  return Image.new('RGB', size, (200, 200, 200))
354
 
355
  def add_text_with_effects(self, image: Image.Image, title: str, description: str,
@@ -359,9 +299,7 @@ class CollagePosterGenerator:
359
  if not title and not description:
360
  return image
361
 
362
- log = self.logger.add_log("Adicionando texto ao pôster...", "processing")
363
-
364
- # Converter para RGBA para suportar transparência
365
  if image.mode != 'RGBA':
366
  image = image.convert('RGBA')
367
 
@@ -370,61 +308,22 @@ class CollagePosterGenerator:
370
  draw = ImageDraw.Draw(text_layer)
371
 
372
  width, height = image.size
 
373
 
374
- # Configurar margens
375
- margin_horizontal = int(width * 0.1) # 10% das laterais
376
- margin_vertical = int(height * 0.1) # 10% superior e inferior
377
-
378
- # Carregar fontes
379
  try:
380
- # Tentar carregar fonte padrão do sistema
381
- title_size = int(min(width, height) * 0.07)
382
- desc_size = int(min(width, height) * 0.035)
383
-
384
- # Tentar várias fontes comuns
385
- font_paths = [
386
- "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
387
- "/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf",
388
- "arialbd.ttf",
389
- "Arial"
390
- ]
391
 
392
- title_font = None
393
- for path in font_paths:
394
- try:
395
- title_font = ImageFont.truetype(path, title_size)
396
- break
397
- except:
398
- continue
399
-
400
- if title_font is None:
401
- title_font = ImageFont.load_default()
402
- log = self.logger.add_log("⚠️ Usando fonte padrão para título", "warning")
403
  except:
 
404
  title_font = ImageFont.load_default()
405
-
406
- try:
407
- desc_font_paths = [
408
- "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
409
- "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf",
410
- "arial.ttf",
411
- "Arial"
412
- ]
413
-
414
- desc_font = None
415
- for path in desc_font_paths:
416
- try:
417
- desc_font = ImageFont.truetype(path, desc_size)
418
- break
419
- except:
420
- continue
421
-
422
- if desc_font is None:
423
- desc_font = ImageFont.load_default()
424
- except:
425
  desc_font = ImageFont.load_default()
426
 
427
- # Cor do texto
428
  try:
429
  hex_color = text_color.lstrip('#')
430
  if len(hex_color) == 6:
@@ -434,14 +333,11 @@ class CollagePosterGenerator:
434
  except:
435
  text_rgb = (255, 255, 255)
436
 
437
- # Posição Y inicial (partindo de baixo)
438
- y_position = height - margin_vertical
439
 
440
- # Adicionar descrição se existir
441
  if description and description.strip():
442
- log = self.logger.add_log("Formatando descrição...", "processing")
443
-
444
- # Quebrar descrição em linhas
445
  words = description.split()
446
  lines = []
447
  current_line = []
@@ -450,15 +346,14 @@ class CollagePosterGenerator:
450
  current_line.append(word)
451
  test_line = ' '.join(current_line)
452
 
453
- # Estimar largura do texto
454
  try:
455
  bbox = draw.textbbox((0, 0), test_line, font=desc_font)
456
  text_width = bbox[2] - bbox[0]
457
  except:
458
- # Estimativa aproximada
459
  text_width = len(test_line) * desc_size * 0.6
460
 
461
- if text_width > (width - 2 * margin_horizontal):
462
  if len(current_line) > 1:
463
  lines.append(' '.join(current_line[:-1]))
464
  current_line = [word]
@@ -469,12 +364,9 @@ class CollagePosterGenerator:
469
  if current_line:
470
  lines.append(' '.join(current_line))
471
 
472
- # Desenhar linhas de baixo para cima
473
  lines.reverse()
474
- line_height = int(desc_size * 1.5)
475
-
476
  for line in lines:
477
- # Calcular posição X centralizada
478
  try:
479
  bbox = draw.textbbox((0, 0), line, font=desc_font)
480
  text_width = bbox[2] - bbox[0]
@@ -483,26 +375,23 @@ class CollagePosterGenerator:
483
  text_width = len(line) * desc_size * 0.6
484
  text_height = desc_size
485
 
486
- x_position = (width - text_width) // 2
487
- y_position -= text_height + 5
488
 
489
- # Adicionar sombra colorida
490
- shadow_color = (255, 100, 100, 180) # Rosa suave com transparência
491
- for offset in [(2, 2), (-2, 2), (2, -2), (-2, -2)]:
492
- draw.text((x_position + offset[0], y_position + offset[1]),
493
- line, font=desc_font, fill=shadow_color)
494
 
495
  # Texto principal
496
- draw.text((x_position, y_position), line,
497
- font=desc_font, fill=text_rgb + (255,))
498
-
499
- y_position -= line_height
500
 
501
- # Adicionar título se existir
502
  if title and title.strip():
503
- log = self.logger.add_log("Formatando título...", "processing")
 
 
504
 
505
- # Quebrar título em linhas
506
  words = title.split()
507
  lines = []
508
  current_line = []
@@ -511,14 +400,13 @@ class CollagePosterGenerator:
511
  current_line.append(word)
512
  test_line = ' '.join(current_line)
513
 
514
- # Estimar largura
515
  try:
516
  bbox = draw.textbbox((0, 0), test_line, font=title_font)
517
  text_width = bbox[2] - bbox[0]
518
  except:
519
  text_width = len(test_line) * title_size * 0.6
520
 
521
- if text_width > (width - 2 * margin_horizontal):
522
  if len(current_line) > 1:
523
  lines.append(' '.join(current_line[:-1]))
524
  current_line = [word]
@@ -529,16 +417,9 @@ class CollagePosterGenerator:
529
  if current_line:
530
  lines.append(' '.join(current_line))
531
 
532
- # Espaço entre título e descrição
533
- if description and description.strip():
534
- y_position -= int(title_size * 0.5)
535
-
536
- # Desenhar linhas de baixo para cima
537
  lines.reverse()
538
- line_height = int(title_size * 1.8)
539
-
540
  for line in lines:
541
- # Calcular posição X centralizada
542
  try:
543
  bbox = draw.textbbox((0, 0), line, font=title_font)
544
  text_width = bbox[2] - bbox[0]
@@ -547,35 +428,27 @@ class CollagePosterGenerator:
547
  text_width = len(line) * title_size * 0.6
548
  text_height = title_size
549
 
550
- x_position = (width - text_width) // 2
551
- y_position -= text_height + 10
552
 
553
- # Sombra mais pronunciada para o título
554
- shadow_color = (100, 150, 255, 220) # Azul suave
555
- for offset in [(3, 3), (-3, 3), (3, -3), (-3, -3), (0, 3), (0, -3)]:
556
- draw.text((x_position + offset[0], y_position + offset[1]),
557
- line, font=title_font, fill=shadow_color)
558
 
559
  # Texto principal
560
- draw.text((x_position, y_position), line,
561
- font=title_font, fill=text_rgb + (255,))
562
-
563
- y_position -= line_height
564
 
565
  # Combinar camadas
566
- result = Image.alpha_composite(image, text_layer)
567
- log = self.logger.add_log("✅ Texto adicionado com sucesso", "success")
568
- return result
569
 
570
  except Exception as e:
571
- log = self.logger.add_log(f"⚠️ Erro ao adicionar texto: {str(e)[:50]}", "warning")
572
  return image
573
 
574
  def compose_collage(self, images: List[Image.Image], background: Image.Image) -> Image.Image:
575
  """Compõe as imagens em um collage"""
576
  try:
577
- log = self.logger.add_log(f"Compondo collage com {len(images)} imagens...", "processing")
578
-
579
  result = background.copy().convert('RGBA')
580
  bg_width, bg_height = background.size
581
 
@@ -584,13 +457,13 @@ class CollagePosterGenerator:
584
 
585
  num_images = len(images)
586
 
587
- # Layout inteligente baseado no número de imagens
588
  if num_images == 1:
589
  # Imagem única no centro
590
  img = images[0]
591
  img.thumbnail((bg_width // 2, bg_height // 2), Image.Resampling.LANCZOS)
592
  x = (bg_width - img.width) // 2
593
- y = (bg_height - img.height) // 3 # Um pouco acima do centro
594
  result.paste(img, (x, y), img)
595
 
596
  elif num_images <= 4:
@@ -598,34 +471,16 @@ class CollagePosterGenerator:
598
  cols = 2
599
  rows = 2
600
  cell_width = bg_width // (cols + 1)
601
- cell_height = bg_height // (rows + 2) # Mais espaço para texto
602
-
603
- for idx, img in enumerate(images):
604
- row = idx // cols
605
- col = idx % cols
606
-
607
- img.thumbnail((cell_width * 0.8, cell_height * 0.8), Image.Resampling.LANCZOS)
608
-
609
- x = (col + 1) * cell_width - img.width // 2
610
- y = (row + 1) * cell_height - img.height // 2
611
-
612
- result.paste(img, (x, y), img)
613
-
614
- elif num_images <= 9:
615
- # Grid 3x3
616
- cols = 3
617
- rows = 3
618
- cell_width = bg_width // (cols + 1)
619
  cell_height = bg_height // (rows + 2)
620
 
621
  for idx, img in enumerate(images):
622
- if idx >= cols * rows: # Não exceder o grid
623
  break
624
-
625
  row = idx // cols
626
  col = idx % cols
627
 
628
- img.thumbnail((cell_width * 0.7, cell_height * 0.7), Image.Resampling.LANCZOS)
629
 
630
  x = (col + 1) * cell_width - img.width // 2
631
  y = (row + 1) * cell_height - img.height // 2
@@ -633,12 +488,12 @@ class CollagePosterGenerator:
633
  result.paste(img, (x, y), img)
634
 
635
  else:
636
- # Layout circular para muitas imagens
637
  center_x, center_y = bg_width // 2, bg_height // 3
638
  radius = min(bg_width, bg_height) // 4
639
 
640
- for idx, img in enumerate(images):
641
- angle = 2 * 3.14159 * idx / min(num_images, 12) # Máximo 12 imagens no círculo
642
 
643
  img.thumbnail((bg_width // 6, bg_height // 6), Image.Resampling.LANCZOS)
644
 
@@ -647,163 +502,145 @@ class CollagePosterGenerator:
647
 
648
  result.paste(img, (x, y), img)
649
 
650
- log = self.logger.add_log("✅ Collage composta com sucesso", "success")
651
  return result.convert('RGB')
652
 
653
  except Exception as e:
654
- log = self.logger.add_log(f"❌ Erro na composição: {str(e)[:50]}", "error")
655
  return background.convert('RGB')
656
 
657
  def optimize_file_size(self, image: Image.Image) -> Image.Image:
658
  """Otimiza o tamanho do arquivo"""
659
  try:
660
- log = self.logger.add_log("Otimizando tamanho do arquivo...", "processing")
661
-
662
  if image.mode == 'RGBA':
663
  image = image.convert('RGB')
664
 
665
  # Tentar diferentes qualidades
666
- for quality in [95, 90, 85, 80, 75, 70]:
667
  buffer = io.BytesIO()
668
  image.save(buffer, format='JPEG', quality=quality, optimize=True)
669
  size_mb = len(buffer.getvalue()) / (1024 * 1024)
670
 
671
  if size_mb <= OUTPUT_MAX_SIZE_MB:
672
  buffer.seek(0)
673
- result = Image.open(buffer).copy()
674
- log = self.logger.add_log(f"✅ Arquivo otimizado: {size_mb:.2f}MB (qualidade: {quality}%)", "success")
675
- return result
676
 
677
- # Se não conseguir, usar qualidade 70% mesmo assim
678
  buffer = io.BytesIO()
679
  image.save(buffer, format='JPEG', quality=70, optimize=True)
680
  buffer.seek(0)
681
- result = Image.open(buffer).copy()
682
- size_mb = len(buffer.getvalue()) / (1024 * 1024)
683
- log = self.logger.add_log(f"⚠️ Arquivo grande: {size_mb:.2f}MB", "warning")
684
- return result
685
 
686
  except Exception as e:
687
- log = self.logger.add_log(f"⚠️ Erro na otimização: {str(e)[:50]}", "warning")
688
  return image
689
 
690
- def generate_poster(self, images: List, resolution_preset: str,
691
- custom_width: int, custom_height: int,
692
- border_style: str, border_color: str,
693
- gradient_color1: str, gradient_color2: str,
694
- title: str, description: str, text_color: str) -> Tuple[Optional[Image.Image], str, str]:
695
- """Gera o pôster final - função principal"""
696
 
697
- # Iniciar novo processo
698
  self.logger.clear()
699
- log_msg = self.logger.add_log("🚀 INICIANDO GERAÇÃO DE PÔSTER", "info")
700
 
701
  try:
702
- # ============= VALIDAÇÃO INICIAL =============
703
- if not images or len(images) == 0:
704
- log_msg = self.logger.add_log("❌ Nenhuma imagem fornecida", "error")
705
- return None, "❌ Por favor, faça upload de pelo menos uma imagem", log_msg
706
 
707
- log_msg = self.logger.add_log(f"📸 {len(images)} imagem(ns) recebida(s)", "success")
 
 
708
 
709
- # ============= DETERMINAR RESOLUÇÃO =============
 
 
710
  if resolution_preset == "Custom":
711
- if not custom_width or not custom_height or custom_width <= 0 or custom_height <= 0:
712
- log_msg = self.logger.add_log("❌ Dimensões customizadas inválidas", "error")
713
- return None, "❌ Defina largura e altura válidas (números positivos)", log_msg
714
-
715
  try:
716
  size = (int(custom_width), int(custom_height))
717
- log_msg = self.logger.add_log(f"📐 Resolução customizada: {size[0]}x{size[1]}px", "info")
718
  except:
719
- log_msg = self.logger.add_log("❌ Dimensões inválidas", "error")
720
- return None, "❌ Use números inteiros para largura e altura", log_msg
721
  else:
722
  size = RESOLUTION_PRESETS.get(resolution_preset, (1080, 1080))
723
- log_msg = self.logger.add_log(f"📐 Resolução: {resolution_preset} ({size[0]}x{size[1]}px)", "info")
724
 
725
- # ============= CARREGAR MODELO =============
726
- self.load_model()
727
-
728
- # ============= PROCESSAR IMAGENS =============
729
  processed_images = []
730
- total_images = min(len(images), MAX_IMAGES)
731
-
732
- log_msg = self.logger.add_log(f"🔄 Processando {total_images} imagem(ns)...", "processing")
733
 
734
- for idx, img_array in enumerate(images[:MAX_IMAGES]):
735
  try:
736
- log_msg = self.logger.add_log(f"Imagem {idx+1}/{total_images}: Convertendo...", "processing")
737
-
738
- # Converter numpy array para PIL Image
739
- if isinstance(img_array, np.ndarray):
740
- pil_img = Image.fromarray(img_array)
741
  else:
742
- # Tentar abrir como arquivo
743
- pil_img = Image.open(io.BytesIO(img_array))
744
 
745
- log_msg = self.logger.add_log(f"Imagem {idx+1}: Removendo fundo...", "processing")
 
746
 
747
- # Remover fundo
748
- bg_removed = self.remove_background(pil_img, idx+1)
 
749
 
750
- log_msg = self.logger.add_log(f"Imagem {idx+1}: Aplicando borda...", "processing")
751
 
752
- # Aplicar efeito de borda
 
 
 
 
753
  border_key = BORDER_STYLES.get(border_style, "none")
754
- bordered = self.apply_border_effect(bg_removed, border_key, border_color, idx+1)
 
 
 
 
 
755
 
756
- processed_images.append(bordered)
757
- log_msg = self.logger.add_log(f"✅ Imagem {idx+1} processada", "success")
758
 
759
  except Exception as e:
760
- error_msg = str(e)[:100]
761
- log_msg = self.logger.add_log(f"⚠️ Imagem {idx+1} ignorada: {error_msg}", "warning")
762
- continue
763
 
764
  if not processed_images:
765
- log_msg = self.logger.add_log("❌ Nenhuma imagem processada com sucesso", "error")
766
- return None, "❌ Não foi possível processar nenhuma imagem", log_msg
767
 
768
- log_msg = self.logger.add_log(f"✅ {len(processed_images)} imagem(ns) processada(s)", "success")
769
 
770
- # ============= CRIAR FUNDO =============
771
- log_msg = self.logger.add_log("🎨 Criando fundo degradê...", "processing")
772
  background = self.create_gradient_background(size, gradient_color1, gradient_color2)
773
 
774
- # ============= COMPOR COLLAGE =============
775
- log_msg = self.logger.add_log("🖼️ Criando composição...", "processing")
776
  collage = self.compose_collage(processed_images, background)
777
 
778
- # ============= ADICIONAR TEXTO =============
779
  if title or description:
780
- log_msg = self.logger.add_log("✍️ Adicionando texto...", "processing")
781
  collage = self.add_text_with_effects(collage, title, description, text_color)
782
 
783
- # ============= OTIMIZAR TAMANHO =============
784
- log_msg = self.logger.add_log("🗜️ Otimizando arquivo...", "processing")
785
  final_image = self.optimize_file_size(collage)
786
 
787
- # ============= CONCLUIR =============
788
- log_msg = self.logger.add_log("🎉 Pôster gerado com sucesso!", "success")
789
- final_message = f"✅ Pôster gerado! {len(processed_images)} imagem(ns), {size[0]}x{size[1]}px"
790
 
791
- return final_image, final_message, log_msg
 
792
 
793
  except Exception as e:
794
- error_details = str(e)[:200]
795
- log_msg = self.logger.add_log(f"❌ ERRO CRÍTICO: {error_details}", "error")
796
- log_msg = self.logger.add_log("🔍 Detalhes técnicos foram registrados", "info")
797
-
798
- # Log completo para debug
799
- import traceback
800
- full_trace = traceback.format_exc()
801
- print("=" * 50)
802
- print("TRACEBACK COMPLETO:")
803
- print(full_trace)
804
- print("=" * 50)
805
-
806
- return None, f"❌ Erro ao gerar pôster: {error_details}", log_msg
807
 
808
  # ============================
809
  # INTERFACE GRADIO
@@ -812,93 +649,91 @@ class CollagePosterGenerator:
812
  # Inicializar gerador
813
  generator = CollagePosterGenerator()
814
 
815
- # Função para atualizar logs em tempo real
816
- def update_logs_display(log_text):
817
- """Formata logs para exibição"""
818
  lines = log_text.split('\n')
819
- formatted_lines = []
820
 
821
  for line in lines:
822
  if '❌' in line:
823
- formatted_lines.append(f"<span style='color: #ff4444; font-weight: bold;'>{line}</span>")
824
  elif '✅' in line:
825
- formatted_lines.append(f"<span style='color: #44ff44;'>{line}</span>")
826
  elif '⚠️' in line:
827
- formatted_lines.append(f"<span style='color: #ffff44;'>{line}</span>")
828
  elif '🔄' in line:
829
- formatted_lines.append(f"<span style='color: #4444ff;'>{line}</span>")
830
  elif '🚀' in line:
831
- formatted_lines.append(f"<span style='color: #ff44ff; font-weight: bold;'>{line}</span>")
 
 
 
 
832
  else:
833
- formatted_lines.append(f"<span style='color: #cccccc;'>{line}</span>")
834
 
835
- return "<br>".join(formatted_lines)
836
 
837
  with gr.Blocks(theme=gr.themes.Soft(), title="Gerador de Pôster de Colagem") as demo:
838
  gr.Markdown("""
839
- # 🎨 Gerador de Pôster de Colagem Profissional
840
 
841
- Crie pôsteres incríveis com múltiplas imagens, remoção de fundo automática e efeitos especiais!
842
  """)
843
 
844
  with gr.Row():
845
  with gr.Column(scale=1):
 
846
  gr.Markdown("### 📤 Upload de Imagens")
 
 
 
 
 
 
847
 
848
- # Área de upload melhorada
849
- with gr.Group():
850
- image_input = gr.File(
851
- label="Selecione imagens (até 10)",
852
- file_types=["image"],
853
- file_count="multiple",
854
- type="bytes",
855
- height=100
856
- )
857
-
858
- preview_gallery = gr.Gallery(
859
- label="Pré-visualização",
860
- columns=3,
861
- height=200,
862
- visible=False
863
- )
864
 
865
- gr.Markdown("### ⚙️ Configurações do Pôster")
 
866
 
867
  with gr.Group():
868
  resolution_preset = gr.Dropdown(
869
- label="📐 Tamanho do Pôster",
870
  choices=list(RESOLUTION_PRESETS.keys()),
871
- value="Instagram Post (1:1)",
872
- interactive=True
873
  )
874
 
875
- with gr.Row(visible=False) as custom_res_row:
876
  custom_width = gr.Number(
877
- label="Largura (pixels)",
878
  value=1080,
879
  minimum=100,
880
- maximum=10000,
881
- step=10
882
  )
883
  custom_height = gr.Number(
884
- label="Altura (pixels)",
885
  value=1080,
886
  minimum=100,
887
- maximum=10000,
888
- step=10
889
  )
890
 
891
  with gr.Group():
892
  border_style = gr.Dropdown(
893
- label="🖼️ Estilo das Bordas",
894
  choices=list(BORDER_STYLES.keys()),
895
  value="Sombra Suave"
896
  )
897
 
898
  border_color = gr.ColorPicker(
899
- label="🎨 Cor dos Efeitos",
900
- value="#00AAFF",
901
- interactive=True
902
  )
903
 
904
  with gr.Group():
@@ -906,263 +741,183 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Gerador de Pôster de Colagem") as
906
  with gr.Row():
907
  gradient_color1 = gr.ColorPicker(
908
  label="Cor Superior",
909
- value="#667EEA",
910
- interactive=True
911
  )
912
  gradient_color2 = gr.ColorPicker(
913
  label="Cor Inferior",
914
- value="#764BA2",
915
- interactive=True
916
  )
917
 
918
  with gr.Group():
919
- gr.Markdown("### 📝 Texto do Pôster")
920
 
921
  title_input = gr.Textbox(
922
- label="Título Principal",
923
- placeholder="Ex: Minhas Férias 2024",
924
- max_lines=2,
925
- interactive=True
926
  )
927
 
928
  description_input = gr.Textbox(
929
- label="Descrição",
930
- placeholder="Ex: Momentos especiais capturados",
931
- lines=2,
932
- interactive=True
933
  )
934
 
935
  text_color = gr.ColorPicker(
936
- label="🎨 Cor do Texto",
937
- value="#FFFFFF",
938
- interactive=True
939
  )
940
 
 
941
  with gr.Row():
942
  process_btn = gr.Button(
943
  "🚀 Gerar Pôster",
944
  variant="primary",
945
- size="lg",
946
  scale=2
947
  )
948
-
949
  clear_btn = gr.Button(
950
- "🗑️ Limpar Tudo",
951
  variant="secondary",
952
  scale=1
953
  )
954
 
955
  with gr.Column(scale=2):
956
- gr.Markdown("### 👁️ Preview do Pôster")
 
957
 
958
- # Área de resultado
959
  output_image = gr.Image(
960
- label="Pôster Gerado",
961
  type="pil",
962
- height=500,
963
- interactive=False
964
  )
965
 
966
- # Status e logs
967
- status_text = gr.Markdown(
968
- "💡 **Status:** Aguardando imagens...\n\n"
969
- "**Instruções:**\n"
970
- "1. Faça upload de imagens\n"
971
- "2. Configure as opções\n"
972
- "3. Clique em 'Gerar Pôster'"
973
- )
974
 
975
- # Logs em tempo real
 
 
 
 
 
 
976
  logs_display = gr.HTML(
977
- label="📋 Logs do Processamento",
978
- value="<div style='background: #1a1a1a; padding: 10px; border-radius: 5px; font-family: monospace;'>"
979
- "<span style='color: #888;'>Aguardando processamento...</span>"
980
- "</div>"
981
  )
982
 
983
- # Área de download
984
- with gr.Group():
985
- gr.Markdown("### 💾 Download")
986
-
987
- with gr.Row():
988
- download_btn = gr.DownloadButton(
989
- "⬇️ Baixar Pôster (JPEG)",
990
- visible=False,
991
- size="lg"
992
- )
993
-
994
- download_png_btn = gr.DownloadButton(
995
- "⬇️ Baixar Pôster (PNG)",
996
- visible=False,
997
- size="lg"
998
- )
999
 
1000
- # ============= FUNÇÕES AUXILIARES =============
1001
 
1002
- def handle_image_upload(files):
1003
- """Processa upload de imagens"""
1004
  if not files:
1005
  return gr.update(visible=False), []
1006
 
1007
- images = []
1008
  previews = []
1009
-
1010
- for i, file in enumerate(files[:MAX_IMAGES]):
1011
  try:
1012
- # Ler imagem
1013
- img = Image.open(io.BytesIO(file))
1014
-
1015
- # Converter para RGB se necessário
1016
- if img.mode != 'RGB':
1017
- img = img.convert('RGB')
1018
-
1019
- # Reduzir para preview
1020
- preview = img.copy()
1021
- preview.thumbnail((200, 200), Image.Resampling.LANCZOS)
1022
-
1023
- # Converter para numpy para o Gallery
1024
- preview_np = np.array(preview)
1025
-
1026
- images.append(file) # Manter bytes originais
1027
- previews.append(preview_np)
1028
-
1029
- except Exception as e:
1030
- print(f"Erro ao processar imagem {i}: {e}")
1031
  continue
1032
 
1033
- return gr.update(visible=True, value=previews), images
1034
-
1035
- def clear_all():
1036
- """Limpa tudo"""
1037
- return [
1038
- None, # image_input
1039
- gr.update(visible=False, value=None), # preview_gallery
1040
- [], # image_input value
1041
- None, # output_image
1042
- "💡 **Status:** Aguardando imagens...", # status_text
1043
- "<div style='background: #1a1a1a; padding: 10px; border-radius: 5px; font-family: monospace;'>"
1044
- "<span style='color: #888;'>Pronto para novo processamento...</span>"
1045
- "</div>", # logs_display
1046
- gr.update(visible=False), # download_btn
1047
- gr.update(visible=False) # download_png_btn
1048
- ]
1049
 
1050
- def toggle_custom_resolution(choice):
1051
  """Mostra/esconde campos de resolução customizada"""
1052
  return gr.update(visible=choice == "Custom")
1053
 
1054
- def process_poster(images, *args):
1055
- """Processa o pôster - função principal"""
1056
- if not images or len(images) == 0:
1057
  return [
1058
  None,
1059
- "❌ **Erro:** Nenhuma imagem fornecida",
1060
- "<div style='background: #1a1a1a; padding: 10px; border-radius: 5px; font-family: monospace; color: #ff4444;'>"
1061
- "❌ Por favor, faça upload de pelo menos uma imagem"
1062
- "</div>",
1063
  gr.update(visible=False),
1064
  gr.update(visible=False)
1065
  ]
1066
 
1067
- try:
1068
- # Converter bytes para numpy arrays
1069
- numpy_images = []
1070
- for img_bytes in images:
1071
- img = Image.open(io.BytesIO(img_bytes))
1072
- if img.mode != 'RGB':
1073
- img = img.convert('RGB')
1074
- numpy_images.append(np.array(img))
1075
-
1076
- # Gerar pôster
1077
- result_img, result_msg, logs = generator.generate_poster(
1078
- numpy_images, *args
1079
- )
1080
-
1081
- # Formatar logs para HTML
1082
- formatted_logs = update_logs_display(logs)
1083
- html_logs = f"""
1084
- <div style='
1085
- background: #1a1a1a;
1086
- padding: 15px;
1087
- border-radius: 5px;
1088
- font-family: monospace;
1089
- font-size: 12px;
1090
- max-height: 300px;
1091
- overflow-y: auto;
1092
- line-height: 1.4;
1093
- '>
1094
- {formatted_logs}
1095
- </div>
1096
- """
1097
 
1098
- if result_img is not None:
1099
- # Salvar para download
1100
- jpeg_temp = tempfile.NamedTemporaryFile(delete=False, suffix='.jpg')
1101
- result_img.save(jpeg_temp.name, 'JPEG', quality=90, optimize=True)
1102
-
1103
- png_temp = tempfile.NamedTemporaryFile(delete=False, suffix='.png')
1104
  result_img.save(png_temp.name, 'PNG')
1105
-
1106
- return [
1107
- result_img,
1108
- result_msg,
1109
- html_logs,
1110
- gr.update(visible=True, value=jpeg_temp.name),
1111
- gr.update(visible=True, value=png_temp.name)
1112
- ]
1113
  else:
1114
- return [
1115
- None,
1116
- result_msg,
1117
- html_logs,
1118
- gr.update(visible=False),
1119
- gr.update(visible=False)
1120
- ]
1121
-
1122
- except Exception as e:
1123
- error_msg = f"❌ **Erro crítico:** {str(e)[:100]}"
1124
- error_logs = f"""
1125
- <div style='
1126
- background: #1a1a1a;
1127
- padding: 15px;
1128
- border-radius: 5px;
1129
- font-family: monospace;
1130
- color: #ff4444;
1131
- font-size: 12px;
1132
- '>
1133
- ❌ ERRO NO PROCESSAMENTO<br>
1134
- Detalhes: {str(e)[:200]}<br><br>
1135
- Tente novamente com menos imagens ou resolução menor.
1136
- </div>
1137
- """
1138
 
 
 
 
 
 
 
 
 
1139
  return [
1140
  None,
1141
- error_msg,
1142
- error_logs,
1143
  gr.update(visible=False),
1144
  gr.update(visible=False)
1145
  ]
1146
 
1147
- # ============= EVENTOS =============
 
 
 
 
 
 
 
 
 
 
 
 
 
1148
 
1149
  # Upload de imagens
1150
  image_input.change(
1151
- fn=handle_image_upload,
1152
  inputs=[image_input],
1153
  outputs=[preview_gallery, image_input]
1154
  )
1155
 
1156
  # Alternar resolução customizada
1157
  resolution_preset.change(
1158
- fn=toggle_custom_resolution,
1159
  inputs=[resolution_preset],
1160
- outputs=[custom_res_row]
1161
  )
1162
 
1163
  # Botão Gerar
1164
  process_btn.click(
1165
- fn=process_poster,
1166
  inputs=[
1167
  image_input,
1168
  resolution_preset,
@@ -1180,8 +935,8 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Gerador de Pôster de Colagem") as
1180
  output_image,
1181
  status_text,
1182
  logs_display,
1183
- download_btn,
1184
- download_png_btn
1185
  ]
1186
  )
1187
 
@@ -1195,65 +950,48 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Gerador de Pôster de Colagem") as
1195
  output_image,
1196
  status_text,
1197
  logs_display,
1198
- download_btn,
1199
- download_png_btn
1200
  ]
1201
  )
1202
 
1203
- # ============= INSTRUÇÕES =============
1204
  gr.Markdown("""
1205
  ---
1206
- ### 📋 **Guia Passo a Passo:**
1207
-
1208
- 1. **📤 Upload de Imagens** (até 10)
1209
- - Clique ou arraste imagens
1210
- - Formatos suportados: JPG, PNG, GIF, BMP
1211
- - As imagens aparecerão na pré-visualização
1212
-
1213
- 2. **⚙️ Configurações:**
1214
- - **Tamanho:** Escolha formato pronto ou customizado
1215
- - **Bordas:** 4 estilos diferentes disponíveis
1216
- - **Cores:** Personalize cores de fundo, bordas e texto
1217
- - **Texto:** Adicione título e descrição (opcional)
1218
-
1219
- 3. **🚀 Geração:**
1220
- - Clique em "Gerar Pôster"
1221
- - Acompanhe o progresso nos logs
1222
- - Processo pode levar alguns segundos
1223
-
1224
- 4. **💾 Download:**
1225
- - Baixe em JPEG (menor tamanho) ou PNG (maior qualidade)
1226
- - Arquivos otimizados para web
1227
-
1228
- ### 🛠️ **Solução de Problemas:**
1229
-
1230
- - **❌ "Nenhuma imagem processada":** Tente com imagens menores ou formato diferente
1231
- - **⚠️ "Algumas imagens ignoradas":** Verifique formato das imagens
1232
- - **⏳ Processamento lento:** Reduza número de imagens ou resolução
1233
- - **📁 Download não funciona:** Recarregue a página e tente novamente
1234
-
1235
- ### 💡 **Dicas:**
1236
-
1237
- - Use imagens com fundo simples para melhor remoção
1238
- - Para melhores resultados, use imagens com boa iluminação
1239
- - Teste diferentes estilos de borda para cada tipo de imagem
1240
- - Reserve espaço para texto escolhendo resoluções maiores
1241
  """)
1242
 
1243
  # ============================
1244
- # CONFIGURAÇÃO DO APLICATIVO
1245
  # ============================
1246
 
1247
  if __name__ == "__main__":
1248
  print("🚀 Iniciando Gerador de Pôster de Colagem...")
1249
- print("📦 Versão: 2.0 - Com logs detalhados")
1250
- print("⚙️ Pronto para processamento!")
1251
 
1252
- # Configurações para Hugging Face
1253
  demo.launch(
1254
  server_name="0.0.0.0",
1255
  server_port=7860,
1256
- share=False,
1257
- debug=False,
1258
- show_error=True
1259
  )
 
7
  import tempfile
8
  import traceback
9
  import time
10
+ import os
11
  from typing import List, Tuple, Optional
12
  import warnings
13
  warnings.filterwarnings("ignore")
 
17
  # ============================
18
  MAX_IMAGES = 10
19
  OUTPUT_MAX_SIZE_MB = 1.5
 
20
 
21
  # Presets de resolução
22
  RESOLUTION_PRESETS = {
 
86
  def __init__(self):
87
  self.device = "cuda" if torch.cuda.is_available() else "cpu"
88
  self.logger = ProcessingLogger()
89
+ print(f"⚙️ Dispositivo: {self.device}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
 
91
+ def remove_background_simple(self, image: Image.Image) -> Image.Image:
92
+ """Remove fundo usando método simples"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  try:
94
  # Converter para RGBA
95
  img = image.convert("RGBA")
96
  data = np.array(img)
97
 
 
98
  if len(data.shape) == 3 and data.shape[2] >= 3:
99
+ # Método 1: Detectar cantos como fundo
100
+ h, w = data.shape[:2]
101
 
102
+ # Amostrar cantos para determinar cor do fundo
103
  corners = []
104
+ sample_size = min(10, h//10, w//10)
105
+
106
+ # Canto superior esquerdo
107
+ if sample_size > 0:
108
+ corners.append(data[:sample_size, :sample_size, :3].mean(axis=(0,1)))
109
+ # Canto superior direito
110
+ corners.append(data[:sample_size, -sample_size:, :3].mean(axis=(0,1)))
111
+ # Canto inferior esquerdo
112
+ corners.append(data[-sample_size:, :sample_size, :3].mean(axis=(0,1)))
113
+ # Canto inferior direito
114
+ corners.append(data[-sample_size:, -sample_size:, :3].mean(axis=(0,1)))
115
 
116
  if corners:
117
+ bg_color = np.mean(corners, axis=0)
118
+
119
+ # Calcular distância de cada pixel para a cor do fundo
120
+ color_diff = np.sqrt(np.sum((data[:, :, :3] - bg_color) ** 2, axis=2))
121
+
122
+ # Normalizar e criar máscara
123
+ max_diff = np.max(color_diff)
124
+ if max_diff > 0:
125
+ mask = (color_diff / max_diff) > 0.3 # Threshold ajustável
126
+ else:
127
+ mask = np.zeros((h, w), dtype=bool)
128
 
129
  # Suavizar máscara
130
  from scipy.ndimage import binary_erosion, binary_dilation
 
 
131
  mask = binary_erosion(mask, structure=np.ones((3,3)))
132
+ mask = binary_dilation(mask, structure=np.ones((5,5)))
 
133
 
134
+ data[:, :, 3] = np.where(mask, 255, 0)
 
135
 
136
+ return Image.fromarray(data, 'RGBA')
 
 
137
 
138
  except Exception as e:
139
+ print(f"⚠️ Erro no remove_background_simple: {e}")
140
  return image.convert("RGBA")
141
 
142
+ def apply_border_effect(self, image: Image.Image, style: str, color: str) -> Image.Image:
143
  """Aplica efeitos de borda estilizados"""
144
  if style == "none":
145
  return image
146
 
147
  try:
 
 
148
  if image.mode != 'RGBA':
149
  image = image.convert('RGBA')
150
 
 
166
  (0, 0, 0, 0))
167
 
168
  # Criar sombra
169
+ for i in range(5, shadow_size, 3):
170
+ alpha = 100 - (i * 5)
171
+ if alpha > 0:
172
+ shadow = Image.new('RGBA', image.size, (0, 0, 0, alpha))
173
+ expanded.paste(shadow, (i, i), shadow)
 
 
 
174
 
 
 
 
 
 
175
  expanded.paste(image, (shadow_size//2, shadow_size//2), image)
176
+ return expanded
177
 
178
  elif style == "neon_glow":
179
  # Brilho neon
180
+ glow_size = 15
181
  expanded = Image.new('RGBA',
182
  (image.width + glow_size*2, image.height + glow_size*2),
183
  (0, 0, 0, 0))
184
 
185
+ # Extrair alpha
186
  alpha = image.split()[-1]
187
 
188
+ # Criar camadas de brilho
189
  for i in range(3):
190
+ layer_size = (image.width + i*10, image.height + i*10)
 
191
  layer = alpha.resize(layer_size, Image.Resampling.LANCZOS)
192
 
193
+ # Aplicar blur
194
+ blurred = layer.filter(ImageFilter.GaussianBlur(radius=5 + i*2))
 
195
 
196
+ # Criar camada colorida
197
+ offset = (expanded.width - layer_size[0]) // 2
198
  colored = Image.new('RGBA', expanded.size, rgb + (80 - i*20,))
199
  colored.putalpha(blurred)
200
 
201
+ expanded.paste(colored, (offset, offset), colored)
202
 
203
+ # Colar imagem original
204
  center_x = (expanded.width - image.width) // 2
205
  center_y = (expanded.height - image.height) // 2
206
  expanded.paste(image, (center_x, center_y), image)
207
+ return expanded
208
 
209
  elif style == "double_line":
210
  # Borda dupla
 
215
 
216
  draw = ImageDraw.Draw(expanded)
217
 
218
+ # Borda externa colorida
219
  draw.rectangle([0, 0, expanded.width-1, expanded.height-1],
220
  outline=rgb, width=border//2)
221
+
222
+ # Borda interna branca
223
  draw.rectangle([border//2, border//2,
224
  expanded.width-border//2-1, expanded.height-border//2-1],
225
  outline=(255, 255, 255), width=border//4)
226
 
227
  expanded.paste(image, (border, border), image)
228
+ return expanded
229
 
230
  elif style == "colored_outline":
231
  # Contorno colorido
232
+ outline_size = 8
233
  expanded = Image.new('RGBA',
234
  (image.width + outline_size*2, image.height + outline_size*2),
235
  (0, 0, 0, 0))
236
 
237
+ # Obter máscara alpha
238
  alpha = np.array(image.split()[-1])
239
 
240
+ # Dilatar para criar contorno
241
  kernel = np.ones((outline_size, outline_size), np.uint8)
242
  dilated = cv2.dilate(alpha, kernel, iterations=1)
243
 
 
245
  outline = dilated - alpha
246
 
247
  # Criar imagem do contorno
248
+ outline_img = Image.new('RGBA', expanded.size, rgb)
249
+ outline_img.putalpha(Image.fromarray(outline))
 
 
 
 
250
 
 
251
  expanded.paste(outline_img, (0, 0), outline_img)
252
  expanded.paste(image, (outline_size, outline_size), image)
253
+ return expanded
254
+
 
 
255
  except Exception as e:
256
+ print(f"⚠️ Erro no apply_border_effect: {e}")
257
  return image
258
 
259
  def create_gradient_background(self, size: Tuple[int, int], color1: str, color2: str) -> Image.Image:
260
  """Cria fundo degradê"""
261
  try:
 
 
262
  width, height = size
263
 
264
+ # Converter cores hex para RGB
265
  def hex_to_rgb(hex_color):
266
  hex_color = hex_color.lstrip('#')
267
  if len(hex_color) == 6:
268
  return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
269
+ return (100, 100, 200) # Azul padrão
 
 
 
270
 
271
  try:
272
  rgb1 = hex_to_rgb(color1)
 
275
  rgb1 = (102, 126, 234)
276
  rgb2 = (118, 75, 162)
277
 
278
+ # Criar degradê vertical
279
  background = Image.new('RGB', size)
280
  draw = ImageDraw.Draw(background)
281
 
 
282
  for y in range(height):
283
  ratio = y / height
284
  r = int(rgb1[0] * (1 - ratio) + rgb2[0] * ratio)
 
286
  b = int(rgb1[2] * (1 - ratio) + rgb2[2] * ratio)
287
  draw.line([(0, y), (width, y)], fill=(r, g, b))
288
 
 
289
  return background
290
 
291
  except Exception as e:
292
+ print(f"⚠️ Erro no create_gradient_background: {e}")
 
293
  return Image.new('RGB', size, (200, 200, 200))
294
 
295
  def add_text_with_effects(self, image: Image.Image, title: str, description: str,
 
299
  if not title and not description:
300
  return image
301
 
302
+ # Converter para RGBA
 
 
303
  if image.mode != 'RGBA':
304
  image = image.convert('RGBA')
305
 
 
308
  draw = ImageDraw.Draw(text_layer)
309
 
310
  width, height = image.size
311
+ margin = int(min(width, height) * 0.08)
312
 
313
+ # Configurar fontes
 
 
 
 
314
  try:
315
+ title_size = int(min(width, height) * 0.06)
316
+ desc_size = int(min(width, height) * 0.03)
 
 
 
 
 
 
 
 
 
317
 
318
+ # Tentar carregar fontes do sistema
319
+ title_font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", title_size)
320
+ desc_font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", desc_size)
 
 
 
 
 
 
 
 
321
  except:
322
+ # Fallback para fontes padrão
323
  title_font = ImageFont.load_default()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
324
  desc_font = ImageFont.load_default()
325
 
326
+ # Converter cor do texto
327
  try:
328
  hex_color = text_color.lstrip('#')
329
  if len(hex_color) == 6:
 
333
  except:
334
  text_rgb = (255, 255, 255)
335
 
336
+ # Posicionamento do texto (de baixo para cima)
337
+ y_position = height - margin
338
 
339
+ # Adicionar descrição
340
  if description and description.strip():
 
 
 
341
  words = description.split()
342
  lines = []
343
  current_line = []
 
346
  current_line.append(word)
347
  test_line = ' '.join(current_line)
348
 
349
+ # Estimar largura
350
  try:
351
  bbox = draw.textbbox((0, 0), test_line, font=desc_font)
352
  text_width = bbox[2] - bbox[0]
353
  except:
 
354
  text_width = len(test_line) * desc_size * 0.6
355
 
356
+ if text_width > (width - 2 * margin):
357
  if len(current_line) > 1:
358
  lines.append(' '.join(current_line[:-1]))
359
  current_line = [word]
 
364
  if current_line:
365
  lines.append(' '.join(current_line))
366
 
367
+ # Desenhar linhas
368
  lines.reverse()
 
 
369
  for line in lines:
 
370
  try:
371
  bbox = draw.textbbox((0, 0), line, font=desc_font)
372
  text_width = bbox[2] - bbox[0]
 
375
  text_width = len(line) * desc_size * 0.6
376
  text_height = desc_size
377
 
378
+ x = (width - text_width) // 2
379
+ y_position -= text_height + 10
380
 
381
+ # Sombra
382
+ shadow_color = (255, 100, 100, 180)
383
+ for dx, dy in [(2, 2), (-2, 2), (2, -2)]:
384
+ draw.text((x + dx, y_position + dy), line, font=desc_font, fill=shadow_color)
 
385
 
386
  # Texto principal
387
+ draw.text((x, y_position), line, font=desc_font, fill=text_rgb + (255,))
 
 
 
388
 
389
+ # Adicionar título
390
  if title and title.strip():
391
+ # Espaço entre título e descrição
392
+ if description and description.strip():
393
+ y_position -= int(title_size * 0.5)
394
 
 
395
  words = title.split()
396
  lines = []
397
  current_line = []
 
400
  current_line.append(word)
401
  test_line = ' '.join(current_line)
402
 
 
403
  try:
404
  bbox = draw.textbbox((0, 0), test_line, font=title_font)
405
  text_width = bbox[2] - bbox[0]
406
  except:
407
  text_width = len(test_line) * title_size * 0.6
408
 
409
+ if text_width > (width - 2 * margin):
410
  if len(current_line) > 1:
411
  lines.append(' '.join(current_line[:-1]))
412
  current_line = [word]
 
417
  if current_line:
418
  lines.append(' '.join(current_line))
419
 
420
+ # Desenhar linhas
 
 
 
 
421
  lines.reverse()
 
 
422
  for line in lines:
 
423
  try:
424
  bbox = draw.textbbox((0, 0), line, font=title_font)
425
  text_width = bbox[2] - bbox[0]
 
428
  text_width = len(line) * title_size * 0.6
429
  text_height = title_size
430
 
431
+ x = (width - text_width) // 2
432
+ y_position -= text_height + 20
433
 
434
+ # Sombra mais forte para título
435
+ shadow_color = (100, 150, 255, 200)
436
+ for dx, dy in [(3, 3), (-3, 3), (3, -3)]:
437
+ draw.text((x + dx, y_position + dy), line, font=title_font, fill=shadow_color)
 
438
 
439
  # Texto principal
440
+ draw.text((x, y_position), line, font=title_font, fill=text_rgb + (255,))
 
 
 
441
 
442
  # Combinar camadas
443
+ return Image.alpha_composite(image, text_layer)
 
 
444
 
445
  except Exception as e:
446
+ print(f"⚠️ Erro no add_text_with_effects: {e}")
447
  return image
448
 
449
  def compose_collage(self, images: List[Image.Image], background: Image.Image) -> Image.Image:
450
  """Compõe as imagens em um collage"""
451
  try:
 
 
452
  result = background.copy().convert('RGBA')
453
  bg_width, bg_height = background.size
454
 
 
457
 
458
  num_images = len(images)
459
 
460
+ # Layout baseado no número de imagens
461
  if num_images == 1:
462
  # Imagem única no centro
463
  img = images[0]
464
  img.thumbnail((bg_width // 2, bg_height // 2), Image.Resampling.LANCZOS)
465
  x = (bg_width - img.width) // 2
466
+ y = (bg_height - img.height) // 3
467
  result.paste(img, (x, y), img)
468
 
469
  elif num_images <= 4:
 
471
  cols = 2
472
  rows = 2
473
  cell_width = bg_width // (cols + 1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
474
  cell_height = bg_height // (rows + 2)
475
 
476
  for idx, img in enumerate(images):
477
+ if idx >= 4:
478
  break
479
+
480
  row = idx // cols
481
  col = idx % cols
482
 
483
+ img.thumbnail((cell_width * 0.8, cell_height * 0.8), Image.Resampling.LANCZOS)
484
 
485
  x = (col + 1) * cell_width - img.width // 2
486
  y = (row + 1) * cell_height - img.height // 2
 
488
  result.paste(img, (x, y), img)
489
 
490
  else:
491
+ # Layout circular
492
  center_x, center_y = bg_width // 2, bg_height // 3
493
  radius = min(bg_width, bg_height) // 4
494
 
495
+ for idx, img in enumerate(images[:12]): # Máximo 12 imagens
496
+ angle = 2 * 3.14159 * idx / min(num_images, 12)
497
 
498
  img.thumbnail((bg_width // 6, bg_height // 6), Image.Resampling.LANCZOS)
499
 
 
502
 
503
  result.paste(img, (x, y), img)
504
 
 
505
  return result.convert('RGB')
506
 
507
  except Exception as e:
508
+ print(f"⚠️ Erro no compose_collage: {e}")
509
  return background.convert('RGB')
510
 
511
  def optimize_file_size(self, image: Image.Image) -> Image.Image:
512
  """Otimiza o tamanho do arquivo"""
513
  try:
 
 
514
  if image.mode == 'RGBA':
515
  image = image.convert('RGB')
516
 
517
  # Tentar diferentes qualidades
518
+ for quality in [90, 85, 80, 75, 70]:
519
  buffer = io.BytesIO()
520
  image.save(buffer, format='JPEG', quality=quality, optimize=True)
521
  size_mb = len(buffer.getvalue()) / (1024 * 1024)
522
 
523
  if size_mb <= OUTPUT_MAX_SIZE_MB:
524
  buffer.seek(0)
525
+ return Image.open(buffer).copy()
 
 
526
 
527
+ # Fallback para qualidade 70
528
  buffer = io.BytesIO()
529
  image.save(buffer, format='JPEG', quality=70, optimize=True)
530
  buffer.seek(0)
531
+ return Image.open(buffer).copy()
 
 
 
532
 
533
  except Exception as e:
534
+ print(f"⚠️ Erro no optimize_file_size: {e}")
535
  return image
536
 
537
+ def generate_poster(self, image_files, resolution_preset, custom_width, custom_height,
538
+ border_style, border_color, gradient_color1, gradient_color2,
539
+ title, description, text_color):
540
+ """Função principal para gerar o pôster"""
 
 
541
 
 
542
  self.logger.clear()
543
+ logs = []
544
 
545
  try:
546
+ # ===== 1. VALIDAÇÃO =====
547
+ logs.append(self.logger.add_log("🚀 Iniciando geração de pôster", "info"))
 
 
548
 
549
+ if not image_files:
550
+ logs.append(self.logger.add_log("❌ Nenhuma imagem fornecida", "error"))
551
+ return None, "❌ Por favor, faça upload de imagens", "\n".join(logs)
552
 
553
+ logs.append(self.logger.add_log(f"📸 {len(image_files)} imagem(ns) recebida(s)", "success"))
554
+
555
+ # ===== 2. DETERMINAR RESOLUÇÃO =====
556
  if resolution_preset == "Custom":
 
 
 
 
557
  try:
558
  size = (int(custom_width), int(custom_height))
559
+ logs.append(self.logger.add_log(f"📐 Resolução customizada: {size[0]}x{size[1]}px", "info"))
560
  except:
561
+ logs.append(self.logger.add_log("❌ Dimensões inválidas", "error"))
562
+ return None, "❌ Use números válidos para largura e altura", "\n".join(logs)
563
  else:
564
  size = RESOLUTION_PRESETS.get(resolution_preset, (1080, 1080))
565
+ logs.append(self.logger.add_log(f"📐 Resolução: {resolution_preset} ({size[0]}x{size[1]}px)", "info"))
566
 
567
+ # ===== 3. CARREGAR IMAGENS =====
 
 
 
568
  processed_images = []
569
+ logs.append(self.logger.add_log("🔄 Carregando imagens...", "processing"))
 
 
570
 
571
+ for idx, file_info in enumerate(image_files[:MAX_IMAGES]):
572
  try:
573
+ # Obter o caminho do arquivo
574
+ if isinstance(file_info, dict) and 'name' in file_info:
575
+ filepath = file_info['name']
576
+ elif isinstance(file_info, str):
577
+ filepath = file_info
578
  else:
579
+ logs.append(self.logger.add_log(f"⚠️ Imagem {idx+1}: Formato inválido", "warning"))
580
+ continue
581
 
582
+ # Abrir imagem
583
+ img = Image.open(filepath)
584
 
585
+ # Converter para RGB se necessário
586
+ if img.mode != 'RGB':
587
+ img = img.convert('RGB')
588
 
589
+ logs.append(self.logger.add_log(f"✅ Imagem {idx+1}: Carregada ({img.size[0]}x{img.size[1]})", "success"))
590
 
591
+ # Remover fundo
592
+ logs.append(self.logger.add_log(f"🔄 Imagem {idx+1}: Removendo fundo...", "processing"))
593
+ bg_removed = self.remove_background_simple(img)
594
+
595
+ # Aplicar borda
596
  border_key = BORDER_STYLES.get(border_style, "none")
597
+ if border_key != "none":
598
+ logs.append(self.logger.add_log(f"🔄 Imagem {idx+1}: Aplicando borda...", "processing"))
599
+ bordered = self.apply_border_effect(bg_removed, border_key, border_color)
600
+ processed_images.append(bordered)
601
+ else:
602
+ processed_images.append(bg_removed)
603
 
604
+ logs.append(self.logger.add_log(f"✅ Imagem {idx+1}: Processada com sucesso", "success"))
 
605
 
606
  except Exception as e:
607
+ error_msg = str(e)[:50]
608
+ logs.append(self.logger.add_log(f"⚠️ Imagem {idx+1}: Erro - {error_msg}", "warning"))
 
609
 
610
  if not processed_images:
611
+ logs.append(self.logger.add_log("❌ Nenhuma imagem processada", "error"))
612
+ return None, "❌ Não foi possível processar nenhuma imagem", "\n".join(logs)
613
 
614
+ logs.append(self.logger.add_log(f"✅ {len(processed_images)} imagem(ns) processada(s)", "success"))
615
 
616
+ # ===== 4. CRIAR FUNDO =====
617
+ logs.append(self.logger.add_log("🎨 Criando fundo degradê...", "processing"))
618
  background = self.create_gradient_background(size, gradient_color1, gradient_color2)
619
 
620
+ # ===== 5. COMPOR COLLAGE =====
621
+ logs.append(self.logger.add_log("🖼️ Criando composição...", "processing"))
622
  collage = self.compose_collage(processed_images, background)
623
 
624
+ # ===== 6. ADICIONAR TEXTO =====
625
  if title or description:
626
+ logs.append(self.logger.add_log("✍️ Adicionando texto...", "processing"))
627
  collage = self.add_text_with_effects(collage, title, description, text_color)
628
 
629
+ # ===== 7. OTIMIZAR =====
630
+ logs.append(self.logger.add_log("🗜️ Otimizando arquivo...", "processing"))
631
  final_image = self.optimize_file_size(collage)
632
 
633
+ # ===== 8. CONCLUIR =====
634
+ logs.append(self.logger.add_log("🎉 Pôster gerado com sucesso!", "success"))
 
635
 
636
+ final_logs = "\n".join(logs)
637
+ return final_image, f"✅ Pôster pronto! {len(processed_images)} imagem(s), {size[0]}x{size[1]}px", final_logs
638
 
639
  except Exception as e:
640
+ error_msg = f"❌ Erro crítico: {str(e)[:100]}"
641
+ logs.append(self.logger.add_log(error_msg, "error"))
642
+ final_logs = "\n".join(logs)
643
+ return None, error_msg, final_logs
 
 
 
 
 
 
 
 
 
644
 
645
  # ============================
646
  # INTERFACE GRADIO
 
649
  # Inicializar gerador
650
  generator = CollagePosterGenerator()
651
 
652
+ def format_logs_for_html(log_text):
653
+ """Formata logs para exibição HTML"""
 
654
  lines = log_text.split('\n')
655
+ formatted = []
656
 
657
  for line in lines:
658
  if '❌' in line:
659
+ formatted.append(f'<span style="color: #ff6b6b; font-weight: bold;">{line}</span>')
660
  elif '✅' in line:
661
+ formatted.append(f'<span style="color: #51cf66;">{line}</span>')
662
  elif '⚠️' in line:
663
+ formatted.append(f'<span style="color: #ffd43b;">{line}</span>')
664
  elif '🔄' in line:
665
+ formatted.append(f'<span style="color: #4dabf7;">{line}</span>')
666
  elif '🚀' in line:
667
+ formatted.append(f'<span style="color: #cc5de8; font-weight: bold;">{line}</span>')
668
+ elif '📝' in line:
669
+ formatted.append(f'<span style="color: #adb5bd;">{line}</span>')
670
+ elif '📸' in line or '📐' in line or '🎨' in line or '🖼️' in line or '✍️' in line or '🗜️' in line:
671
+ formatted.append(f'<span style="color: #74c0fc;">{line}</span>')
672
  else:
673
+ formatted.append(f'<span style="color: #dee2e6;">{line}</span>')
674
 
675
+ return '<br>'.join(formatted)
676
 
677
  with gr.Blocks(theme=gr.themes.Soft(), title="Gerador de Pôster de Colagem") as demo:
678
  gr.Markdown("""
679
+ # 🎨 Gerador de Pôster de Colagem
680
 
681
+ Crie pôsteres incríveis com múltiplas imagens, remoção de fundo e efeitos especiais!
682
  """)
683
 
684
  with gr.Row():
685
  with gr.Column(scale=1):
686
+ # Upload de imagens
687
  gr.Markdown("### 📤 Upload de Imagens")
688
+ image_input = gr.File(
689
+ label="Selecione imagens (até 10)",
690
+ file_types=["image"],
691
+ file_count="multiple",
692
+ type="filepath"
693
+ )
694
 
695
+ # Pré-visualização
696
+ preview_gallery = gr.Gallery(
697
+ label="Pré-visualização das Imagens",
698
+ columns=4,
699
+ height=200,
700
+ visible=False
701
+ )
 
 
 
 
 
 
 
 
 
702
 
703
+ # Configurações
704
+ gr.Markdown("### ⚙️ Configurações")
705
 
706
  with gr.Group():
707
  resolution_preset = gr.Dropdown(
708
+ label="Tamanho do Pôster",
709
  choices=list(RESOLUTION_PRESETS.keys()),
710
+ value="Instagram Post (1:1)"
 
711
  )
712
 
713
+ with gr.Row(visible=False) as custom_row:
714
  custom_width = gr.Number(
715
+ label="Largura (px)",
716
  value=1080,
717
  minimum=100,
718
+ maximum=10000
 
719
  )
720
  custom_height = gr.Number(
721
+ label="Altura (px)",
722
  value=1080,
723
  minimum=100,
724
+ maximum=10000
 
725
  )
726
 
727
  with gr.Group():
728
  border_style = gr.Dropdown(
729
+ label="Estilo da Borda",
730
  choices=list(BORDER_STYLES.keys()),
731
  value="Sombra Suave"
732
  )
733
 
734
  border_color = gr.ColorPicker(
735
+ label="Cor da Borda",
736
+ value="#00AAFF"
 
737
  )
738
 
739
  with gr.Group():
 
741
  with gr.Row():
742
  gradient_color1 = gr.ColorPicker(
743
  label="Cor Superior",
744
+ value="#667EEA"
 
745
  )
746
  gradient_color2 = gr.ColorPicker(
747
  label="Cor Inferior",
748
+ value="#764BA2"
 
749
  )
750
 
751
  with gr.Group():
752
+ gr.Markdown("### 📝 Texto")
753
 
754
  title_input = gr.Textbox(
755
+ label="Título (opcional)",
756
+ placeholder="Digite o título aqui..."
 
 
757
  )
758
 
759
  description_input = gr.Textbox(
760
+ label="Descrição (opcional)",
761
+ placeholder="Digite a descrição aqui...",
762
+ lines=2
 
763
  )
764
 
765
  text_color = gr.ColorPicker(
766
+ label="Cor do Texto",
767
+ value="#FFFFFF"
 
768
  )
769
 
770
+ # Botões de ação
771
  with gr.Row():
772
  process_btn = gr.Button(
773
  "🚀 Gerar Pôster",
774
  variant="primary",
 
775
  scale=2
776
  )
 
777
  clear_btn = gr.Button(
778
+ "🗑️ Limpar",
779
  variant="secondary",
780
  scale=1
781
  )
782
 
783
  with gr.Column(scale=2):
784
+ # Resultado
785
+ gr.Markdown("### 👁️ Pôster Gerado")
786
 
 
787
  output_image = gr.Image(
788
+ label="Resultado",
789
  type="pil",
790
+ height=500
 
791
  )
792
 
793
+ # Status
794
+ status_text = gr.Markdown("""
795
+ ### 📊 Status
796
+ **Aguardando imagens...**
 
 
 
 
797
 
798
+ Instruções:
799
+ 1. Faça upload de imagens (até 10)
800
+ 2. Configure as opções
801
+ 3. Clique em "Gerar Pôster"
802
+ """)
803
+
804
+ # Logs
805
  logs_display = gr.HTML(
806
+ label="📋 Logs de Processamento",
807
+ value='<div style="background: #1a1a1a; padding: 15px; border-radius: 5px; font-family: monospace; color: #ccc;">Aguardando processamento...</div>'
 
 
808
  )
809
 
810
+ # Download
811
+ gr.Markdown("### 💾 Download")
812
+ with gr.Row():
813
+ download_jpeg = gr.DownloadButton(
814
+ "⬇️ Baixar JPEG",
815
+ visible=False
816
+ )
817
+ download_png = gr.DownloadButton(
818
+ "⬇️ Baixar PNG",
819
+ visible=False
820
+ )
 
 
 
 
 
821
 
822
+ # ===== FUNÇÕES =====
823
 
824
+ def update_preview(files):
825
+ """Atualiza pré-visualização das imagens"""
826
  if not files:
827
  return gr.update(visible=False), []
828
 
 
829
  previews = []
830
+ for file in files[:MAX_IMAGES]:
 
831
  try:
832
+ img = Image.open(file)
833
+ # Redimensionar para preview
834
+ img.thumbnail((150, 150), Image.Resampling.LANCZOS)
835
+ previews.append(np.array(img))
836
+ except:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
837
  continue
838
 
839
+ return gr.update(visible=True, value=previews), files
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
840
 
841
+ def toggle_custom_res(choice):
842
  """Mostra/esconde campos de resolução customizada"""
843
  return gr.update(visible=choice == "Custom")
844
 
845
+ def process_images(files, *args):
846
+ """Processa as imagens e gera o pôster"""
847
+ if not files:
848
  return [
849
  None,
850
+ "### ❌ Erro\nPor favor, faça upload de imagens primeiro.",
851
+ '<div style="background: #1a1a1a; padding: 15px; border-radius: 5px; font-family: monospace; color: #ff6b6b;">❌ Nenhuma imagem fornecida</div>',
 
 
852
  gr.update(visible=False),
853
  gr.update(visible=False)
854
  ]
855
 
856
+ # Gerar pôster
857
+ result_img, result_msg, logs = generator.generate_poster(files, *args)
858
+
859
+ # Formatar logs
860
+ html_logs = f'<div style="background: #1a1a1a; padding: 15px; border-radius: 5px; font-family: monospace; line-height: 1.5; max-height: 300px; overflow-y: auto;">{format_logs_for_html(logs)}</div>'
861
+
862
+ if result_img is not None:
863
+ # Salvar arquivos temporários para download
864
+ jpeg_temp = tempfile.NamedTemporaryFile(delete=False, suffix='.jpg')
865
+ result_img.save(jpeg_temp.name, 'JPEG', quality=90, optimize=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
866
 
867
+ png_temp = tempfile.NamedTemporaryFile(delete=False, suffix='.png')
868
+ if result_img.mode == 'RGBA':
 
 
 
 
869
  result_img.save(png_temp.name, 'PNG')
 
 
 
 
 
 
 
 
870
  else:
871
+ result_img.convert('RGB').save(png_temp.name, 'PNG')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
872
 
873
+ return [
874
+ result_img,
875
+ f"### ✅ Sucesso!\n{result_msg}",
876
+ html_logs,
877
+ gr.update(visible=True, value=jpeg_temp.name),
878
+ gr.update(visible=True, value=png_temp.name)
879
+ ]
880
+ else:
881
  return [
882
  None,
883
+ f"### ❌ Erro\n{result_msg}",
884
+ html_logs,
885
  gr.update(visible=False),
886
  gr.update(visible=False)
887
  ]
888
 
889
+ def clear_all():
890
+ """Limpa tudo"""
891
+ return [
892
+ None,
893
+ gr.update(visible=False),
894
+ [],
895
+ None,
896
+ "### 📊 Status\n**Aguardando imagens...**\n\nInstruções:\n1. Faça upload de imagens (até 10)\n2. Configure as opções\n3. Clique em 'Gerar Pôster'",
897
+ '<div style="background: #1a1a1a; padding: 15px; border-radius: 5px; font-family: monospace; color: #ccc;">Pronto para novo processamento...</div>',
898
+ gr.update(visible=False),
899
+ gr.update(visible=False)
900
+ ]
901
+
902
+ # ===== EVENTOS =====
903
 
904
  # Upload de imagens
905
  image_input.change(
906
+ fn=update_preview,
907
  inputs=[image_input],
908
  outputs=[preview_gallery, image_input]
909
  )
910
 
911
  # Alternar resolução customizada
912
  resolution_preset.change(
913
+ fn=toggle_custom_res,
914
  inputs=[resolution_preset],
915
+ outputs=[custom_row]
916
  )
917
 
918
  # Botão Gerar
919
  process_btn.click(
920
+ fn=process_images,
921
  inputs=[
922
  image_input,
923
  resolution_preset,
 
935
  output_image,
936
  status_text,
937
  logs_display,
938
+ download_jpeg,
939
+ download_png
940
  ]
941
  )
942
 
 
950
  output_image,
951
  status_text,
952
  logs_display,
953
+ download_jpeg,
954
+ download_png
955
  ]
956
  )
957
 
958
+ # ===== INSTRUÇÕES =====
959
  gr.Markdown("""
960
  ---
961
+ ### 📖 Como Usar:
962
+
963
+ 1. **Upload de Imagens**: Selecione até 10 imagens
964
+ 2. **Configurações**: Escolha tamanho, bordas e cores
965
+ 3. **Texto**: Adicione título e descrição (opcional)
966
+ 4. **Gerar**: Clique no botão para processar
967
+ 5. **Download**: Baixe o resultado em JPEG ou PNG
968
+
969
+ ### ⚡ Recursos:
970
+ - ✅ Remoção automática de fundo
971
+ - ✅ 4 estilos de borda diferentes
972
+ - ✅ Fundo degradê personalizável
973
+ - ✅ Texto com efeitos de sombra
974
+ - ✅ Suporte a múltiplas resoluções
975
+ - ✅ Otimização de tamanho de arquivo
976
+
977
+ ### 🛠️ Dicas:
978
+ - Para melhores resultados, use imagens com fundo claro
979
+ - Reduza o número de imagens se o processamento for lento
980
+ - Teste diferentes estilos de borda
981
+ - Use cores contrastantes para texto e fundo
 
 
 
 
 
 
 
 
 
 
 
 
 
 
982
  """)
983
 
984
  # ============================
985
+ # EXECUÇÃO
986
  # ============================
987
 
988
  if __name__ == "__main__":
989
  print("🚀 Iniciando Gerador de Pôster de Colagem...")
990
+ print("⚙️ Sistema pronto!")
 
991
 
992
+ # Configurar para Hugging Face
993
  demo.launch(
994
  server_name="0.0.0.0",
995
  server_port=7860,
996
+ share=False
 
 
997
  )