Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,9 +6,15 @@ import torch
|
|
| 6 |
from transformers import AutoModelForImageSegmentation
|
| 7 |
import io
|
| 8 |
import tempfile
|
| 9 |
-
|
|
|
|
| 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 |
-
|
| 47 |
|
| 48 |
# Carregar modelo de remoção de fundo
|
|
|
|
| 49 |
try:
|
| 50 |
-
|
| 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 |
-
|
| 58 |
except Exception as e:
|
| 59 |
-
|
|
|
|
| 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 |
-
|
| 67 |
return self._simple_bg_removal(image)
|
| 68 |
|
| 69 |
# Preparar imagem
|
| 70 |
original_size = image.size
|
| 71 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
|
|
|
|
|
|
| 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 |
-
|
| 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 |
-
|
| 109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 117 |
-
image =
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 247 |
|
| 248 |
def create_gradient_background(self, size: Tuple[int, int], color1: str, color2: str) -> Image.Image:
|
| 249 |
"""Cria fundo degradê"""
|
| 250 |
-
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
#
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 386 |
|
| 387 |
def compose_collage(self, images: List[Image.Image], background: Image.Image) -> Image.Image:
|
| 388 |
"""Compõe as imagens em um collage"""
|
| 389 |
-
|
| 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 |
-
|
| 408 |
-
|
| 409 |
-
|
|
|
|
| 410 |
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
|
| 415 |
-
|
| 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 |
-
#
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 427 |
-
image = image.convert('RGB')
|
| 428 |
|
| 429 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 430 |
output = io.BytesIO()
|
| 431 |
-
image.save(output, format='JPEG', quality=
|
| 432 |
-
|
|
|
|
| 433 |
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 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 |
-
|
| 448 |
-
|
| 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 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 464 |
|
| 465 |
-
|
| 466 |
-
|
|
|
|
| 467 |
|
| 468 |
-
|
| 469 |
-
pil_img = self.remove_background(pil_img)
|
| 470 |
|
| 471 |
-
#
|
| 472 |
-
|
|
|
|
| 473 |
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 490 |
|
| 491 |
# Inicializar gerador
|
| 492 |
-
|
| 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("💡 **
|
| 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 |
-
|
| 593 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
#
|
| 606 |
-
|
| 607 |
-
|
| 608 |
-
|
| 609 |
-
|
| 610 |
-
|
| 611 |
-
|
| 612 |
|
| 613 |
-
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
###
|
| 630 |
|
| 631 |
-
-
|
| 632 |
-
-
|
| 633 |
-
-
|
| 634 |
-
-
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
)
|