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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
🎨 Object Replacer - App 8 do Photoshop AI Ecosystem
|
| 3 |
+
Substitui objetos em imagens por outros objetos
|
| 4 |
+
Autor: Photoshop AI Ecosystem
|
| 5 |
+
Versão: 1.0.0
|
| 6 |
+
Data: 2024
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import gradio as gr
|
| 10 |
+
from PIL import Image, ImageDraw, ImageFilter, ImageOps, ImageEnhance, ImageFont
|
| 11 |
+
import numpy as np
|
| 12 |
+
import tempfile
|
| 13 |
+
import time
|
| 14 |
+
import os
|
| 15 |
+
import sys
|
| 16 |
+
import math
|
| 17 |
+
import colorsys
|
| 18 |
+
import random
|
| 19 |
+
from io import BytesIO
|
| 20 |
+
|
| 21 |
+
print("=" * 60)
|
| 22 |
+
print("🚀 INICIANDO APP 8: OBJECT REPLACER")
|
| 23 |
+
print(f"Python version: {sys.version}")
|
| 24 |
+
print(f"Pillow version: {Image.__version__}")
|
| 25 |
+
print("=" * 60)
|
| 26 |
+
|
| 27 |
+
# ========== CONFIGURAÇÃO ==========
|
| 28 |
+
|
| 29 |
+
MAX_IMAGE_SIZE = 1024
|
| 30 |
+
OBJECT_LIBRARY = {
|
| 31 |
+
"emoji": "😀 Emoji",
|
| 32 |
+
"heart": "❤️ Coração",
|
| 33 |
+
"star": "⭐ Estrela",
|
| 34 |
+
"flower": "🌷 Flor",
|
| 35 |
+
"tree": "🌳 Árvore",
|
| 36 |
+
"car": "🚗 Carro",
|
| 37 |
+
"house": "🏠 Casa",
|
| 38 |
+
"cloud": "☁️ Nuvem",
|
| 39 |
+
"sun": "☀️ Sol",
|
| 40 |
+
"moon": "🌙 Lua",
|
| 41 |
+
"text": "📝 Texto",
|
| 42 |
+
"logo": "🏢 Logo",
|
| 43 |
+
"pattern": "🔶 Padrão",
|
| 44 |
+
"gradient": "🌈 Gradiente",
|
| 45 |
+
"transparent": "🎯 Remover"
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
print(f"📏 Tamanho máximo: {MAX_IMAGE_SIZE}px")
|
| 49 |
+
print(f"🎯 Objetos disponíveis: {len(OBJECT_LIBRARY)}")
|
| 50 |
+
|
| 51 |
+
# ========== FUNÇÕES AUXILIARES ==========
|
| 52 |
+
|
| 53 |
+
def log_message(message):
|
| 54 |
+
"""Log para debug"""
|
| 55 |
+
timestamp = time.strftime("%H:%M:%S")
|
| 56 |
+
print(f"[{timestamp}] {message}")
|
| 57 |
+
|
| 58 |
+
def validate_image(image):
|
| 59 |
+
"""Valida e prepara imagem"""
|
| 60 |
+
try:
|
| 61 |
+
if image is None:
|
| 62 |
+
return None, "❌ Nenhuma imagem fornecida"
|
| 63 |
+
|
| 64 |
+
# Converter para PIL Image
|
| 65 |
+
if isinstance(image, dict): # Gradio dict
|
| 66 |
+
if 'image' in image:
|
| 67 |
+
img_array = image['image']
|
| 68 |
+
if isinstance(img_array, np.ndarray):
|
| 69 |
+
img = Image.fromarray(img_array.astype('uint8'))
|
| 70 |
+
else:
|
| 71 |
+
return None, "❌ Formato de array inválido"
|
| 72 |
+
else:
|
| 73 |
+
return None, "❌ Dicionário sem chave 'image'"
|
| 74 |
+
elif isinstance(image, np.ndarray):
|
| 75 |
+
img = Image.fromarray(image.astype('uint8'))
|
| 76 |
+
else:
|
| 77 |
+
img = image
|
| 78 |
+
|
| 79 |
+
# Verificar tamanho
|
| 80 |
+
if max(img.size) > 4000:
|
| 81 |
+
return None, "❌ Imagem muito grande (>4000px)."
|
| 82 |
+
|
| 83 |
+
if min(img.size) < 32:
|
| 84 |
+
return None, "❌ Imagem muito pequena (<32px)."
|
| 85 |
+
|
| 86 |
+
log_message(f"✅ Imagem válida: {img.size}px, {img.mode}")
|
| 87 |
+
return img, "ok"
|
| 88 |
+
|
| 89 |
+
except Exception as e:
|
| 90 |
+
error_msg = f"❌ Erro na validação: {str(e)}"
|
| 91 |
+
log_message(error_msg)
|
| 92 |
+
return None, error_msg
|
| 93 |
+
|
| 94 |
+
def resize_image(image, max_size):
|
| 95 |
+
"""Redimensiona mantendo aspect ratio"""
|
| 96 |
+
if max(image.size) <= max_size:
|
| 97 |
+
return image
|
| 98 |
+
|
| 99 |
+
ratio = max_size / max(image.size)
|
| 100 |
+
new_width = int(image.width * ratio)
|
| 101 |
+
new_height = int(image.height * ratio)
|
| 102 |
+
|
| 103 |
+
log_message(f"Redimensionando: {image.size} -> ({new_width}, {new_height})")
|
| 104 |
+
|
| 105 |
+
return image.resize((new_width, new_height), Image.Resampling.LANCZOS)
|
| 106 |
+
|
| 107 |
+
def get_average_color(image, box):
|
| 108 |
+
"""Obtém a cor média de uma área"""
|
| 109 |
+
x1, y1, x2, y2 = box
|
| 110 |
+
region = image.crop((x1, y1, x2, y2))
|
| 111 |
+
|
| 112 |
+
# Converter para array numpy
|
| 113 |
+
region_array = np.array(region)
|
| 114 |
+
|
| 115 |
+
# Calcular média de cada canal
|
| 116 |
+
if len(region_array.shape) == 3:
|
| 117 |
+
avg_color = region_array.mean(axis=(0, 1)).astype(int)
|
| 118 |
+
else:
|
| 119 |
+
avg_color = [region_array.mean().astype(int)] * 3
|
| 120 |
+
|
| 121 |
+
return tuple(avg_color[:3])
|
| 122 |
+
|
| 123 |
+
def calculate_color_similarity(color1, color2):
|
| 124 |
+
"""Calcula similaridade entre cores (0-100%)"""
|
| 125 |
+
r1, g1, b1 = color1
|
| 126 |
+
r2, g2, b2 = color2
|
| 127 |
+
|
| 128 |
+
# Distância Euclidiana normalizada
|
| 129 |
+
distance = math.sqrt((r1 - r2)**2 + (g1 - g2)**2 + (b1 - b2)**2)
|
| 130 |
+
max_distance = math.sqrt(255**2 * 3)
|
| 131 |
+
|
| 132 |
+
similarity = 100 * (1 - distance / max_distance)
|
| 133 |
+
return similarity
|
| 134 |
+
|
| 135 |
+
def create_mask_from_selection(image, box, threshold=30):
|
| 136 |
+
"""Cria máscara baseada na seleção e cores similares"""
|
| 137 |
+
x1, y1, x2, y2 = box
|
| 138 |
+
width, height = image.size
|
| 139 |
+
|
| 140 |
+
# Criar máscara vazia
|
| 141 |
+
mask = Image.new('L', (width, height), 0)
|
| 142 |
+
draw = ImageDraw.Draw(mask)
|
| 143 |
+
|
| 144 |
+
# Preencher área selecionada
|
| 145 |
+
draw.rectangle([x1, y1, x2, y2], fill=255)
|
| 146 |
+
|
| 147 |
+
# Obter cor média da área selecionada
|
| 148 |
+
avg_color = get_average_color(image, box)
|
| 149 |
+
|
| 150 |
+
# Expandir máscara para pixels similares
|
| 151 |
+
img_array = np.array(image.convert('RGB'))
|
| 152 |
+
mask_array = np.array(mask)
|
| 153 |
+
|
| 154 |
+
# Limites de busca (expandir um pouco)
|
| 155 |
+
search_x1 = max(0, x1 - 20)
|
| 156 |
+
search_y1 = max(0, y1 - 20)
|
| 157 |
+
search_x2 = min(width, x2 + 20)
|
| 158 |
+
search_y2 = min(height, y2 + 20)
|
| 159 |
+
|
| 160 |
+
for y in range(search_y1, search_y2):
|
| 161 |
+
for x in range(search_x1, search_x2):
|
| 162 |
+
# Se já está na máscara, pular
|
| 163 |
+
if mask_array[y, x] > 0:
|
| 164 |
+
continue
|
| 165 |
+
|
| 166 |
+
# Verificar cor do pixel
|
| 167 |
+
pixel_color = tuple(img_array[y, x])
|
| 168 |
+
similarity = calculate_color_similarity(avg_color, pixel_color)
|
| 169 |
+
|
| 170 |
+
# Se similar o suficiente, adicionar à máscara
|
| 171 |
+
if similarity > threshold:
|
| 172 |
+
# Suavizar bordas com valor baseado na similaridade
|
| 173 |
+
mask_value = int(255 * (similarity / 100))
|
| 174 |
+
mask_array[y, x] = mask_value
|
| 175 |
+
|
| 176 |
+
mask = Image.fromarray(mask_array)
|
| 177 |
+
|
| 178 |
+
# Suavizar bordas da máscara
|
| 179 |
+
mask = mask.filter(ImageFilter.GaussianBlur(radius=2))
|
| 180 |
+
|
| 181 |
+
return mask
|
| 182 |
+
|
| 183 |
+
# ========== GERADORES DE OBJETOS ==========
|
| 184 |
+
|
| 185 |
+
def create_emoji_object(size, color=(255, 200, 0)):
|
| 186 |
+
"""Cria objeto emoji"""
|
| 187 |
+
img = Image.new('RGBA', (size, size), (0, 0, 0, 0))
|
| 188 |
+
draw = ImageDraw.Draw(img)
|
| 189 |
+
|
| 190 |
+
# Face amarela
|
| 191 |
+
draw.ellipse([5, 5, size-5, size-5], fill=color, outline=(200, 150, 0), width=2)
|
| 192 |
+
|
| 193 |
+
# Olhos
|
| 194 |
+
eye_size = size // 6
|
| 195 |
+
left_eye_x = size // 3
|
| 196 |
+
right_eye_x = size * 2 // 3
|
| 197 |
+
eye_y = size // 3
|
| 198 |
+
|
| 199 |
+
draw.ellipse([left_eye_x-eye_size//2, eye_y-eye_size//2,
|
| 200 |
+
left_eye_x+eye_size//2, eye_y+eye_size//2], fill=(0, 0, 0))
|
| 201 |
+
draw.ellipse([right_eye_x-eye_size//2, eye_y-eye_size//2,
|
| 202 |
+
right_eye_x+eye_size//2, eye_y+eye_size//2], fill=(0, 0, 0))
|
| 203 |
+
|
| 204 |
+
# Boca sorridente
|
| 205 |
+
mouth_y = size * 2 // 3
|
| 206 |
+
draw.arc([size//4, mouth_y-eye_size, size*3//4, mouth_y+eye_size],
|
| 207 |
+
0, 180, fill=(0, 0, 0), width=3)
|
| 208 |
+
|
| 209 |
+
return img
|
| 210 |
+
|
| 211 |
+
def create_heart_object(size, color=(255, 0, 0)):
|
| 212 |
+
"""Cria objeto coração"""
|
| 213 |
+
img = Image.new('RGBA', (size, size), (0, 0, 0, 0))
|
| 214 |
+
draw = ImageDraw.Draw(img)
|
| 215 |
+
|
| 216 |
+
# Usar polígono para coração
|
| 217 |
+
center_x, center_y = size // 2, size // 2
|
| 218 |
+
heart_size = size // 2 - 10
|
| 219 |
+
|
| 220 |
+
# Pontos do coração (fórmula paramétrica)
|
| 221 |
+
points = []
|
| 222 |
+
for t in np.linspace(0, 2 * math.pi, 100):
|
| 223 |
+
x = 16 * (math.sin(t) ** 3)
|
| 224 |
+
y = 13 * math.cos(t) - 5 * math.cos(2*t) - 2 * math.cos(3*t) - math.cos(4*t)
|
| 225 |
+
|
| 226 |
+
# Escalar e centralizar
|
| 227 |
+
x = center_x + (x * heart_size / 16)
|
| 228 |
+
y = center_y - (y * heart_size / 16) # Negativo porque Y cresce para baixo
|
| 229 |
+
points.append((x, y))
|
| 230 |
+
|
| 231 |
+
if points:
|
| 232 |
+
draw.polygon(points, fill=color, outline=(200, 0, 0), width=2)
|
| 233 |
+
|
| 234 |
+
return img
|
| 235 |
+
|
| 236 |
+
def create_star_object(size, color=(255, 255, 0)):
|
| 237 |
+
"""Cria objeto estrela"""
|
| 238 |
+
img = Image.new('RGBA', (size, size), (0, 0, 0, 0))
|
| 239 |
+
draw = ImageDraw.Draw(img)
|
| 240 |
+
|
| 241 |
+
center_x, center_y = size // 2, size // 2
|
| 242 |
+
outer_radius = size // 2 - 10
|
| 243 |
+
inner_radius = outer_radius // 2
|
| 244 |
+
|
| 245 |
+
# Pontos da estrela (5 pontas)
|
| 246 |
+
points = []
|
| 247 |
+
for i in range(10):
|
| 248 |
+
angle = math.pi / 5 * i
|
| 249 |
+
radius = outer_radius if i % 2 == 0 else inner_radius
|
| 250 |
+
x = center_x + radius * math.cos(angle - math.pi/2)
|
| 251 |
+
y = center_y + radius * math.sin(angle - math.pi/2)
|
| 252 |
+
points.append((x, y))
|
| 253 |
+
|
| 254 |
+
if points:
|
| 255 |
+
draw.polygon(points, fill=color, outline=(200, 200, 0), width=2)
|
| 256 |
+
|
| 257 |
+
return img
|
| 258 |
+
|
| 259 |
+
def create_flower_object(size, color=(255, 105, 180)):
|
| 260 |
+
"""Cria objeto flor"""
|
| 261 |
+
img = Image.new('RGBA', (size, size), (0, 0, 0, 0))
|
| 262 |
+
draw = ImageDraw.Draw(img)
|
| 263 |
+
|
| 264 |
+
center_x, center_y = size // 2, size // 2
|
| 265 |
+
petal_radius = size // 4
|
| 266 |
+
center_radius = size // 8
|
| 267 |
+
|
| 268 |
+
# Centro da flor
|
| 269 |
+
draw.ellipse([center_x-center_radius, center_y-center_radius,
|
| 270 |
+
center_x+center_radius, center_y+center_radius],
|
| 271 |
+
fill=(255, 255, 100), outline=(200, 200, 50), width=2)
|
| 272 |
+
|
| 273 |
+
# Pétalas (8 pétalas)
|
| 274 |
+
for angle in range(0, 360, 45):
|
| 275 |
+
rad = math.radians(angle)
|
| 276 |
+
petal_x = center_x + (petal_radius * 0.8) * math.cos(rad)
|
| 277 |
+
petal_y = center_y + (petal_radius * 0.8) * math.sin(rad)
|
| 278 |
+
|
| 279 |
+
draw.ellipse([petal_x-petal_radius//2, petal_y-petal_radius//2,
|
| 280 |
+
petal_x+petal_radius//2, petal_y+petal_radius//2],
|
| 281 |
+
fill=color, outline=(200, 85, 160), width=2)
|
| 282 |
+
|
| 283 |
+
return img
|
| 284 |
+
|
| 285 |
+
def create_tree_object(size, color=(34, 139, 34)):
|
| 286 |
+
"""Cria objeto árvore"""
|
| 287 |
+
img = Image.new('RGBA', (size, size), (0, 0, 0, 0))
|
| 288 |
+
draw = ImageDraw.Draw(img)
|
| 289 |
+
|
| 290 |
+
trunk_width = size // 8
|
| 291 |
+
trunk_height = size // 3
|
| 292 |
+
tree_x = size // 2
|
| 293 |
+
|
| 294 |
+
# Tronco
|
| 295 |
+
trunk_y = size - trunk_height
|
| 296 |
+
draw.rectangle([tree_x-trunk_width//2, trunk_y,
|
| 297 |
+
tree_x+trunk_width//2, size-10],
|
| 298 |
+
fill=(101, 67, 33), outline=(139, 69, 19), width=2)
|
| 299 |
+
|
| 300 |
+
# Copa (3 níveis)
|
| 301 |
+
levels = 3
|
| 302 |
+
for i in range(levels):
|
| 303 |
+
level_y = trunk_y - i * (size // 6)
|
| 304 |
+
level_width = (size * 2 // 3) - i * (size // 8)
|
| 305 |
+
level_height = size // 6
|
| 306 |
+
|
| 307 |
+
draw.ellipse([tree_x-level_width//2, level_y-level_height//2,
|
| 308 |
+
tree_x+level_width//2, level_y+level_height//2],
|
| 309 |
+
fill=color, outline=(0, 100, 0), width=2)
|
| 310 |
+
|
| 311 |
+
return img
|
| 312 |
+
|
| 313 |
+
def create_car_object(size, color=(255, 0, 0)):
|
| 314 |
+
"""Cria objeto carro"""
|
| 315 |
+
img = Image.new('RGBA', (size, size), (0, 0, 0, 0))
|
| 316 |
+
draw = ImageDraw.Draw(img)
|
| 317 |
+
|
| 318 |
+
# Corpo do carro
|
| 319 |
+
car_width = size * 3 // 4
|
| 320 |
+
car_height = size // 3
|
| 321 |
+
car_x = (size - car_width) // 2
|
| 322 |
+
car_y = size // 2 - car_height // 2
|
| 323 |
+
|
| 324 |
+
# Corpo principal
|
| 325 |
+
draw.rounded_rectangle([car_x, car_y, car_x+car_width, car_y+car_height],
|
| 326 |
+
radius=10, fill=color, outline=(200, 0, 0), width=2)
|
| 327 |
+
|
| 328 |
+
# Janelas
|
| 329 |
+
window_color = (135, 206, 235)
|
| 330 |
+
draw.rectangle([car_x+10, car_y+5, car_x+car_width-10, car_y+car_height//2],
|
| 331 |
+
fill=window_color, outline=(100, 149, 237), width=1)
|
| 332 |
+
|
| 333 |
+
# Rodas
|
| 334 |
+
wheel_radius = size // 8
|
| 335 |
+
draw.ellipse([car_x+wheel_radius, car_y+car_height-wheel_radius//2,
|
| 336 |
+
car_x+wheel_radius*2, car_y+car_height+wheel_radius//2],
|
| 337 |
+
fill=(50, 50, 50), outline=(30, 30, 30), width=2)
|
| 338 |
+
draw.ellipse([car_x+car_width-wheel_radius*2, car_y+car_height-wheel_radius//2,
|
| 339 |
+
car_x+car_width-wheel_radius, car_y+car_height+wheel_radius//2],
|
| 340 |
+
fill=(50, 50, 50), outline=(30, 30, 30), width=2)
|
| 341 |
+
|
| 342 |
+
return img
|
| 343 |
+
|
| 344 |
+
def create_house_object(size, color=(255, 228, 196)):
|
| 345 |
+
"""Cria objeto casa"""
|
| 346 |
+
img = Image.new('RGBA', (size, size), (0, 0, 0, 0))
|
| 347 |
+
draw = ImageDraw.Draw(img)
|
| 348 |
+
|
| 349 |
+
house_width = size * 2 // 3
|
| 350 |
+
house_height = size // 2
|
| 351 |
+
house_x = (size - house_width) // 2
|
| 352 |
+
house_y = size // 2
|
| 353 |
+
|
| 354 |
+
# Corpo da casa
|
| 355 |
+
draw.rectangle([house_x, house_y, house_x+house_width, house_y+house_height],
|
| 356 |
+
fill=color, outline=(210, 180, 140), width=3)
|
| 357 |
+
|
| 358 |
+
# Telhado
|
| 359 |
+
roof_color = (139, 0, 0)
|
| 360 |
+
draw.polygon([(house_x-10, house_y),
|
| 361 |
+
(house_x+house_width//2, house_y-house_height//2),
|
| 362 |
+
(house_x+house_width+10, house_y)],
|
| 363 |
+
fill=roof_color, outline=(178, 34, 34), width=3)
|
| 364 |
+
|
| 365 |
+
# Porta
|
| 366 |
+
door_color = (101, 67, 33)
|
| 367 |
+
door_width = house_width // 4
|
| 368 |
+
door_height = house_height // 2
|
| 369 |
+
draw.rectangle([house_x+house_width//2-door_width//2,
|
| 370 |
+
house_y+house_height-door_height,
|
| 371 |
+
house_x+house_width//2+door_width//2,
|
| 372 |
+
house_y+house_height],
|
| 373 |
+
fill=door_color, outline=(139, 69, 19), width=2)
|
| 374 |
+
|
| 375 |
+
# Janelas
|
| 376 |
+
window_color = (173, 216, 230)
|
| 377 |
+
window_size = house_width // 6
|
| 378 |
+
|
| 379 |
+
# Janela esquerda
|
| 380 |
+
draw.rectangle([house_x+window_size, house_y+window_size,
|
| 381 |
+
house_x+window_size*2, house_y+window_size*2],
|
| 382 |
+
fill=window_color, outline=(100, 149, 237), width=2)
|
| 383 |
+
|
| 384 |
+
# Janela direita
|
| 385 |
+
draw.rectangle([house_x+house_width-window_size*2, house_y+window_size,
|
| 386 |
+
house_x+house_width-window_size, house_y+window_size*2],
|
| 387 |
+
fill=window_color, outline=(100, 149, 237), width=2)
|
| 388 |
+
|
| 389 |
+
# Cruz nas janelas
|
| 390 |
+
for wx, wy in [(house_x+window_size*1.5, house_y+window_size*1.5),
|
| 391 |
+
(house_x+house_width-window_size*1.5, house_y+window_size*1.5)]:
|
| 392 |
+
draw.line([(wx-window_size//2, wy), (wx+window_size//2, wy)],
|
| 393 |
+
fill=(100, 149, 237), width=1)
|
| 394 |
+
draw.line([(wx, wy-window_size//2), (wx, wy+window_size//2)],
|
| 395 |
+
fill=(100, 149, 237), width=1)
|
| 396 |
+
|
| 397 |
+
return img
|
| 398 |
+
|
| 399 |
+
def create_cloud_object(size, color=(255, 255, 255)):
|
| 400 |
+
"""Cria objeto nuvem"""
|
| 401 |
+
img = Image.new('RGBA', (size, size), (0, 0, 0, 0))
|
| 402 |
+
draw = ImageDraw.Draw(img)
|
| 403 |
+
|
| 404 |
+
center_x, center_y = size // 2, size // 2
|
| 405 |
+
cloud_radius = size // 3
|
| 406 |
+
|
| 407 |
+
# Nuvem como vários círculos sobrepostos
|
| 408 |
+
circles = [
|
| 409 |
+
(center_x - cloud_radius//2, center_y, cloud_radius),
|
| 410 |
+
(center_x + cloud_radius//2, center_y, cloud_radius),
|
| 411 |
+
(center_x, center_y - cloud_radius//2, cloud_radius),
|
| 412 |
+
(center_x - cloud_radius, center_y, cloud_radius//2),
|
| 413 |
+
(center_x + cloud_radius, center_y, cloud_radius//2)
|
| 414 |
+
]
|
| 415 |
+
|
| 416 |
+
for cx, cy, radius in circles:
|
| 417 |
+
draw.ellipse([cx-radius, cy-radius, cx+radius, cy+radius],
|
| 418 |
+
fill=color, outline=(240, 240, 240), width=2)
|
| 419 |
+
|
| 420 |
+
return img
|
| 421 |
+
|
| 422 |
+
def create_sun_object(size, color=(255, 255, 0)):
|
| 423 |
+
"""Cria objeto sol"""
|
| 424 |
+
img = Image.new('RGBA', (size, size), (0, 0, 0, 0))
|
| 425 |
+
draw = ImageDraw.Draw(img)
|
| 426 |
+
|
| 427 |
+
center_x, center_y = size // 2, size // 2
|
| 428 |
+
sun_radius = size // 3
|
| 429 |
+
|
| 430 |
+
# Sol
|
| 431 |
+
draw.ellipse([center_x-sun_radius, center_y-sun_radius,
|
| 432 |
+
center_x+sun_radius, center_y+sun_radius],
|
| 433 |
+
fill=color, outline=(255, 165, 0), width=3)
|
| 434 |
+
|
| 435 |
+
# Raios de sol
|
| 436 |
+
ray_length = sun_radius + size // 8
|
| 437 |
+
for angle in range(0, 360, 30):
|
| 438 |
+
rad = math.radians(angle)
|
| 439 |
+
start_x = center_x + sun_radius * math.cos(rad)
|
| 440 |
+
start_y = center_y + sun_radius * math.sin(rad)
|
| 441 |
+
end_x = center_x + ray_length * math.cos(rad)
|
| 442 |
+
end_y = center_y + ray_length * math.sin(rad)
|
| 443 |
+
|
| 444 |
+
draw.line([(start_x, start_y), (end_x, end_y)],
|
| 445 |
+
fill=color, width=3)
|
| 446 |
+
|
| 447 |
+
return img
|
| 448 |
+
|
| 449 |
+
def create_moon_object(size, color=(240, 240, 240)):
|
| 450 |
+
"""Cria objeto lua"""
|
| 451 |
+
img = Image.new('RGBA', (size, size), (0, 0, 0, 0))
|
| 452 |
+
draw = ImageDraw.Draw(img)
|
| 453 |
+
|
| 454 |
+
center_x, center_y = size // 2, size // 2
|
| 455 |
+
moon_radius = size // 3
|
| 456 |
+
|
| 457 |
+
# Lua cheia com crateras
|
| 458 |
+
draw.ellipse([center_x-moon_radius, center_y-moon_radius,
|
| 459 |
+
center_x+moon_radius, center_y+moon_radius],
|
| 460 |
+
fill=color, outline=(200, 200, 200), width=3)
|
| 461 |
+
|
| 462 |
+
# Crateras
|
| 463 |
+
crater_colors = [(220, 220, 220), (210, 210, 210), (230, 230, 230)]
|
| 464 |
+
for i in range(5):
|
| 465 |
+
cr_x = center_x + random.randint(-moon_radius//2, moon_radius//2)
|
| 466 |
+
cr_y = center_y + random.randint(-moon_radius//2, moon_radius//2)
|
| 467 |
+
cr_radius = random.randint(moon_radius//8, moon_radius//4)
|
| 468 |
+
|
| 469 |
+
if (cr_x - center_x)**2 + (cr_y - center_y)**2 < (moon_radius - cr_radius)**2:
|
| 470 |
+
draw.ellipse([cr_x-cr_radius, cr_y-cr_radius,
|
| 471 |
+
cr_x+cr_radius, cr_y+cr_radius],
|
| 472 |
+
fill=random.choice(crater_colors),
|
| 473 |
+
outline=(190, 190, 190), width=1)
|
| 474 |
+
|
| 475 |
+
return img
|
| 476 |
+
|
| 477 |
+
def create_text_object(size, text="TEXTO", color=(0, 0, 0)):
|
| 478 |
+
"""Cria objeto de texto"""
|
| 479 |
+
img = Image.new('RGBA', (size, size), (0, 0, 0, 0))
|
| 480 |
+
draw = ImageDraw.Draw(img)
|
| 481 |
+
|
| 482 |
+
try:
|
| 483 |
+
# Tentar carregar fonte
|
| 484 |
+
font_size = min(size // 4, 48)
|
| 485 |
+
try:
|
| 486 |
+
font = ImageFont.truetype("arial.ttf", font_size)
|
| 487 |
+
except:
|
| 488 |
+
font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", font_size)
|
| 489 |
+
except:
|
| 490 |
+
font = ImageFont.load_default()
|
| 491 |
+
|
| 492 |
+
# Fundo para texto
|
| 493 |
+
bg_color = (255, 255, 255, 200)
|
| 494 |
+
text_bbox = draw.textbbox((0, 0), text, font=font)
|
| 495 |
+
text_width = text_bbox[2] - text_bbox[0]
|
| 496 |
+
text_height = text_bbox[3] - text_bbox[1]
|
| 497 |
+
|
| 498 |
+
bg_x = (size - text_width) // 2 - 10
|
| 499 |
+
bg_y = (size - text_height) // 2 - 5
|
| 500 |
+
bg_width = text_width + 20
|
| 501 |
+
bg_height = text_height + 10
|
| 502 |
+
|
| 503 |
+
draw.rounded_rectangle([bg_x, bg_y, bg_x+bg_width, bg_y+bg_height],
|
| 504 |
+
radius=5, fill=bg_color, outline=color, width=2)
|
| 505 |
+
|
| 506 |
+
# Texto
|
| 507 |
+
text_x = (size - text_width) // 2
|
| 508 |
+
text_y = (size - text_height) // 2
|
| 509 |
+
|
| 510 |
+
draw.text((text_x, text_y), text, fill=color, font=font)
|
| 511 |
+
|
| 512 |
+
return img
|
| 513 |
+
|
| 514 |
+
def create_logo_object(size, color=(0, 100, 200)):
|
| 515 |
+
"""Cria objeto logo"""
|
| 516 |
+
img = Image.new('RGBA', (size, size), (0, 0, 0, 0))
|
| 517 |
+
draw = ImageDraw.Draw(img)
|
| 518 |
+
|
| 519 |
+
center_x, center_y = size // 2, size // 2
|
| 520 |
+
logo_radius = size // 3
|
| 521 |
+
|
| 522 |
+
# Círculo externo
|
| 523 |
+
draw.ellipse([center_x-logo_radius, center_y-logo_radius,
|
| 524 |
+
center_x+logo_radius, center_y+logo_radius],
|
| 525 |
+
fill=color, outline=(0, 80, 180), width=3)
|
| 526 |
+
|
| 527 |
+
# Letra/ícone interno
|
| 528 |
+
inner_radius = logo_radius * 2 // 3
|
| 529 |
+
inner_color = (255, 255, 255)
|
| 530 |
+
|
| 531 |
+
# "L" estilizada
|
| 532 |
+
draw.rectangle([center_x-inner_radius//2, center_y-inner_radius,
|
| 533 |
+
center_x-inner_radius//4, center_y+inner_radius//4],
|
| 534 |
+
fill=inner_color, outline=inner_color, width=2)
|
| 535 |
+
draw.rectangle([center_x-inner_radius//2, center_y+inner_radius//4,
|
| 536 |
+
center_x+inner_radius//2, center_y+inner_radius//2],
|
| 537 |
+
fill=inner_color, outline=inner_color, width=2)
|
| 538 |
+
|
| 539 |
+
# Texto abaixo
|
| 540 |
+
try:
|
| 541 |
+
font_size = size // 10
|
| 542 |
+
try:
|
| 543 |
+
font = ImageFont.truetype("arial.ttf", font_size)
|
| 544 |
+
except:
|
| 545 |
+
font = ImageFont.load_default()
|
| 546 |
+
|
| 547 |
+
text = "LOGO"
|
| 548 |
+
text_bbox = draw.textbbox((0, 0), text, font=font)
|
| 549 |
+
text_width = text_bbox[2] - text_bbox[0]
|
| 550 |
+
|
| 551 |
+
draw.text(((size - text_width) // 2, center_y+logo_radius+5),
|
| 552 |
+
text, fill=color, font=font)
|
| 553 |
+
except:
|
| 554 |
+
pass
|
| 555 |
+
|
| 556 |
+
return img
|
| 557 |
+
|
| 558 |
+
def create_pattern_object(size, color=(100, 200, 100)):
|
| 559 |
+
"""Cria objeto padrão"""
|
| 560 |
+
img = Image.new('RGBA', (size, size), (0, 0, 0, 0))
|
| 561 |
+
draw = ImageDraw.Draw(img)
|
| 562 |
+
|
| 563 |
+
# Padrão geométrico
|
| 564 |
+
cell_size = size // 8
|
| 565 |
+
|
| 566 |
+
for y in range(0, size, cell_size):
|
| 567 |
+
for x in range(0, size, cell_size):
|
| 568 |
+
if (x // cell_size + y // cell_size) % 2 == 0:
|
| 569 |
+
# Quadrado
|
| 570 |
+
draw.rectangle([x, y, x+cell_size, y+cell_size],
|
| 571 |
+
fill=color, outline=(80, 180, 80), width=1)
|
| 572 |
+
|
| 573 |
+
# Círculo dentro
|
| 574 |
+
circle_color = (color[0]+50, color[1]+50, color[2]+50)
|
| 575 |
+
draw.ellipse([x+cell_size//4, y+cell_size//4,
|
| 576 |
+
x+cell_size*3//4, y+cell_size*3//4],
|
| 577 |
+
fill=circle_color, outline=color, width=1)
|
| 578 |
+
else:
|
| 579 |
+
# Triângulo
|
| 580 |
+
points = [(x+cell_size//2, y),
|
| 581 |
+
(x+cell_size, y+cell_size),
|
| 582 |
+
(x, y+cell_size)]
|
| 583 |
+
draw.polygon(points, fill=color, outline=(80, 180, 80), width=1)
|
| 584 |
+
|
| 585 |
+
return img
|
| 586 |
+
|
| 587 |
+
def create_gradient_object(size, color1=(255, 0, 0), color2=(0, 0, 255)):
|
| 588 |
+
"""Cria objeto gradiente"""
|
| 589 |
+
img = Image.new('RGB', (size, size), (0, 0, 0))
|
| 590 |
+
|
| 591 |
+
# Criar gradiente vertical
|
| 592 |
+
for y in range(size):
|
| 593 |
+
# Interpolação linear
|
| 594 |
+
ratio = y / size
|
| 595 |
+
r = int(color1[0] * (1 - ratio) + color2[0] * ratio)
|
| 596 |
+
g = int(color1[1] * (1 - ratio) + color2[1] * ratio)
|
| 597 |
+
b = int(color1[2] * (1 - ratio) + color2[2] * ratio)
|
| 598 |
+
|
| 599 |
+
# Desenhar linha
|
| 600 |
+
for x in range(size):
|
| 601 |
+
# Adicionar variação horizontal leve
|
| 602 |
+
h_ratio = x / size
|
| 603 |
+
hr = int(r * (0.9 + 0.1 * math.sin(h_ratio * math.pi)))
|
| 604 |
+
hg = int(g * (0.9 + 0.1 * math.sin(h_ratio * math.pi)))
|
| 605 |
+
hb = int(b * (0.9 + 0.1 * math.sin(h_ratio * math.pi)))
|
| 606 |
+
|
| 607 |
+
img.putpixel((x, y), (hr, hg, hb))
|
| 608 |
+
|
| 609 |
+
return img.convert('RGBA')
|
| 610 |
+
|
| 611 |
+
# ========== FUNÇÃO PRINCIPAL DE SUBSTITUIÇÃO ==========
|
| 612 |
+
|
| 613 |
+
def replace_object(image, selection_box, object_type, custom_text=""):
|
| 614 |
+
"""Substitui objeto na imagem"""
|
| 615 |
+
try:
|
| 616 |
+
log_message(f"Substituindo objeto - Tipo: {object_type}, Box: {selection_box}")
|
| 617 |
+
|
| 618 |
+
# Validar box
|
| 619 |
+
if selection_box is None or len(selection_box) != 4:
|
| 620 |
+
return None, "❌ Selecione uma área na imagem primeiro"
|
| 621 |
+
|
| 622 |
+
x1, y1, x2, y2 = selection_box
|
| 623 |
+
if x2 <= x1 or y2 <= y1:
|
| 624 |
+
return None, "❌ Área de seleção inválida"
|
| 625 |
+
|
| 626 |
+
# Validar imagem
|
| 627 |
+
img, msg = validate_image(image)
|
| 628 |
+
if img is None:
|
| 629 |
+
return None, msg
|
| 630 |
+
|
| 631 |
+
# Redimensionar se necessário
|
| 632 |
+
img = resize_image(img, MAX_IMAGE_SIZE)
|
| 633 |
+
|
| 634 |
+
# Obter tamanho do objeto a ser inserido
|
| 635 |
+
obj_width = x2 - x1
|
| 636 |
+
obj_height = y2 - y1
|
| 637 |
+
obj_size = max(obj_width, obj_height)
|
| 638 |
+
|
| 639 |
+
# Criar objeto baseado no tipo
|
| 640 |
+
if object_type == "emoji":
|
| 641 |
+
replacement = create_emoji_object(obj_size)
|
| 642 |
+
elif object_type == "heart":
|
| 643 |
+
replacement = create_heart_object(obj_size)
|
| 644 |
+
elif object_type == "star":
|
| 645 |
+
replacement = create_star_object(obj_size)
|
| 646 |
+
elif object_type == "flower":
|
| 647 |
+
replacement = create_flower_object(obj_size)
|
| 648 |
+
elif object_type == "tree":
|
| 649 |
+
replacement = create_tree_object(obj_size)
|
| 650 |
+
elif object_type == "car":
|
| 651 |
+
replacement = create_car_object(obj_size)
|
| 652 |
+
elif object_type == "house":
|
| 653 |
+
replacement = create_house_object(obj_size)
|
| 654 |
+
elif object_type == "cloud":
|
| 655 |
+
replacement = create_cloud_object(obj_size)
|
| 656 |
+
elif object_type == "sun":
|
| 657 |
+
replacement = create_sun_object(obj_size)
|
| 658 |
+
elif object_type == "moon":
|
| 659 |
+
replacement = create_moon_object(obj_size)
|
| 660 |
+
elif object_type == "text":
|
| 661 |
+
replacement = create_text_object(obj_size, custom_text if custom_text else "TEXTO")
|
| 662 |
+
elif object_type == "logo":
|
| 663 |
+
replacement = create_logo_object(obj_size)
|
| 664 |
+
elif object_type == "pattern":
|
| 665 |
+
replacement = create_pattern_object(obj_size)
|
| 666 |
+
elif object_type == "gradient":
|
| 667 |
+
# Usar cores da área original para o gradiente
|
| 668 |
+
avg_color = get_average_color(img, (x1, y1, x2, y2))
|
| 669 |
+
# Criar cor complementar
|
| 670 |
+
h, l, s = colorsys.rgb_to_hls(avg_color[0]/255, avg_color[1]/255, avg_color[2]/255)
|
| 671 |
+
comp_h = (h + 0.5) % 1.0
|
| 672 |
+
r2, g2, b2 = [int(c*255) for c in colorsys.hls_to_rgb(comp_h, l, s)]
|
| 673 |
+
replacement = create_gradient_object(obj_size, avg_color, (r2, g2, b2))
|
| 674 |
+
elif object_type == "transparent":
|
| 675 |
+
# Remover objeto (deixar transparente)
|
| 676 |
+
replacement = Image.new('RGBA', (obj_width, obj_height), (0, 0, 0, 0))
|
| 677 |
+
else:
|
| 678 |
+
return None, f"❌ Tipo de objeto não suportado: {object_type}"
|
| 679 |
+
|
| 680 |
+
# Redimensionar objeto para caber na área selecionada
|
| 681 |
+
replacement = replacement.resize((obj_width, obj_height), Image.Resampling.LANCZOS)
|
| 682 |
+
|
| 683 |
+
# Criar cópia da imagem original
|
| 684 |
+
result = img.copy()
|
| 685 |
+
|
| 686 |
+
if object_type == "transparent":
|
| 687 |
+
# Para remoção, criar máscara e aplicar
|
| 688 |
+
mask = create_mask_from_selection(img, (x1, y1, x2, y2))
|
| 689 |
+
|
| 690 |
+
# Converter imagem para RGBA se necessário
|
| 691 |
+
if result.mode != 'RGBA':
|
| 692 |
+
result = result.convert('RGBA')
|
| 693 |
+
|
| 694 |
+
# Colar área transparente usando a máscara
|
| 695 |
+
result.paste(replacement, (x1, y1), mask.crop((x1, y1, x2, y2)))
|
| 696 |
+
else:
|
| 697 |
+
# Para substituição, colocar o novo objeto
|
| 698 |
+
# Criar máscara suavizada
|
| 699 |
+
mask = create_mask_from_selection(img, (x1, y1, x2, y2))
|
| 700 |
+
crop_mask = mask.crop((x1, y1, x2, y2))
|
| 701 |
+
|
| 702 |
+
# Ajustar objeto para combinar com o fundo
|
| 703 |
+
# Obter cor média da área ao redor para blending
|
| 704 |
+
expanded_box = (
|
| 705 |
+
max(0, x1 - 10), max(0, y1 - 10),
|
| 706 |
+
min(img.width, x2 + 10), min(img.height, y2 + 10)
|
| 707 |
+
)
|
| 708 |
+
bg_color = get_average_color(img, expanded_box)
|
| 709 |
+
|
| 710 |
+
# Ajustar brilho/contraste do objeto para combinar
|
| 711 |
+
replacement_rgb = replacement.convert('RGB')
|
| 712 |
+
replacement_array = np.array(replacement_rgb).astype(float)
|
| 713 |
+
|
| 714 |
+
# Ajustar para combinar com fundo
|
| 715 |
+
bg_factor = np.mean(bg_color) / 128.0
|
| 716 |
+
replacement_array = np.clip(replacement_array * bg_factor, 0, 255)
|
| 717 |
+
|
| 718 |
+
replacement = Image.fromarray(replacement_array.astype(np.uint8))
|
| 719 |
+
replacement.putalpha(replacement.split()[3]) # Manter alpha original
|
| 720 |
+
|
| 721 |
+
# Colar objeto na imagem
|
| 722 |
+
if result.mode != 'RGBA':
|
| 723 |
+
result = result.convert('RGBA')
|
| 724 |
+
|
| 725 |
+
result.paste(replacement, (x1, y1), crop_mask)
|
| 726 |
+
|
| 727 |
+
# Aplicar blur nas bordas para melhor integração
|
| 728 |
+
border_mask = mask.crop((x1, y1, x2, y2))
|
| 729 |
+
border_mask = border_mask.filter(ImageFilter.GaussianBlur(radius=2))
|
| 730 |
+
|
| 731 |
+
# Criar cópia final com melhor blending
|
| 732 |
+
final_result = img.copy()
|
| 733 |
+
if final_result.mode != 'RGBA':
|
| 734 |
+
final_result = final_result.convert('RGBA')
|
| 735 |
+
|
| 736 |
+
temp_image = Image.new('RGBA', final_result.size, (0, 0, 0, 0))
|
| 737 |
+
temp_image.paste(result.crop((x1, y1, x2, y2)), (x1, y1))
|
| 738 |
+
|
| 739 |
+
final_result = Image.composite(temp_image, final_result, mask)
|
| 740 |
+
|
| 741 |
+
log_message("✅ Objeto substituído com sucesso")
|
| 742 |
+
return final_result.convert('RGB'), "✅ Objeto substituído com sucesso!"
|
| 743 |
+
|
| 744 |
+
except Exception as e:
|
| 745 |
+
error_msg = f"❌ Erro ao substituir objeto: {str(e)}"
|
| 746 |
+
log_message(error_msg)
|
| 747 |
+
return None, error_msg
|
| 748 |
+
|
| 749 |
+
def save_modified_image(image, prefix="modified"):
|
| 750 |
+
"""Salva imagem modificada"""
|
| 751 |
+
try:
|
| 752 |
+
if image is None:
|
| 753 |
+
return None
|
| 754 |
+
|
| 755 |
+
timestamp = time.strftime("%Y%m%d_%H%M%S")
|
| 756 |
+
|
| 757 |
+
temp_file = tempfile.NamedTemporaryFile(
|
| 758 |
+
delete=False,
|
| 759 |
+
suffix=".png",
|
| 760 |
+
prefix=f"{prefix}_"
|
| 761 |
+
)
|
| 762 |
+
|
| 763 |
+
image.save(temp_file.name, "PNG", optimize=True)
|
| 764 |
+
|
| 765 |
+
file_size = os.path.getsize(temp_file.name) // 1024
|
| 766 |
+
log_message(f"Imagem salva: {temp_file.name} ({file_size}KB)")
|
| 767 |
+
|
| 768 |
+
return temp_file.name
|
| 769 |
+
|
| 770 |
+
except Exception as e:
|
| 771 |
+
log_message(f"❌ Erro ao salvar: {str(e)}")
|
| 772 |
+
return None
|
| 773 |
+
|
| 774 |
+
# ========== INTERFACE GRADIO ==========
|
| 775 |
+
|
| 776 |
+
print("🎨 Criando interface Object Replacer...")
|
| 777 |
+
|
| 778 |
+
# Estilo CSS customizado
|
| 779 |
+
custom_css = """
|
| 780 |
+
.gradio-container {
|
| 781 |
+
max-width: 1200px !important;
|
| 782 |
+
margin: 0 auto !important;
|
| 783 |
+
}
|
| 784 |
+
.container {
|
| 785 |
+
max-width: 1200px;
|
| 786 |
+
margin: 0 auto;
|
| 787 |
+
padding: 20px;
|
| 788 |
+
}
|
| 789 |
+
.header {
|
| 790 |
+
text-align: center;
|
| 791 |
+
margin-bottom: 30px;
|
| 792 |
+
padding: 20px;
|
| 793 |
+
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 794 |
+
border-radius: 15px;
|
| 795 |
+
color: white;
|
| 796 |
+
}
|
| 797 |
+
.header h1 {
|
| 798 |
+
margin: 0;
|
| 799 |
+
font-size: 2.5em;
|
| 800 |
+
font-weight: 700;
|
| 801 |
+
}
|
| 802 |
+
.header p {
|
| 803 |
+
margin: 10px 0 0 0;
|
| 804 |
+
font-size: 1.2em;
|
| 805 |
+
opacity: 0.9;
|
| 806 |
+
}
|
| 807 |
+
.section {
|
| 808 |
+
background: white;
|
| 809 |
+
padding: 25px;
|
| 810 |
+
border-radius: 15px;
|
| 811 |
+
margin-bottom: 20px;
|
| 812 |
+
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
|
| 813 |
+
}
|
| 814 |
+
.section-title {
|
| 815 |
+
color: #333;
|
| 816 |
+
margin-bottom: 20px;
|
| 817 |
+
padding-bottom: 10px;
|
| 818 |
+
border-bottom: 2px solid #667eea;
|
| 819 |
+
font-size: 1.5em;
|
| 820 |
+
font-weight: 600;
|
| 821 |
+
}
|
| 822 |
+
.object-preview {
|
| 823 |
+
display: flex;
|
| 824 |
+
flex-wrap: wrap;
|
| 825 |
+
gap: 15px;
|
| 826 |
+
justify-content: center;
|
| 827 |
+
margin: 20px 0;
|
| 828 |
+
}
|
| 829 |
+
.object-item {
|
| 830 |
+
text-align: center;
|
| 831 |
+
cursor: pointer;
|
| 832 |
+
padding: 10px;
|
| 833 |
+
border-radius: 10px;
|
| 834 |
+
transition: all 0.3s ease;
|
| 835 |
+
background: #f8f9fa;
|
| 836 |
+
border: 2px solid transparent;
|
| 837 |
+
}
|
| 838 |
+
.object-item:hover {
|
| 839 |
+
transform: translateY(-5px);
|
| 840 |
+
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
|
| 841 |
+
border-color: #667eea;
|
| 842 |
+
background: white;
|
| 843 |
+
}
|
| 844 |
+
.object-icon {
|
| 845 |
+
font-size: 2.5em;
|
| 846 |
+
margin-bottom: 5px;
|
| 847 |
+
}
|
| 848 |
+
.object-label {
|
| 849 |
+
font-size: 0.9em;
|
| 850 |
+
color: #555;
|
| 851 |
+
}
|
| 852 |
+
.instructions {
|
| 853 |
+
background: #f0f7ff;
|
| 854 |
+
padding: 15px;
|
| 855 |
+
border-radius: 10px;
|
| 856 |
+
margin: 15px 0;
|
| 857 |
+
border-left: 4px solid #667eea;
|
| 858 |
+
}
|
| 859 |
+
.step {
|
| 860 |
+
margin: 10px 0;
|
| 861 |
+
padding: 8px;
|
| 862 |
+
background: white;
|
| 863 |
+
border-radius: 8px;
|
| 864 |
+
display: flex;
|
| 865 |
+
align-items: center;
|
| 866 |
+
}
|
| 867 |
+
.step-number {
|
| 868 |
+
background: #667eea;
|
| 869 |
+
color: white;
|
| 870 |
+
width: 30px;
|
| 871 |
+
height: 30px;
|
| 872 |
+
border-radius: 50%;
|
| 873 |
+
display: flex;
|
| 874 |
+
align-items: center;
|
| 875 |
+
justify-content: center;
|
| 876 |
+
margin-right: 15px;
|
| 877 |
+
font-weight: bold;
|
| 878 |
+
}
|
| 879 |
+
.result-box {
|
| 880 |
+
border: 2px dashed #667eea;
|
| 881 |
+
border-radius: 10px;
|
| 882 |
+
padding: 20px;
|
| 883 |
+
text-align: center;
|
| 884 |
+
background: #f8f9ff;
|
| 885 |
+
}
|
| 886 |
+
.download-btn {
|
| 887 |
+
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 888 |
+
color: white;
|
| 889 |
+
border: none;
|
| 890 |
+
padding: 12px 30px;
|
| 891 |
+
border-radius: 25px;
|
| 892 |
+
font-weight: 600;
|
| 893 |
+
cursor: pointer;
|
| 894 |
+
transition: all 0.3s ease;
|
| 895 |
+
text-decoration: none;
|
| 896 |
+
display: inline-block;
|
| 897 |
+
margin: 10px;
|
| 898 |
+
}
|
| 899 |
+
.download-btn:hover {
|
| 900 |
+
transform: translateY(-2px);
|
| 901 |
+
box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
|
| 902 |
+
}
|
| 903 |
+
.status-message {
|
| 904 |
+
padding: 10px;
|
| 905 |
+
border-radius: 5px;
|
| 906 |
+
margin: 10px 0;
|
| 907 |
+
font-weight: 500;
|
| 908 |
+
}
|
| 909 |
+
.status-success {
|
| 910 |
+
background: #d4edda;
|
| 911 |
+
color: #155724;
|
| 912 |
+
border: 1px solid #c3e6cb;
|
| 913 |
+
}
|
| 914 |
+
.status-error {
|
| 915 |
+
background: #f8d7da;
|
| 916 |
+
color: #721c24;
|
| 917 |
+
border: 1px solid #f5c6cb;
|
| 918 |
+
}
|
| 919 |
+
.footer {
|
| 920 |
+
text-align: center;
|
| 921 |
+
margin-top: 30px;
|
| 922 |
+
padding: 20px;
|
| 923 |
+
color: #666;
|
| 924 |
+
font-size: 0.9em;
|
| 925 |
+
}
|
| 926 |
+
"""
|
| 927 |
+
|
| 928 |
+
# Função para criar preview dos objetos
|
| 929 |
+
def create_object_preview(object_type, label):
|
| 930 |
+
"""Cria preview visual do objeto"""
|
| 931 |
+
preview_size = 100
|
| 932 |
+
if object_type == "emoji":
|
| 933 |
+
preview = create_emoji_object(preview_size)
|
| 934 |
+
elif object_type == "heart":
|
| 935 |
+
preview = create_heart_object(preview_size)
|
| 936 |
+
elif object_type == "star":
|
| 937 |
+
preview = create_star_object(preview_size)
|
| 938 |
+
elif object_type == "flower":
|
| 939 |
+
preview = create_flower_object(preview_size)
|
| 940 |
+
elif object_type == "tree":
|
| 941 |
+
preview = create_tree_object(preview_size)
|
| 942 |
+
elif object_type == "car":
|
| 943 |
+
preview = create_car_object(preview_size)
|
| 944 |
+
elif object_type == "house":
|
| 945 |
+
preview = create_house_object(preview_size)
|
| 946 |
+
elif object_type == "cloud":
|
| 947 |
+
preview = create_cloud_object(preview_size)
|
| 948 |
+
elif object_type == "sun":
|
| 949 |
+
preview = create_sun_object(preview_size)
|
| 950 |
+
elif object_type == "moon":
|
| 951 |
+
preview = create_moon_object(preview_size)
|
| 952 |
+
elif object_type == "text":
|
| 953 |
+
preview = create_text_object(preview_size, "ABC")
|
| 954 |
+
elif object_type == "logo":
|
| 955 |
+
preview = create_logo_object(preview_size)
|
| 956 |
+
elif object_type == "pattern":
|
| 957 |
+
preview = create_pattern_object(preview_size)
|
| 958 |
+
elif object_type == "gradient":
|
| 959 |
+
preview = create_gradient_object(preview_size)
|
| 960 |
+
elif object_type == "transparent":
|
| 961 |
+
preview = Image.new('RGBA', (preview_size, preview_size), (0, 0, 0, 0))
|
| 962 |
+
draw = ImageDraw.Draw(preview)
|
| 963 |
+
draw.rectangle([0, 0, preview_size, preview_size], outline=(200, 0, 0), width=3)
|
| 964 |
+
draw.line([0, 0, preview_size, preview_size], fill=(200, 0, 0), width=3)
|
| 965 |
+
draw.line([preview_size, 0, 0, preview_size], fill=(200, 0, 0), width=3)
|
| 966 |
+
else:
|
| 967 |
+
preview = Image.new('RGB', (preview_size, preview_size), (200, 200, 200))
|
| 968 |
+
|
| 969 |
+
# Converter para base64 para mostrar na interface
|
| 970 |
+
import base64
|
| 971 |
+
from io import BytesIO
|
| 972 |
+
|
| 973 |
+
buffered = BytesIO()
|
| 974 |
+
preview.save(buffered, format="PNG")
|
| 975 |
+
img_str = base64.b64encode(buffered.getvalue()).decode()
|
| 976 |
+
|
| 977 |
+
return f"""
|
| 978 |
+
<div class="object-item" onclick="document.querySelector('#object-type-select').value='{object_type}'; document.querySelector('#object-type-select').dispatchEvent(new Event('change'));">
|
| 979 |
+
<div class="object-icon">
|
| 980 |
+
<img src="data:image/png;base64,{img_str}" width="80" height="80" style="border-radius: 10px;">
|
| 981 |
+
</div>
|
| 982 |
+
<div class="object-label">{label}</div>
|
| 983 |
+
</div>
|
| 984 |
+
"""
|
| 985 |
+
|
| 986 |
+
# Interface principal
|
| 987 |
+
def create_interface():
|
| 988 |
+
with gr.Blocks(title="🎨 Object Replacer - Photoshop AI App 8",
|
| 989 |
+
theme=gr.themes.Soft(),
|
| 990 |
+
css=custom_css) as demo:
|
| 991 |
+
|
| 992 |
+
# Header
|
| 993 |
+
gr.HTML("""
|
| 994 |
+
<div class="header">
|
| 995 |
+
<h1>🎨 Object Replacer</h1>
|
| 996 |
+
<p>App 8 do Photoshop AI Ecosystem - Substitua objetos em imagens de forma inteligente</p>
|
| 997 |
+
</div>
|
| 998 |
+
""")
|
| 999 |
+
|
| 1000 |
+
with gr.Row():
|
| 1001 |
+
# Coluna esquerda - Upload e Configuração
|
| 1002 |
+
with gr.Column(scale=1):
|
| 1003 |
+
with gr.Group():
|
| 1004 |
+
gr.Markdown("### 📤 Upload da Imagem")
|
| 1005 |
+
image_input = gr.Image(
|
| 1006 |
+
label="Arraste ou clique para fazer upload",
|
| 1007 |
+
type="pil",
|
| 1008 |
+
interactive=True,
|
| 1009 |
+
height=300
|
| 1010 |
+
)
|
| 1011 |
+
|
| 1012 |
+
with gr.Group():
|
| 1013 |
+
gr.Markdown("### 🎯 Seleção da Área")
|
| 1014 |
+
gr.Markdown("Arraste na imagem para selecionar o objeto a ser substituído")
|
| 1015 |
+
select_button = gr.Image(
|
| 1016 |
+
label="Clique e arraste para selecionar",
|
| 1017 |
+
type="pil",
|
| 1018 |
+
interactive=True,
|
| 1019 |
+
height=300,
|
| 1020 |
+
tool="sketch"
|
| 1021 |
+
)
|
| 1022 |
+
|
| 1023 |
+
with gr.Group():
|
| 1024 |
+
gr.Markdown("### ⚙️ Configurações")
|
| 1025 |
+
object_type_select = gr.Dropdown(
|
| 1026 |
+
choices=list(OBJECT_LIBRARY.values()),
|
| 1027 |
+
value="😀 Emoji",
|
| 1028 |
+
label="Tipo de Objeto",
|
| 1029 |
+
interactive=True
|
| 1030 |
+
)
|
| 1031 |
+
|
| 1032 |
+
custom_text = gr.Textbox(
|
| 1033 |
+
label="Texto Personalizado (para tipo Texto)",
|
| 1034 |
+
placeholder="Digite seu texto aqui...",
|
| 1035 |
+
visible=False
|
| 1036 |
+
)
|
| 1037 |
+
|
| 1038 |
+
def toggle_text_visibility(object_type):
|
| 1039 |
+
# Verifica se o objeto selecionado é "text"
|
| 1040 |
+
is_text = "Texto" in object_type
|
| 1041 |
+
return gr.update(visible=is_text)
|
| 1042 |
+
|
| 1043 |
+
object_type_select.change(
|
| 1044 |
+
fn=toggle_text_visibility,
|
| 1045 |
+
inputs=[object_type_select],
|
| 1046 |
+
outputs=[custom_text]
|
| 1047 |
+
)
|
| 1048 |
+
|
| 1049 |
+
# Coluna direita - Preview e Resultados
|
| 1050 |
+
with gr.Column(scale=1):
|
| 1051 |
+
with gr.Group():
|
| 1052 |
+
gr.Markdown("### 👁️ Preview dos Objetos")
|
| 1053 |
+
gr.HTML("""
|
| 1054 |
+
<div class="object-preview">
|
| 1055 |
+
""" +
|
| 1056 |
+
"".join([create_object_preview(k, v) for k, v in OBJECT_LIBRARY.items()]) +
|
| 1057 |
+
"""
|
| 1058 |
+
</div>
|
| 1059 |
+
""")
|
| 1060 |
+
|
| 1061 |
+
with gr.Group():
|
| 1062 |
+
gr.Markdown("### 🔄 Resultado")
|
| 1063 |
+
image_output = gr.Image(
|
| 1064 |
+
label="Imagem Modificada",
|
| 1065 |
+
type="pil",
|
| 1066 |
+
interactive=False,
|
| 1067 |
+
height=300
|
| 1068 |
+
)
|
| 1069 |
+
|
| 1070 |
+
status_output = gr.HTML(
|
| 1071 |
+
value="<div class='status-message'>Pronto para processar...</div>",
|
| 1072 |
+
label="Status"
|
| 1073 |
+
)
|
| 1074 |
+
|
| 1075 |
+
with gr.Group():
|
| 1076 |
+
gr.Markdown("### 💾 Download")
|
| 1077 |
+
download_button = gr.Button(
|
| 1078 |
+
"⬇️ Baixar Imagem Modificada",
|
| 1079 |
+
variant="primary",
|
| 1080 |
+
size="lg"
|
| 1081 |
+
)
|
| 1082 |
+
|
| 1083 |
+
download_file = gr.File(
|
| 1084 |
+
label="Arquivo para download",
|
| 1085 |
+
visible=False
|
| 1086 |
+
)
|
| 1087 |
+
|
| 1088 |
+
# Instruções
|
| 1089 |
+
gr.HTML("""
|
| 1090 |
+
<div class="instructions">
|
| 1091 |
+
<h3>📋 Instruções Passo a Passo:</h3>
|
| 1092 |
+
<div class="step">
|
| 1093 |
+
<div class="step-number">1</div>
|
| 1094 |
+
<div>Faça upload de uma imagem</div>
|
| 1095 |
+
</div>
|
| 1096 |
+
<div class="step">
|
| 1097 |
+
<div class="step-number">2</div>
|
| 1098 |
+
<div>Selecione a área do objeto na imagem</div>
|
| 1099 |
+
</div>
|
| 1100 |
+
<div class="step">
|
| 1101 |
+
<div class="step-number">3</div>
|
| 1102 |
+
<div>Escolha o tipo de objeto para substituição</div>
|
| 1103 |
+
</div>
|
| 1104 |
+
<div class="step">
|
| 1105 |
+
<div class="step-number">4</div>
|
| 1106 |
+
<div>Ajuste as configurações se necessário</div>
|
| 1107 |
+
</div>
|
| 1108 |
+
<div class="step">
|
| 1109 |
+
<div class="step-number">5</div>
|
| 1110 |
+
<div>Clique em 'Substituir Objeto' e baixe o resultado</div>
|
| 1111 |
+
</div>
|
| 1112 |
+
</div>
|
| 1113 |
+
""")
|
| 1114 |
+
|
| 1115 |
+
# Processamento
|
| 1116 |
+
def process_image(image, selection, object_type_label, text_input=""):
|
| 1117 |
+
try:
|
| 1118 |
+
if image is None:
|
| 1119 |
+
return None, None, "<div class='status-message status-error'>❌ Por favor, faça upload de uma imagem primeiro.</div>"
|
| 1120 |
+
|
| 1121 |
+
if selection is None or 'layers' not in selection or selection['layers'] is None:
|
| 1122 |
+
return None, None, "<div class='status-message status-error'>❌ Por favor, selecione uma área na imagem primeiro.</div>"
|
| 1123 |
+
|
| 1124 |
+
# Converter label para key
|
| 1125 |
+
object_type_key = None
|
| 1126 |
+
for key, value in OBJECT_LIBRARY.items():
|
| 1127 |
+
if value == object_type_label:
|
| 1128 |
+
object_type_key = key
|
| 1129 |
+
break
|
| 1130 |
+
|
| 1131 |
+
if object_type_key is None:
|
| 1132 |
+
return None, None, f"<div class='status-message status-error'>❌ Tipo de objeto inválido: {object_type_label}</div>"
|
| 1133 |
+
|
| 1134 |
+
# Obter coordenadas da seleção
|
| 1135 |
+
selection_layer = selection['layers'][0]
|
| 1136 |
+
x1 = int(selection_layer['x'])
|
| 1137 |
+
y1 = int(selection_layer['y'])
|
| 1138 |
+
x2 = int(selection_layer['x'] + selection_layer['width'])
|
| 1139 |
+
y2 = int(selection_layer['y'] + selection_layer['height'])
|
| 1140 |
+
|
| 1141 |
+
# Validar seleção
|
| 1142 |
+
if x2 <= x1 or y2 <= y1:
|
| 1143 |
+
return None, None, "<div class='status-message status-error'>❌ Área de seleção muito pequena. Por favor, selecione uma área maior.</div>"
|
| 1144 |
+
|
| 1145 |
+
# Processar substituição
|
| 1146 |
+
result, message = replace_object(image, (x1, y1, x2, y2), object_type_key, text_input)
|
| 1147 |
+
|
| 1148 |
+
if result is None:
|
| 1149 |
+
return None, None, f"<div class='status-message status-error'>{message}</div>"
|
| 1150 |
+
|
| 1151 |
+
# Salvar imagem
|
| 1152 |
+
temp_file = save_modified_image(result, "object_replaced")
|
| 1153 |
+
|
| 1154 |
+
if temp_file:
|
| 1155 |
+
status_html = f"<div class='status-message status-success'>{message}</div>"
|
| 1156 |
+
return result, temp_file, status_html
|
| 1157 |
+
else:
|
| 1158 |
+
return result, None, f"<div class='status-message status-success'>{message} (mas não foi possível salvar o arquivo)</div>"
|
| 1159 |
+
|
| 1160 |
+
except Exception as e:
|
| 1161 |
+
error_msg = f"<div class='status-message status-error'>❌ Erro no processamento: {str(e)}</div>"
|
| 1162 |
+
log_message(f"Erro no processamento: {str(e)}")
|
| 1163 |
+
return None, None, error_msg
|
| 1164 |
+
|
| 1165 |
+
# Conectar eventos
|
| 1166 |
+
select_button.change(
|
| 1167 |
+
fn=process_image,
|
| 1168 |
+
inputs=[image_input, select_button, object_type_select, custom_text],
|
| 1169 |
+
outputs=[image_output, download_file, status_output]
|
| 1170 |
+
)
|
| 1171 |
+
|
| 1172 |
+
object_type_select.change(
|
| 1173 |
+
fn=process_image,
|
| 1174 |
+
inputs=[image_input, select_button, object_type_select, custom_text],
|
| 1175 |
+
outputs=[image_output, download_file, status_output]
|
| 1176 |
+
)
|
| 1177 |
+
|
| 1178 |
+
custom_text.change(
|
| 1179 |
+
fn=process_image,
|
| 1180 |
+
inputs=[image_input, select_button, object_type_select, custom_text],
|
| 1181 |
+
outputs=[image_output, download_file, status_output]
|
| 1182 |
+
)
|
| 1183 |
+
|
| 1184 |
+
# Botão de download
|
| 1185 |
+
def trigger_download(image):
|
| 1186 |
+
if image is None:
|
| 1187 |
+
return None
|
| 1188 |
+
temp_file = save_modified_image(image, "object_replaced")
|
| 1189 |
+
return temp_file
|
| 1190 |
+
|
| 1191 |
+
download_button.click(
|
| 1192 |
+
fn=trigger_download,
|
| 1193 |
+
inputs=[image_output],
|
| 1194 |
+
outputs=[download_file]
|
| 1195 |
+
)
|
| 1196 |
+
|
| 1197 |
+
# Footer
|
| 1198 |
+
gr.HTML("""
|
| 1199 |
+
<div class="footer">
|
| 1200 |
+
<p>✨ Photoshop AI Ecosystem - App 8: Object Replacer ✨</p>
|
| 1201 |
+
<p>Ferramenta de substituição de objetos em imagens usando processamento inteligente</p>
|
| 1202 |
+
<p style="font-size: 0.8em; color: #999; margin-top: 10px;">
|
| 1203 |
+
⚡ Processamento em tempo real • 🎨 15 tipos de objetos • 🔧 Substituição inteligente
|
| 1204 |
+
</p>
|
| 1205 |
+
</div>
|
| 1206 |
+
""")
|
| 1207 |
+
|
| 1208 |
+
# JavaScript para melhorar a experiência
|
| 1209 |
+
gr.HTML("""
|
| 1210 |
+
<script>
|
| 1211 |
+
// Atualizar dinamicamente o preview quando o tipo de objeto mudar
|
| 1212 |
+
document.addEventListener('DOMContentLoaded', function() {
|
| 1213 |
+
const objectSelect = document.querySelector('#object-type-select');
|
| 1214 |
+
if (objectSelect) {
|
| 1215 |
+
objectSelect.addEventListener('change', function() {
|
| 1216 |
+
// Destacar o objeto selecionado no preview
|
| 1217 |
+
document.querySelectorAll('.object-item').forEach(item => {
|
| 1218 |
+
item.style.borderColor = 'transparent';
|
| 1219 |
+
item.style.background = '#f8f9fa';
|
| 1220 |
+
});
|
| 1221 |
+
|
| 1222 |
+
// Encontrar e destacar o item correspondente
|
| 1223 |
+
const selectedLabel = this.value;
|
| 1224 |
+
document.querySelectorAll('.object-label').forEach(label => {
|
| 1225 |
+
if (label.textContent === selectedLabel) {
|
| 1226 |
+
const item = label.closest('.object-item');
|
| 1227 |
+
if (item) {
|
| 1228 |
+
item.style.borderColor = '#667eea';
|
| 1229 |
+
item.style.background = 'white';
|
| 1230 |
+
item.style.boxShadow = '0 5px 15px rgba(0, 0, 0, 0.1)';
|
| 1231 |
+
}
|
| 1232 |
+
}
|
| 1233 |
+
});
|
| 1234 |
+
});
|
| 1235 |
+
|
| 1236 |
+
// Disparar evento inicial
|
| 1237 |
+
objectSelect.dispatchEvent(new Event('change'));
|
| 1238 |
+
}
|
| 1239 |
+
});
|
| 1240 |
+
</script>
|
| 1241 |
+
""")
|
| 1242 |
+
|
| 1243 |
+
return demo
|
| 1244 |
+
|
| 1245 |
+
# ========== EXECUÇÃO PRINCIPAL ==========
|
| 1246 |
+
|
| 1247 |
+
if __name__ == "__main__":
|
| 1248 |
+
print("🚀 Inicializando Object Replacer...")
|
| 1249 |
+
|
| 1250 |
+
# Criar interface
|
| 1251 |
+
demo = create_interface()
|
| 1252 |
+
|
| 1253 |
+
# Configurar para execução local
|
| 1254 |
+
demo.launch(
|
| 1255 |
+
server_name="0.0.0.0" if os.getenv('SPACE_ID') else "127.0.0.1",
|
| 1256 |
+
server_port=int(os.getenv('PORT', 7860)),
|
| 1257 |
+
share=False,
|
| 1258 |
+
debug=True,
|
| 1259 |
+
show_error=True
|
| 1260 |
+
)
|