Daniel251 commited on
Commit
da64e34
·
verified ·
1 Parent(s): 4544671

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +638 -0
app.py ADDED
@@ -0,0 +1,638 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ from PIL import Image, ImageDraw, ImageFilter, ImageEnhance, ImageOps, ImageFont
4
+ import cv2
5
+ import torch
6
+ from transformers import AutoModelForImageSegmentation
7
+ from transformers import pipeline
8
+ import rembg
9
+ import io
10
+ import base64
11
+ import tempfile
12
+ import os
13
+ from pathlib import Path
14
+ from typing import List, Tuple, Optional
15
+ import warnings
16
+ warnings.filterwarnings("ignore")
17
+
18
+ # Configurações
19
+ MODEL_NAME = "briaai/RMBG-1.4"
20
+ MAX_IMAGES = 10
21
+ MAX_FILE_SIZE_MB = 5
22
+ OUTPUT_MAX_SIZE_MB = 1.5
23
+
24
+ # Presets de resolução
25
+ RESOLUTION_PRESETS = {
26
+ "Instagram Post": (1080, 1080),
27
+ "Instagram Story": (1080, 1920),
28
+ "Facebook Post": (1200, 630),
29
+ "Twitter Post": (1200, 675),
30
+ "LinkedIn Post": (1200, 627),
31
+ "Pinterest Pin": (1000, 1500),
32
+ "YouTube Thumbnail": (1280, 720),
33
+ "A4 Print (300dpi)": (2480, 3508),
34
+ "A3 Print (300dpi)": (3508, 4960),
35
+ "Poster 18x24": (2700, 3600),
36
+ "Custom": None
37
+ }
38
+
39
+ # Efeitos de borda
40
+ BORDER_STYLES = {
41
+ "Nenhuma": "none",
42
+ "Sombra Suave": "soft_shadow",
43
+ "Brilho Neon": "neon_glow",
44
+ "Borda Dupla": "double_line",
45
+ "Pincelada": "brush_stroke",
46
+ "Pontilhado": "dotted",
47
+ "Degradê": "gradient_border",
48
+ "Brilho Interno": "inner_glow"
49
+ }
50
+
51
+ # Estilos de fonte
52
+ FONT_STYLES = {
53
+ "Moderno": "modern",
54
+ "Vintage": "vintage",
55
+ "Elegante": "elegant",
56
+ "Bold": "bold",
57
+ "Script": "script",
58
+ "Futurista": "futuristic"
59
+ }
60
+
61
+ class CollagePosterGenerator:
62
+ def __init__(self):
63
+ self.device = "cuda" if torch.cuda.is_available() else "cpu"
64
+ print(f"Using device: {self.device}")
65
+
66
+ # Inicializar modelo de remoção de fundo
67
+ try:
68
+ self.rembg_model = rembg.new_session(model_name="u2net")
69
+ except:
70
+ self.rembg_model = None
71
+
72
+ def remove_background(self, image: Image.Image) -> Image.Image:
73
+ """Remove o fundo da imagem usando rembg"""
74
+ try:
75
+ if self.rembg_model:
76
+ result = rembg.remove(image, session=self.rembg_model)
77
+ else:
78
+ # Fallback simples
79
+ result = image.convert("RGBA")
80
+ data = np.array(result)
81
+ # Simples threshold para fundo branco
82
+ white_threshold = 200
83
+ mask = (data[:, :, 0] > white_threshold) & \
84
+ (data[:, :, 1] > white_threshold) & \
85
+ (data[:, :, 2] > white_threshold)
86
+ data[:, :, 3] = np.where(mask, 0, 255)
87
+ result = Image.fromarray(data, 'RGBA')
88
+ return result
89
+ except Exception as e:
90
+ print(f"Erro na remoção de fundo: {e}")
91
+ return image.convert("RGBA")
92
+
93
+ def apply_border_effect(self, image: Image.Image, style: str, color: str = "#ffffff") -> Image.Image:
94
+ """Aplica efeitos de borda estilizados"""
95
+ if style == "none" or not style:
96
+ return image
97
+
98
+ # Converter para RGBA se necessário
99
+ if image.mode != 'RGBA':
100
+ image = image.convert('RGBA')
101
+
102
+ # Expandir a imagem para adicionar borda
103
+ border_size = 20
104
+
105
+ if style == "soft_shadow":
106
+ # Criar sombra suave
107
+ shadow = Image.new('RGBA', image.size, (0, 0, 0, 0))
108
+ draw = ImageDraw.Draw(shadow)
109
+
110
+ # Desenhar sombra
111
+ for i in range(10):
112
+ alpha = int(50 - i * 5)
113
+ offset = i + 1
114
+ shadow_layer = Image.new('RGBA', image.size, (0, 0, 0, alpha))
115
+ shadow.paste(shadow_layer, (offset, offset), shadow_layer)
116
+
117
+ # Combinar com imagem original
118
+ result = Image.alpha_composite(shadow, image)
119
+
120
+ elif style == "neon_glow":
121
+ # Efeito de brilho neon
122
+ glow_size = 15
123
+ expanded_size = (image.width + glow_size*2, image.height + glow_size*2)
124
+ result = Image.new('RGBA', expanded_size, (0, 0, 0, 0))
125
+
126
+ # Criar máscara de brilho
127
+ mask = Image.new('L', expanded_size, 0)
128
+ draw = ImageDraw.Draw(mask)
129
+ draw.rectangle([glow_size, glow_size,
130
+ expanded_size[0]-glow_size, expanded_size[1]-glow_size],
131
+ fill=255)
132
+ mask = mask.filter(ImageFilter.GaussianBlur(radius=glow_size//2))
133
+
134
+ # Adicionar cor ao brilho
135
+ glow = Image.new('RGBA', expanded_size, color)
136
+ glow.putalpha(mask)
137
+
138
+ # Colar brilho e imagem
139
+ result.paste(glow, (0, 0), glow)
140
+ result.paste(image, (glow_size, glow_size), image)
141
+
142
+ elif style == "double_line":
143
+ # Borda dupla
144
+ border_color = color
145
+ inner_color = "#ffffff"
146
+
147
+ # Criar nova imagem com borda
148
+ new_size = (image.width + border_size*2, image.height + border_size*2)
149
+ result = Image.new('RGBA', new_size, (0, 0, 0, 0))
150
+ draw = ImageDraw.Draw(result)
151
+
152
+ # Desenhar borda externa
153
+ draw.rectangle([0, 0, new_size[0]-1, new_size[1]-1],
154
+ outline=border_color, width=border_size//2)
155
+ # Desenhar borda interna
156
+ draw.rectangle([border_size//2, border_size//2,
157
+ new_size[0]-border_size//2-1, new_size[1]-border_size//2-1],
158
+ outline=inner_color, width=border_size//4)
159
+
160
+ # Colar imagem original
161
+ result.paste(image, (border_size, border_size), image)
162
+
163
+ elif style == "brush_stroke":
164
+ # Efeito de pincelada
165
+ from PIL import ImageFilter
166
+
167
+ # Criar máscara de borda irregular
168
+ mask = Image.new('L', (image.width + 40, image.height + 40), 0)
169
+ draw = ImageDraw.Draw(mask)
170
+
171
+ # Desenhar borda com textura
172
+ for i in range(5):
173
+ offset = i * 8
174
+ draw.rectangle([offset, offset,
175
+ mask.width - offset - 1, mask.height - offset - 1],
176
+ outline=255, width=3)
177
+
178
+ mask = mask.filter(ImageFilter.GaussianBlur(radius=3))
179
+
180
+ # Aplicar cor
181
+ border = Image.new('RGBA', mask.size, color)
182
+ border.putalpha(mask)
183
+
184
+ result = Image.new('RGBA', mask.size, (0, 0, 0, 0))
185
+ result.paste(border, (0, 0), border)
186
+ result.paste(image, (20, 20), image)
187
+
188
+ else:
189
+ # Borda simples como fallback
190
+ result = ImageOps.expand(image, border=border_size, fill=color)
191
+
192
+ return result
193
+
194
+ def create_gradient_background(self, size: Tuple[int, int], colors: List[str]) -> Image.Image:
195
+ """Cria fundo degradê"""
196
+ width, height = size
197
+
198
+ # Converter cores hex para RGB
199
+ def hex_to_rgb(hex_color):
200
+ hex_color = hex_color.lstrip('#')
201
+ return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
202
+
203
+ color1 = hex_to_rgb(colors[0])
204
+ color2 = hex_to_rgb(colors[1]) if len(colors) > 1 else color1
205
+
206
+ # Criar degradê linear
207
+ background = Image.new('RGB', size)
208
+ draw = ImageDraw.Draw(background)
209
+
210
+ for i in range(height):
211
+ # Interpolar entre as cores
212
+ ratio = i / height
213
+ r = int(color1[0] * (1 - ratio) + color2[0] * ratio)
214
+ g = int(color1[1] * (1 - ratio) + color2[1] * ratio)
215
+ b = int(color1[2] * (1 - ratio) + color2[2] * ratio)
216
+
217
+ draw.line([(0, i), (width, i)], fill=(r, g, b))
218
+
219
+ return background
220
+
221
+ def add_text_with_effects(self, image: Image.Image, title: str, description: str,
222
+ font_style: str, text_color: str) -> Image.Image:
223
+ """Adiciona texto com efeitos visuais"""
224
+ if not title and not description:
225
+ return image
226
+
227
+ draw = ImageDraw.Draw(image)
228
+ width, height = image.size
229
+
230
+ # Carregar fontes (usaremos fontes padrão do PIL para simplicidade)
231
+ try:
232
+ # Tentar carregar fontes do sistema
233
+ title_font = ImageFont.truetype("arialbd.ttf", 60)
234
+ desc_font = ImageFont.truetype("arial.ttf", 30)
235
+ except:
236
+ # Fallback para fontes padrão
237
+ title_font = ImageFont.load_default()
238
+ desc_font = ImageFont.load_default()
239
+
240
+ # Configurar margens
241
+ margin = 50
242
+
243
+ # Processar título
244
+ if title:
245
+ # Quebrar título em linhas
246
+ words = title.split()
247
+ lines = []
248
+ current_line = []
249
+
250
+ for word in words:
251
+ current_line.append(word)
252
+ # Verificar largura (aproximada)
253
+ if len(' '.join(current_line)) > 20: # Limite simples de caracteres
254
+ lines.append(' '.join(current_line[:-1]))
255
+ current_line = [word]
256
+
257
+ if current_line:
258
+ lines.append(' '.join(current_line))
259
+
260
+ # Adicionar sombra colorida atrás do texto
261
+ shadow_color = (255, 100, 100, 150) # Rosa suave
262
+
263
+ # Desenhar cada linha
264
+ y_position = height - margin - (len(lines) * 70) - (len(description.split('\n')) * 40 if description else 0)
265
+
266
+ for i, line in enumerate(lines):
267
+ text_width = draw.textlength(line, font=title_font)
268
+ x_position = (width - text_width) // 2
269
+
270
+ # Desenhar sombra
271
+ for dx, dy in [(2, 2), (-2, 2), (2, -2), (-2, -2)]:
272
+ draw.text((x_position + dx, y_position + i*70 + dy),
273
+ line, font=title_font, fill=shadow_color)
274
+
275
+ # Desenhar texto principal
276
+ draw.text((x_position, y_position + i*70),
277
+ line, font=title_font, fill=text_color)
278
+
279
+ # Processar descrição
280
+ if description:
281
+ # Quebrar descrição em linhas
282
+ desc_lines = description.split('\n')
283
+
284
+ y_start = height - margin - (len(desc_lines) * 40)
285
+
286
+ for i, line in enumerate(desc_lines):
287
+ if not line.strip():
288
+ continue
289
+
290
+ text_width = draw.textlength(line, font=desc_font)
291
+ x_position = (width - text_width) // 2
292
+
293
+ # Desenhar sombra
294
+ for dx, dy in [(1, 1), (-1, 1), (1, -1), (-1, -1)]:
295
+ draw.text((x_position + dx, y_start + i*40 + dy),
296
+ line, font=desc_font, fill=(0, 0, 0, 100))
297
+
298
+ # Desenhar texto
299
+ draw.text((x_position, y_start + i*40),
300
+ line, font=desc_font, fill=text_color)
301
+
302
+ return image
303
+
304
+ def compose_collage(self, images: List[Image.Image], background: Image.Image,
305
+ arrangement: str = "grid") -> Image.Image:
306
+ """Compõe as imagens em um collage no fundo"""
307
+ result = background.copy()
308
+ bg_width, bg_height = background.size
309
+
310
+ if not images:
311
+ return result
312
+
313
+ # Calcular posições baseadas no número de imagens
314
+ num_images = len(images)
315
+
316
+ if arrangement == "grid":
317
+ # Organização em grade
318
+ cols = int(np.ceil(np.sqrt(num_images)))
319
+ rows = int(np.ceil(num_images / cols))
320
+
321
+ cell_width = bg_width // (cols + 2)
322
+ cell_height = bg_height // (rows + 2)
323
+
324
+ for idx, img in enumerate(images):
325
+ row = idx // cols
326
+ col = idx % cols
327
+
328
+ # Redimensionar imagem para caber na célula
329
+ img.thumbnail((cell_width * 0.8, cell_height * 0.8), Image.Resampling.LANCZOS)
330
+
331
+ # Calcular posição
332
+ x = (col + 1) * cell_width + (cell_width - img.width) // 2
333
+ y = (row + 1) * cell_height + (cell_height - img.height) // 2
334
+
335
+ # Adicionar à composição
336
+ result.paste(img, (x, y), img)
337
+
338
+ else: # Arranjo circular
339
+ center_x, center_y = bg_width // 2, bg_height // 2
340
+ radius = min(bg_width, bg_height) // 3
341
+
342
+ for idx, img in enumerate(images):
343
+ # Redimensionar
344
+ max_size = min(bg_width, bg_height) // 4
345
+ img.thumbnail((max_size, max_size), Image.Resampling.LANCZOS)
346
+
347
+ # Calcular posição em círculo
348
+ angle = 2 * np.pi * idx / num_images
349
+ x = int(center_x + radius * np.cos(angle) - img.width // 2)
350
+ y = int(center_y + radius * np.sin(angle) - img.height // 2)
351
+
352
+ # Adicionar à composição
353
+ result.paste(img, (x, y), img)
354
+
355
+ return result
356
+
357
+ def optimize_file_size(self, image: Image.Image, max_size_mb: float = 1.5) -> Image.Image:
358
+ """Otimiza o tamanho do arquivo mantendo qualidade"""
359
+ output = io.BytesIO()
360
+ quality = 95
361
+
362
+ for q in range(95, 10, -5):
363
+ output = io.BytesIO()
364
+ image.save(output, format='JPEG', quality=q, optimize=True)
365
+ size_mb = len(output.getvalue()) / (1024 * 1024)
366
+
367
+ if size_mb <= max_size_mb:
368
+ break
369
+
370
+ # Recarregar imagem do buffer
371
+ output.seek(0)
372
+ return Image.open(output)
373
+
374
+ def generate_poster(self, images: List[np.ndarray], resolution_preset: str,
375
+ custom_width: int, custom_height: int,
376
+ border_style: str, border_color: str,
377
+ gradient_color1: str, gradient_color2: str,
378
+ title: str, description: str,
379
+ font_style: str, text_color: str) -> Image.Image:
380
+ """Gera o pôster final"""
381
+
382
+ # Determinar resolução
383
+ if resolution_preset == "Custom" and custom_width and custom_height:
384
+ size = (custom_width, custom_height)
385
+ else:
386
+ size = RESOLUTION_PRESETS.get(resolution_preset, (1080, 1080))
387
+
388
+ # Converter numpy arrays para PIL Images
389
+ pil_images = []
390
+ for img_array in images:
391
+ pil_img = Image.fromarray(img_array)
392
+
393
+ # Remover fundo
394
+ pil_img = self.remove_background(pil_img)
395
+
396
+ # Aplicar efeito de borda
397
+ pil_img = self.apply_border_effect(pil_img, border_style, border_color)
398
+
399
+ pil_images.append(pil_img)
400
+
401
+ # Criar fundo degradê
402
+ background = self.create_gradient_background(size, [gradient_color1, gradient_color2])
403
+
404
+ # Criar collage
405
+ collage = self.compose_collage(pil_images, background)
406
+
407
+ # Adicionar texto
408
+ if title or description:
409
+ collage = self.add_text_with_effects(collage, title, description, font_style, text_color)
410
+
411
+ return collage
412
+
413
+ # Inicializar gerador
414
+ generator = CollagePosterGenerator()
415
+
416
+ def process_images(*args):
417
+ """Função principal para processar as imagens"""
418
+ try:
419
+ # Extrair argumentos
420
+ images = args[0]
421
+ resolution_preset = args[1]
422
+ custom_width = args[2]
423
+ custom_height = args[3]
424
+ border_style = args[4]
425
+ border_color = args[5]
426
+ gradient_color1 = args[6]
427
+ gradient_color2 = args[7]
428
+ title = args[8]
429
+ description = args[9]
430
+ font_style = args[10]
431
+ text_color = args[11]
432
+
433
+ if not images:
434
+ return None, "Por favor, faça upload de pelo menos uma imagem"
435
+
436
+ # Gerar pôster
437
+ result = generator.generate_poster(
438
+ images=images,
439
+ resolution_preset=resolution_preset,
440
+ custom_width=custom_width,
441
+ custom_height=custom_height,
442
+ border_style=border_style,
443
+ border_color=border_color,
444
+ gradient_color1=gradient_color1,
445
+ gradient_color2=gradient_color2,
446
+ title=title,
447
+ description=description,
448
+ font_style=font_style,
449
+ text_color=text_color
450
+ )
451
+
452
+ # Otimizar tamanho do arquivo
453
+ result = generator.optimize_file_size(result, OUTPUT_MAX_SIZE_MB)
454
+
455
+ return result, "✅ Pôster gerado com sucesso! Clique em Download para salvar."
456
+
457
+ except Exception as e:
458
+ print(f"Erro: {e}")
459
+ return None, f"❌ Erro ao processar: {str(e)}"
460
+
461
+ # Interface Gradio
462
+ with gr.Blocks(theme=gr.themes.Soft(), title="Gerador de Pôster de Colagem") as demo:
463
+ gr.Markdown("""
464
+ # 🎨 Gerador de Pôster de Colagem Profissional
465
+
466
+ Crie pôsteres incríveis com múltiplas imagens, remoção de fundo automática e efeitos especiais!
467
+ """)
468
+
469
+ with gr.Row():
470
+ with gr.Column(scale=1):
471
+ gr.Markdown("### 📤 Upload de Imagens")
472
+ image_input = gr.Gallery(
473
+ label="Arraste e solte suas imagens aqui",
474
+ type="numpy",
475
+ height=300
476
+ )
477
+
478
+ upload_button = gr.UploadButton(
479
+ "📁 Escolher Imagens",
480
+ file_types=["image"],
481
+ file_count="multiple"
482
+ )
483
+ upload_button.upload(lambda x: x, upload_button, image_input)
484
+
485
+ gr.Markdown("### ⚙️ Configurações")
486
+
487
+ with gr.Row():
488
+ resolution_preset = gr.Dropdown(
489
+ label="Resolução",
490
+ choices=list(RESOLUTION_PRESETS.keys()),
491
+ value="Instagram Post"
492
+ )
493
+
494
+ with gr.Row():
495
+ custom_width = gr.Number(
496
+ label="Largura Customizada",
497
+ value=1080,
498
+ visible=False
499
+ )
500
+ custom_height = gr.Number(
501
+ label="Altura Customizada",
502
+ value=1080,
503
+ visible=False
504
+ )
505
+
506
+ # Mostrar campos customizados apenas quando "Custom" for selecionado
507
+ def toggle_custom_fields(choice):
508
+ return gr.update(visible=choice == "Custom"), gr.update(visible=choice == "Custom")
509
+
510
+ resolution_preset.change(
511
+ toggle_custom_fields,
512
+ inputs=[resolution_preset],
513
+ outputs=[custom_width, custom_height]
514
+ )
515
+
516
+ border_style = gr.Dropdown(
517
+ label="Estilo da Borda",
518
+ choices=list(BORDER_STYLES.keys()),
519
+ value="Sombra Suave"
520
+ )
521
+
522
+ border_color = gr.ColorPicker(
523
+ label="Cor da Borda",
524
+ value="#ffffff"
525
+ )
526
+
527
+ gr.Markdown("### 🎨 Cores do Fundo")
528
+ with gr.Row():
529
+ gradient_color1 = gr.ColorPicker(label="Cor 1", value="#1a2a6c")
530
+ gradient_color2 = gr.ColorPicker(label="Cor 2", value="#b21f1f")
531
+
532
+ gr.Markdown("### 📝 Texto do Pôster")
533
+
534
+ title_input = gr.Textbox(
535
+ label="Título Principal",
536
+ placeholder="Digite o título aqui...",
537
+ max_lines=2
538
+ )
539
+
540
+ description_input = gr.Textbox(
541
+ label="Descrição",
542
+ placeholder="Digite a descrição aqui...",
543
+ lines=3
544
+ )
545
+
546
+ with gr.Row():
547
+ font_style = gr.Dropdown(
548
+ label="Estilo da Fonte",
549
+ choices=list(FONT_STYLES.keys()),
550
+ value="Moderno"
551
+ )
552
+
553
+ text_color = gr.ColorPicker(
554
+ label="Cor do Texto",
555
+ value="#ffffff"
556
+ )
557
+
558
+ process_btn = gr.Button("🚀 Gerar Pôster", variant="primary", size="lg")
559
+
560
+ with gr.Column(scale=2):
561
+ gr.Markdown("### 👁️ Preview do Pôster")
562
+
563
+ output_image = gr.Image(
564
+ label="Pôster Gerado",
565
+ type="pil",
566
+ height=500
567
+ )
568
+
569
+ status_text = gr.Markdown("Aguardando processamento...")
570
+
571
+ with gr.Row():
572
+ download_btn = gr.Button("💾 Download (Alta Resolução)", size="lg")
573
+ clear_btn = gr.Button("🗑️ Limpar Tudo", variant="secondary")
574
+
575
+ # Processamento
576
+ process_btn.click(
577
+ fn=process_images,
578
+ inputs=[
579
+ image_input,
580
+ resolution_preset,
581
+ custom_width,
582
+ custom_height,
583
+ border_style,
584
+ border_color,
585
+ gradient_color1,
586
+ gradient_color2,
587
+ title_input,
588
+ description_input,
589
+ font_style,
590
+ text_color
591
+ ],
592
+ outputs=[output_image, status_text]
593
+ )
594
+
595
+ # Download
596
+ def prepare_download(img):
597
+ if img is None:
598
+ return None
599
+ # Salvar em arquivo temporário
600
+ temp_path = tempfile.NamedTemporaryFile(delete=False, suffix='.jpg').name
601
+ img.save(temp_path, 'JPEG', quality=95)
602
+ return temp_path
603
+
604
+ download_btn.click(
605
+ fn=prepare_download,
606
+ inputs=[output_image],
607
+ outputs=gr.File(label="Download do Pôster")
608
+ )
609
+
610
+ # Limpar
611
+ def clear_all():
612
+ return None, None, None, None, "", "", "Aguardando processamento..."
613
+
614
+ clear_btn.click(
615
+ fn=clear_all,
616
+ outputs=[image_input, output_image, title_input, description_input, status_text]
617
+ )
618
+
619
+ gr.Markdown("""
620
+ ### 📋 Instruções:
621
+ 1. **Upload de Imagens**: Selecione até 10 imagens
622
+ 2. **Configurações**: Escolha resolução, bordas e cores
623
+ 3. **Texto**: Adicione título e descrição (opcional)
624
+ 4. **Gerar**: Clique no botão para processar
625
+ 5. **Download**: Baixe o pôster em alta resolução
626
+
627
+ ### ⚡ Recursos:
628
+ - ✅ Remoção automática de fundo
629
+ - ✅ Efeitos de borda estilizados
630
+ - ✅ Fundo degradê personalizado
631
+ - ✅ Texto com sombras coloridas
632
+ - ✅ Otimização de tamanho (até 1.5MB)
633
+ - ✅ Suporte a múltiplas resoluções
634
+ """)
635
+
636
+ # Configuração para Hugging Face Space
637
+ if __name__ == "__main__":
638
+ demo.launch(debug=True, share=True)