Daniel251 commited on
Commit
8b258a3
·
verified ·
1 Parent(s): 8244457

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +338 -502
app.py CHANGED
@@ -1,233 +1,122 @@
1
  """
2
- 🎨 Object Replacer AI
3
- Substituição inteligente de objetos usando IA moderna
4
- Versão: 2.0.0 (AI-Powered)
5
  """
6
 
7
  import gradio as gr
8
- from PIL import Image, ImageDraw, ImageFilter
9
  import numpy as np
10
  import torch
11
- from transformers import pipeline, AutoModelForImageSegmentation, AutoProcessor
12
  from diffusers import StableDiffusionInpaintPipeline
 
13
  import tempfile
14
  import time
15
- import os
16
 
17
- print("=" * 60)
18
- print("🚀 INICIANDO OBJECT REPLACER AI")
19
- print("=" * 60)
20
 
21
  # Configurações
22
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
23
- MAX_IMAGE_SIZE = 1024
24
 
25
  print(f"💻 Dispositivo: {DEVICE}")
26
- print(f"📏 Tamanho máximo: {MAX_IMAGE_SIZE}px")
27
 
28
- # Modelos (lazy loading)
29
- segmentation_model = None
30
- inpainting_model = None
31
- object_detection_model = None
32
 
33
- def log_message(message):
34
- """Log com timestamp"""
35
- timestamp = time.strftime("%H:%M:%S")
36
- print(f"[{timestamp}] {message}")
37
 
38
- def load_segmentation_model():
39
- """Carrega modelo de segmentação"""
40
- global segmentation_model
41
- if segmentation_model is None:
42
- log_message("📦 Carregando modelo de segmentação...")
43
- try:
44
- # SAM (Segment Anything Model) ou alternativa
45
- segmentation_model = pipeline(
46
- "image-segmentation",
47
- model="facebook/detr-resnet-50-panoptic",
48
- device=0 if DEVICE == "cuda" else -1
49
- )
50
- log_message("✅ Modelo de segmentação carregado!")
51
- except Exception as e:
52
- log_message(f"⚠️ Erro ao carregar SAM, usando alternativa: {e}")
53
- segmentation_model = pipeline(
54
- "image-segmentation",
55
- model="nvidia/segformer-b0-finetuned-ade-512-512",
56
- device=0 if DEVICE == "cuda" else -1
57
- )
58
- return segmentation_model
59
-
60
- def load_inpainting_model():
61
  """Carrega modelo de inpainting"""
62
- global inpainting_model
63
- if inpainting_model is None:
64
- log_message("📦 Carregando modelo de inpainting...")
65
  try:
66
- inpainting_model = StableDiffusionInpaintPipeline.from_pretrained(
67
  "stabilityai/stable-diffusion-2-inpainting",
68
  torch_dtype=torch.float16 if DEVICE == "cuda" else torch.float32,
69
- safety_checker=None
 
70
  ).to(DEVICE)
71
 
72
  if DEVICE == "cuda":
73
- inpainting_model.enable_attention_slicing()
74
- inpainting_model.enable_vae_slicing()
75
 
76
- log_message("✅ Modelo de inpainting carregado!")
77
  except Exception as e:
78
- log_message(f"⚠️ Erro ao carregar SD Inpainting: {e}")
79
- # Fallback para modelo menor
80
- inpainting_model = StableDiffusionInpaintPipeline.from_pretrained(
81
  "runwayml/stable-diffusion-inpainting",
82
- torch_dtype=torch.float16 if DEVICE == "cuda" else torch.float32
 
83
  ).to(DEVICE)
84
- return inpainting_model
85
 
86
- def load_object_detection_model():
87
- """Carrega modelo de detecção de objetos"""
88
- global object_detection_model
89
- if object_detection_model is None:
90
- log_message("📦 Carregando modelo de detecção...")
91
- try:
92
- object_detection_model = pipeline(
93
- "object-detection",
94
- model="facebook/detr-resnet-50",
95
- device=0 if DEVICE == "cuda" else -1
96
- )
97
- log_message("✅ Modelo de detecção carregado!")
98
- except Exception as e:
99
- log_message(f"⚠️ Erro ao carregar DETR: {e}")
100
- return object_detection_model
101
-
102
- def resize_image(image, max_size=MAX_IMAGE_SIZE):
103
- """Redimensiona imagem mantendo aspect ratio"""
104
  if max(image.size) <= max_size:
105
  return image
106
-
107
  ratio = max_size / max(image.size)
108
  new_size = (int(image.width * ratio), int(image.height * ratio))
109
-
110
  return image.resize(new_size, Image.Resampling.LANCZOS)
111
 
112
- def detect_objects_in_image(image):
113
- """Detecta objetos automaticamente na imagem"""
114
- try:
115
- log_message("🔍 Detectando objetos...")
116
-
117
- model = load_object_detection_model()
118
-
119
- # Redimensionar para processamento
120
- img_resized = resize_image(image, 800)
121
-
122
- # Detectar objetos
123
- results = model(img_resized)
124
-
125
- # Processar resultados
126
- detected_objects = []
127
- for detection in results:
128
- if detection['score'] > 0.7: # Confiança mínima
129
- detected_objects.append({
130
- 'label': detection['label'],
131
- 'score': detection['score'],
132
- 'box': detection['box']
133
- })
134
-
135
- log_message(f"✅ {len(detected_objects)} objetos detectados")
136
- return detected_objects
137
-
138
- except Exception as e:
139
- log_message(f"❌ Erro na detecção: {e}")
140
- return []
141
-
142
- def create_mask_from_box(image_size, box, feather=20):
143
- """Cria máscara a partir de bounding box"""
144
  mask = Image.new('L', image_size, 0)
145
  draw = ImageDraw.Draw(mask)
146
 
147
- x1 = int(box['xmin'])
148
- y1 = int(box['ymin'])
149
- x2 = int(box['xmax'])
150
- y2 = int(box['ymax'])
151
-
152
- # Desenhar retângulo
153
- draw.rectangle([x1, y1, x2, y2], fill=255)
154
 
155
  # Suavizar bordas
156
- if feather > 0:
157
- mask = mask.filter(ImageFilter.GaussianBlur(radius=feather))
158
 
159
  return mask
160
 
161
- def smart_segmentation(image, point_x, point_y):
162
- """Segmentação inteligente baseada em ponto clicado"""
163
- try:
164
- log_message(f"🎯 Segmentando objeto em ({point_x}, {point_y})...")
165
-
166
- model = load_segmentation_model()
167
-
168
- # Segmentar imagem
169
- segments = model(image)
170
-
171
- # Encontrar segmento que contém o ponto clicado
172
- best_mask = None
173
- best_score = 0
174
-
175
- for segment in segments:
176
- mask = segment['mask']
177
- # Verificar se o ponto está dentro do segmento
178
- mask_array = np.array(mask)
179
- if point_y < mask_array.shape[0] and point_x < mask_array.shape[1]:
180
- if mask_array[point_y, point_x] > 128:
181
- score = segment.get('score', 0.5)
182
- if score > best_score:
183
- best_score = score
184
- best_mask = mask
185
-
186
- if best_mask is None:
187
- # Se não encontrou, criar máscara circular ao redor do ponto
188
- log_message("⚠️ Criando máscara padrão")
189
- best_mask = Image.new('L', image.size, 0)
190
- draw = ImageDraw.Draw(best_mask)
191
- radius = min(image.size) // 8
192
- draw.ellipse([point_x-radius, point_y-radius,
193
- point_x+radius, point_y+radius], fill=255)
194
- best_mask = best_mask.filter(ImageFilter.GaussianBlur(radius=10))
195
-
196
- log_message("✅ Segmentação concluída")
197
- return best_mask
198
-
199
- except Exception as e:
200
- log_message(f"❌ Erro na segmentação: {e}")
201
- # Máscara de fallback
202
- mask = Image.new('L', image.size, 0)
203
- draw = ImageDraw.Draw(mask)
204
- radius = min(image.size) // 8
205
- draw.ellipse([point_x-radius, point_y-radius,
206
- point_x+radius, point_y+radius], fill=255)
207
- return mask.filter(ImageFilter.GaussianBlur(radius=10))
208
 
209
- def inpaint_object(image, mask, prompt, negative_prompt="", steps=30, guidance=7.5):
210
- """Substitui objeto usando inpainting com IA"""
211
  try:
212
- log_message(f"🎨 Gerando novo objeto: '{prompt}'...")
213
 
214
- model = load_inpainting_model()
 
215
 
216
- # Redimensionar para múltiplo de 8 (requisito do SD)
217
- original_size = image.size
218
- new_width = (image.width // 8) * 8
219
- new_height = (image.height // 8) * 8
220
 
221
- img_resized = image.resize((new_width, new_height), Image.Resampling.LANCZOS)
222
- mask_resized = mask.resize((new_width, new_height), Image.Resampling.LANCZOS)
223
 
224
- # Inpainting
225
- start_time = time.time()
226
 
227
  with torch.no_grad():
228
- result = model(
229
  prompt=prompt,
230
- negative_prompt=negative_prompt or "ugly, blurry, low quality, distorted",
231
  image=img_resized,
232
  mask_image=mask_resized,
233
  num_inference_steps=steps,
@@ -235,385 +124,332 @@ def inpaint_object(image, mask, prompt, negative_prompt="", steps=30, guidance=7
235
  strength=0.99
236
  )
237
 
238
- output_image = result.images[0]
239
 
240
- # Redimensionar de volta ao tamanho original
241
- output_image = output_image.resize(original_size, Image.Resampling.LANCZOS)
242
 
243
- generation_time = time.time() - start_time
244
- log_message(f"✅ Objeto gerado em {generation_time:.1f}s")
245
 
246
- return output_image, generation_time
247
 
248
  except Exception as e:
249
- log_message(f"❌ Erro no inpainting: {e}")
250
- return None, 0
251
 
252
- def remove_object(image, mask):
253
  """Remove objeto preenchendo com contexto"""
254
  try:
255
- log_message("🗑️ Removendo objeto...")
256
-
257
- model = load_inpainting_model()
258
-
259
- # Prompt para remoção (sem adicionar nada)
260
- prompt = "smooth background, natural continuation, seamless"
261
- negative_prompt = "objects, people, animals, text, watermark"
262
-
263
- result, time_taken = inpaint_object(
264
- image, mask, prompt, negative_prompt,
265
- steps=40, guidance=7.0
266
- )
267
-
268
- return result
269
-
270
- except Exception as e:
271
- log_message(f"❌ Erro ao remover: {e}")
272
- return image
273
-
274
- def process_replacement(image, mask, action, replacement_prompt="", steps=30, guidance=7.5):
275
- """Processa a substituição ou remoção de objeto"""
276
- try:
277
- if image is None:
278
- return None, "❌ Nenhuma imagem fornecida"
279
-
280
- if mask is None:
281
- return None, "❌ Nenhuma máscara fornecida"
282
-
283
- # Validar e redimensionar
284
- image = resize_image(image, MAX_IMAGE_SIZE)
285
-
286
- if action == "replace":
287
- if not replacement_prompt or len(replacement_prompt.strip()) < 3:
288
- return None, "❌ Descrição do objeto muito curta"
289
-
290
- # Substituir objeto
291
- result, gen_time = inpaint_object(
292
- image, mask, replacement_prompt,
293
- steps=steps, guidance=guidance
294
- )
295
-
296
- if result is None:
297
- return None, "❌ Erro ao gerar novo objeto"
298
-
299
- status = f"✅ Objeto substituído com sucesso! (Tempo: {gen_time:.1f}s)"
300
- return result, status
301
-
302
- elif action == "remove":
303
- # Remover objeto
304
- result = remove_object(image, mask)
305
-
306
- if result is None:
307
- return None, "❌ Erro ao remover objeto"
308
-
309
- status = "✅ Objeto removido com sucesso!"
310
- return result, status
311
-
312
- else:
313
- return None, f"❌ Ação desconhecida: {action}"
314
-
315
- except Exception as e:
316
- error_msg = f"❌ Erro no processamento: {str(e)}"
317
- log_message(error_msg)
318
- return None, error_msg
319
-
320
- def auto_detect_and_visualize(image):
321
- """Detecta objetos e desenha bounding boxes"""
322
- try:
323
- if image is None:
324
- return None
325
-
326
- objects = detect_objects_in_image(image)
327
 
328
- if not objects:
329
- return image
 
330
 
331
- # Desenhar detecções
332
- img_with_boxes = image.copy()
333
- draw = ImageDraw.Draw(img_with_boxes)
334
-
335
- for obj in objects:
336
- box = obj['box']
337
- label = obj['label']
338
- score = obj['score']
339
-
340
- # Desenhar caixa
341
- x1, y1 = int(box['xmin']), int(box['ymin'])
342
- x2, y2 = int(box['xmax']), int(box['ymax'])
343
-
344
- draw.rectangle([x1, y1, x2, y2], outline=(0, 255, 0), width=3)
345
-
346
- # Desenhar label
347
- text = f"{label} ({score:.2f})"
348
- draw.text((x1, y1-20), text, fill=(0, 255, 0))
349
 
350
- return img_with_boxes
 
 
351
 
352
  except Exception as e:
353
- log_message(f"Erro na visualização: {e}")
354
- return image
355
 
356
  # Interface Gradio
357
  with gr.Blocks(title="🎨 Object Replacer AI", theme=gr.themes.Soft()) as demo:
358
 
359
  gr.HTML("""
360
- <div style="text-align: center; padding: 30px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
361
- border-radius: 15px; color: white; margin-bottom: 30px;">
362
- <h1 style="margin: 0; font-size: 2.5em;">🎨 Object Replacer AI</h1>
363
- <p style="margin: 10px 0; font-size: 1.2em;">Substituição inteligente de objetos com Inteligência Artificial</p>
364
- <small style="opacity: 0.9;">Powered by Stable Diffusion Inpainting + DETR Detection</small>
365
  </div>
366
  """)
367
 
368
- with gr.Tabs():
369
- # Tab 1: Manual
370
- with gr.Tab("🖱️ Modo Manual"):
371
- gr.Markdown("""
372
- ### Como usar:
373
- 1. Faça upload da imagem
374
- 2. Clique na imagem para selecionar o objeto
375
- 3. Escolha: Substituir (descreva o novo objeto) ou Remover
376
- 4. Ajuste configurações avançadas se necessário
377
- 5. Clique em Processar
378
- """)
379
-
380
- with gr.Row():
381
- with gr.Column(scale=1):
382
- gr.Markdown("### 📤 Imagem Original")
383
- input_image = gr.Image(
384
- label="",
385
- type="pil",
386
- interactive=True,
387
- height=400
388
- )
389
-
390
- gr.Markdown("### 🎯 Configurações")
391
- action_radio = gr.Radio(
392
- choices=["replace", "remove"],
393
- value="replace",
394
- label="Ação",
395
- info="Substituir ou remover objeto?"
396
- )
397
-
398
- replacement_prompt = gr.Textbox(
399
- label="Descrição do Novo Objeto",
400
- placeholder="Ex: a red sports car, a beautiful flower, a modern building...",
401
- lines=3,
402
- visible=True
403
- )
404
-
405
- with gr.Accordion("⚙️ Configurações Avançadas", open=False):
406
- steps_slider = gr.Slider(
407
- 10, 50, 30, step=5,
408
- label="Steps (Qualidade)",
409
- info="Mais steps = melhor qualidade"
410
- )
411
-
412
- guidance_slider = gr.Slider(
413
- 1.0, 20.0, 7.5, step=0.5,
414
- label="Guidance Scale",
415
- info="Quanto seguir o prompt"
416
- )
417
-
418
- process_btn = gr.Button(
419
- "✨ Processar Imagem",
420
- variant="primary",
421
- size="lg"
422
- )
423
-
424
- with gr.Column(scale=1):
425
- gr.Markdown("### 🖼️ Resultado")
426
- output_image = gr.Image(
427
- label="",
428
- type="pil",
429
- height=400
430
- )
431
-
432
- status_text = gr.Markdown("**Status:** Aguardando imagem...")
433
-
434
- with gr.Row():
435
- download_btn = gr.Button("📥 Baixar", size="lg")
436
- clear_btn = gr.Button("🔄 Limpar", variant="secondary", size="lg")
437
-
438
- download_file = gr.File(label="Download")
439
-
440
- # Estado para armazenar ponto clicado e máscara
441
- click_point = gr.State(None)
442
- mask_state = gr.State(None)
443
-
444
- # Detectar clique na imagem
445
- def handle_click(image, evt: gr.SelectData):
446
- if image is None:
447
- return None, None, "❌ Carregue uma imagem primeiro"
448
-
449
- x, y = evt.index[0], evt.index[1]
450
- log_message(f"Clique detectado em: ({x}, {y})")
451
-
452
- # Criar máscara baseada no clique
453
- mask = smart_segmentation(image, x, y)
454
-
455
- # Visualizar máscara na imagem
456
- img_with_mask = image.copy().convert('RGBA')
457
- mask_colored = Image.new('RGBA', image.size, (255, 0, 0, 100))
458
- img_with_mask.paste(mask_colored, (0, 0), mask)
459
-
460
- return (x, y), mask, "✅ Objeto selecionado! Configure e clique em Processar"
461
-
462
- input_image.select(
463
- fn=handle_click,
464
- inputs=[input_image],
465
- outputs=[click_point, mask_state, status_text]
466
  )
467
 
468
- # Mostrar/esconder prompt baseado na ação
469
- def toggle_prompt(action):
470
- return gr.update(visible=(action == "replace"))
471
 
472
- action_radio.change(
473
- fn=toggle_prompt,
474
- inputs=[action_radio],
475
- outputs=[replacement_prompt]
 
476
  )
477
 
478
- # Processar
479
- def process_manual(image, mask, action, prompt, steps, guidance):
480
- if mask is None:
481
- return None, "❌ Clique na imagem para selecionar um objeto primeiro"
482
-
483
- return process_replacement(image, mask, action, prompt, steps, guidance)
484
-
485
- process_btn.click(
486
- fn=process_manual,
487
- inputs=[input_image, mask_state, action_radio, replacement_prompt,
488
- steps_slider, guidance_slider],
489
- outputs=[output_image, status_text]
490
  )
491
 
492
- # Download
493
- def save_output(image):
494
- if image is None:
495
- return None
496
- temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
497
- image.save(temp_file.name, "PNG")
498
- return temp_file.name
499
 
500
- download_btn.click(
501
- fn=save_output,
502
- inputs=[output_image],
503
- outputs=[download_file]
 
 
 
 
504
  )
505
 
506
- # Limpar
507
- clear_btn.click(
508
- fn=lambda: (None, None, None, None, "Tudo limpo!"),
509
- outputs=[input_image, output_image, click_point, mask_state, status_text]
 
510
  )
511
-
512
- # Tab 2: Auto-Detect
513
- with gr.Tab("🤖 Detecção Automática"):
514
- gr.Markdown("""
515
- ### Detecção automática de objetos:
516
- 1. Faça upload da imagem
517
- 2. Clique em "Detectar Objetos"
518
- 3. Os objetos serão destacados automaticamente
519
- 4. Selecione o objeto desejado e processe
520
- """)
521
 
522
- with gr.Row():
523
- with gr.Column():
524
- auto_input = gr.Image(label="Imagem Original", type="pil")
525
- detect_btn = gr.Button("🔍 Detectar Objetos", variant="primary")
526
-
527
- with gr.Column():
528
- auto_output = gr.Image(label="Objetos Detectados", type="pil")
529
- detected_list = gr.Textbox(
530
- label="Objetos Encontrados",
531
- interactive=False,
532
- lines=5
533
- )
534
 
535
- def detect_and_show(image):
536
- if image is None:
537
- return None, "Nenhuma imagem fornecida"
538
-
539
- objects = detect_objects_in_image(image)
540
- img_viz = auto_detect_and_visualize(image)
541
 
542
- if objects:
543
- obj_list = "\n".join([
544
- f"• {obj['label']} (confiança: {obj['score']:.2%})"
545
- for obj in objects
546
- ])
547
- return img_viz, f"Encontrados {len(objects)} objetos:\n\n{obj_list}"
548
- else:
549
- return img_viz, "Nenhum objeto detectado com alta confiança"
 
 
 
550
 
551
- detect_btn.click(
552
- fn=detect_and_show,
553
- inputs=[auto_input],
554
- outputs=[auto_output, detected_list]
 
555
  )
556
-
557
- # Tab 3: Exemplos e Dicas
558
- with gr.Tab("📚 Exemplos & Dicas"):
559
- gr.Markdown("""
560
- ## 🎯 Dicas para Melhores Resultados:
561
 
562
- ### ✨ Prompts Efetivos para Substituição:
563
 
564
- **Para objetos concretos:**
565
- - "a red sports car, photorealistic, high detail"
566
- - "a beautiful rose flower, vibrant colors, professional photo"
567
- - "a modern glass building, architectural photography"
568
- - "a fluffy golden retriever dog, cute, high quality"
569
 
570
- **Para modificações artísticas:**
571
- - "a magical glowing crystal, fantasy art, ethereal"
572
- - "a steampunk robot, intricate details, bronze and copper"
573
- - "a neon sign, cyberpunk style, glowing lights"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
574
 
575
- **Palavras-chave importantes:**
576
- - Qualidade: "photorealistic", "high detail", "4k", "professional"
577
- - Estilo: "realistic", "artistic", "fantasy", "modern", "vintage"
578
- - Iluminação: "well-lit", "golden hour", "studio lighting"
579
 
580
- ### 🎨 Configurações Recomendadas:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
581
 
582
- | Tipo de Tarefa | Steps | Guidance Scale |
583
- |----------------|-------|----------------|
584
- | Substituição simples | 20-30 | 7-8 |
585
- | Substituição complexa | 40-50 | 7.5-9 |
586
- | Remoção de objeto | 30-40 | 6-7 |
587
- | Resultado artístico | 30-40 | 9-12 |
588
 
589
- ### ⚠️ Limitações:
 
 
590
 
591
- - Primeira execução é lenta (carregando modelos)
592
- - GPU recomendada para velocidade
593
- - Objetos muito pequenos ou parcialmente visíveis podem não ser bem detectados
594
- - Máscaras precisas melhoram resultados
 
 
 
 
595
 
596
- ### 💡 Técnicas Avançadas:
597
 
598
- 1. **Para remoções limpas**: Use "smooth background, natural continuation"
599
- 2. **Para manter estilo**: Inclua o estilo da imagem no prompt
600
- 3. **Para objetos realistas**: Adicione detalhes de iluminação e perspectiva
601
- 4. **Para integração**: Use guidance scale mais baixo (6-7)
602
- """)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
603
 
604
  gr.HTML("""
605
- <div style="text-align: center; margin-top: 30px; padding: 20px; color: #666;">
606
- <p><strong>✨ Object Replacer AI ✨</strong></p>
607
- <p>Tecnologia de ponta em substituição e remoção de objetos</p>
608
- <p style="font-size: 0.9em; margin-top: 10px;">
609
- 🤖 DETR Object Detection • 🎨 Stable Diffusion Inpainting • 🔍 Segmentação Inteligente
 
 
 
610
  </p>
611
  </div>
612
  """)
613
 
614
  if __name__ == "__main__":
615
- log_message(f"✅ Sistema iniciado! Dispositivo: {DEVICE}")
616
- log_message("⚡ Modelos serão carregados sob demanda")
617
 
618
  demo.launch(
619
  server_name="0.0.0.0",
 
1
  """
2
+ 🎨 Object Replacer AI - Versão Funcional
3
+ Substituição inteligente de objetos usando IA
 
4
  """
5
 
6
  import gradio as gr
7
+ from PIL import Image, ImageDraw, ImageFilter, ImageFont
8
  import numpy as np
9
  import torch
 
10
  from diffusers import StableDiffusionInpaintPipeline
11
+ import cv2
12
  import tempfile
13
  import time
 
14
 
15
+ print("🚀 Iniciando Object Replacer AI...")
 
 
16
 
17
  # Configurações
18
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
19
+ MAX_SIZE = 768
20
 
21
  print(f"💻 Dispositivo: {DEVICE}")
 
22
 
23
+ # Modelo global
24
+ inpaint_pipe = None
 
 
25
 
26
+ def log_msg(msg):
27
+ print(f"[{time.strftime('%H:%M:%S')}] {msg}")
 
 
28
 
29
+ def load_inpaint_model():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  """Carrega modelo de inpainting"""
31
+ global inpaint_pipe
32
+ if inpaint_pipe is None:
33
+ log_msg("📦 Carregando Stable Diffusion Inpainting...")
34
  try:
35
+ inpaint_pipe = StableDiffusionInpaintPipeline.from_pretrained(
36
  "stabilityai/stable-diffusion-2-inpainting",
37
  torch_dtype=torch.float16 if DEVICE == "cuda" else torch.float32,
38
+ safety_checker=None,
39
+ requires_safety_checker=False
40
  ).to(DEVICE)
41
 
42
  if DEVICE == "cuda":
43
+ inpaint_pipe.enable_attention_slicing()
44
+ inpaint_pipe.enable_vae_slicing()
45
 
46
+ log_msg("✅ Modelo carregado!")
47
  except Exception as e:
48
+ log_msg(f"⚠️ Erro: {e}, tentando modelo alternativo...")
49
+ inpaint_pipe = StableDiffusionInpaintPipeline.from_pretrained(
 
50
  "runwayml/stable-diffusion-inpainting",
51
+ torch_dtype=torch.float16 if DEVICE == "cuda" else torch.float32,
52
+ safety_checker=None
53
  ).to(DEVICE)
54
+ return inpaint_pipe
55
 
56
+ def resize_image(image, max_size=MAX_SIZE):
57
+ """Redimensiona mantendo proporção"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  if max(image.size) <= max_size:
59
  return image
 
60
  ratio = max_size / max(image.size)
61
  new_size = (int(image.width * ratio), int(image.height * ratio))
 
62
  return image.resize(new_size, Image.Resampling.LANCZOS)
63
 
64
+ def create_circular_mask(image_size, center_x, center_y, radius):
65
+ """Cria máscara circular ao redor do ponto clicado"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  mask = Image.new('L', image_size, 0)
67
  draw = ImageDraw.Draw(mask)
68
 
69
+ # Desenhar círculo
70
+ draw.ellipse(
71
+ [center_x - radius, center_y - radius,
72
+ center_x + radius, center_y + radius],
73
+ fill=255
74
+ )
 
75
 
76
  # Suavizar bordas
77
+ mask = mask.filter(ImageFilter.GaussianBlur(radius=15))
 
78
 
79
  return mask
80
 
81
+ def create_mask_from_brush(image_size, brush_strokes):
82
+ """Cria máscara a partir de traços de pincel"""
83
+ mask = Image.new('L', image_size, 0)
84
+ draw = ImageDraw.Draw(mask)
85
+
86
+ if brush_strokes and len(brush_strokes) > 0:
87
+ for stroke in brush_strokes:
88
+ if len(stroke) >= 2:
89
+ # Desenhar linha grossa
90
+ draw.line(stroke, fill=255, width=30)
91
+
92
+ # Suavizar
93
+ mask = mask.filter(ImageFilter.GaussianBlur(radius=10))
94
+
95
+ return mask
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
+ def smart_inpaint(image, mask, prompt, negative_prompt, steps, guidance):
98
+ """Substitui objeto usando inpainting"""
99
  try:
100
+ log_msg(f"🎨 Gerando: '{prompt}'")
101
 
102
+ # Carregar modelo
103
+ pipe = load_inpaint_model()
104
 
105
+ # Ajustar tamanho para múltiplo de 8
106
+ w, h = image.size
107
+ new_w = (w // 8) * 8
108
+ new_h = (h // 8) * 8
109
 
110
+ img_resized = image.resize((new_w, new_h), Image.Resampling.LANCZOS)
111
+ mask_resized = mask.resize((new_w, new_h), Image.Resampling.LANCZOS)
112
 
113
+ # Gerar
114
+ start = time.time()
115
 
116
  with torch.no_grad():
117
+ result = pipe(
118
  prompt=prompt,
119
+ negative_prompt=negative_prompt,
120
  image=img_resized,
121
  mask_image=mask_resized,
122
  num_inference_steps=steps,
 
124
  strength=0.99
125
  )
126
 
127
+ output = result.images[0]
128
 
129
+ # Voltar ao tamanho original
130
+ output = output.resize((w, h), Image.Resampling.LANCZOS)
131
 
132
+ elapsed = time.time() - start
133
+ log_msg(f"✅ Concluído em {elapsed:.1f}s")
134
 
135
+ return output, f"✅ Objeto gerado em {elapsed:.1f}s!"
136
 
137
  except Exception as e:
138
+ log_msg(f"❌ Erro: {e}")
139
+ return None, f"❌ Erro: {str(e)}"
140
 
141
+ def remove_object_smart(image, mask):
142
  """Remove objeto preenchendo com contexto"""
143
  try:
144
+ log_msg("🗑️ Removendo objeto...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
 
146
+ # Usar inpainting com prompt genérico
147
+ prompt = "smooth background, natural surface, seamless, no objects"
148
+ negative_prompt = "object, item, text, watermark, person, animal"
149
 
150
+ result, msg = smart_inpaint(image, mask, prompt, negative_prompt, 40, 7.0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
 
152
+ if result:
153
+ return result, "✅ Objeto removido!"
154
+ return None, msg
155
 
156
  except Exception as e:
157
+ return None, f"❌ Erro ao remover: {str(e)}"
 
158
 
159
  # Interface Gradio
160
  with gr.Blocks(title="🎨 Object Replacer AI", theme=gr.themes.Soft()) as demo:
161
 
162
  gr.HTML("""
163
+ <div style="text-align: center; padding: 25px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
164
+ border-radius: 12px; color: white; margin-bottom: 25px; box-shadow: 0 4px 15px rgba(0,0,0,0.2);">
165
+ <h1 style="margin: 0; font-size: 2.5em; font-weight: 700;">✨ Object Replacer AI</h1>
166
+ <p style="margin: 10px 0; font-size: 1.1em; opacity: 0.95;">Substitua ou remova objetos com Inteligência Artificial</p>
167
+ <small style="opacity: 0.85;">Powered by Stable Diffusion Inpainting</small>
168
  </div>
169
  """)
170
 
171
+ # Estado para armazenar dados
172
+ mask_state = gr.State(None)
173
+ original_image_state = gr.State(None)
174
+
175
+ with gr.Row():
176
+ with gr.Column(scale=1):
177
+ gr.Markdown("### 📤 1. Carregue sua Imagem")
178
+ input_image = gr.Image(
179
+ label="",
180
+ type="pil",
181
+ interactive=True,
182
+ height=350
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
183
  )
184
 
185
+ gr.Markdown("### 🖌️ 2. Marque o Objeto")
186
+ gr.Markdown("**Use o pincel para pintar sobre o objeto que deseja substituir/remover**")
 
187
 
188
+ brush_image = gr.ImageMask(
189
+ label="Pinte sobre o objeto",
190
+ type="pil",
191
+ brush_radius=20,
192
+ height=350
193
  )
194
 
195
+ brush_size = gr.Slider(
196
+ 10, 50, 20, step=5,
197
+ label="Tamanho do Pincel",
198
+ info="Ajuste o tamanho do pincel"
 
 
 
 
 
 
 
 
199
  )
200
 
201
+ clear_mask_btn = gr.Button("🔄 Limpar Máscara", size="sm")
202
+
203
+ with gr.Column(scale=1):
204
+ gr.Markdown("### ⚙️ 3. Configure a Ação")
 
 
 
205
 
206
+ action_radio = gr.Radio(
207
+ choices=[
208
+ ("🔄 Substituir por novo objeto", "replace"),
209
+ ("🗑️ Remover objeto", "remove")
210
+ ],
211
+ value="replace",
212
+ label="O que fazer?",
213
+ interactive=True
214
  )
215
 
216
+ replacement_prompt = gr.Textbox(
217
+ label="📝 Descreva o novo objeto (em inglês para melhor resultado)",
218
+ placeholder="Ex: a red sports car / a beautiful flower / a modern laptop",
219
+ lines=3,
220
+ value="a beautiful red rose flower, photorealistic, high quality"
221
  )
 
 
 
 
 
 
 
 
 
 
222
 
223
+ negative_prompt = gr.Textbox(
224
+ label="🚫 O que evitar (opcional)",
225
+ placeholder="Ex: ugly, blurry, low quality",
226
+ value="ugly, blurry, low quality, distorted, deformed",
227
+ lines=2
228
+ )
 
 
 
 
 
 
229
 
230
+ with gr.Accordion("🎛️ Configurações Avançadas", open=False):
231
+ steps_slider = gr.Slider(
232
+ 10, 50, 25, step=5,
233
+ label="Steps (Qualidade)",
234
+ info="Mais steps = melhor qualidade (mas mais lento)"
235
+ )
236
 
237
+ guidance_slider = gr.Slider(
238
+ 1.0, 15.0, 7.5, step=0.5,
239
+ label="Guidance Scale",
240
+ info="7-9 recomendado. Maior = segue mais o prompt"
241
+ )
242
+
243
+ process_btn = gr.Button(
244
+ "✨ PROCESSAR IMAGEM",
245
+ variant="primary",
246
+ size="lg"
247
+ )
248
 
249
+ gr.Markdown("### 🖼️ 4. Resultado")
250
+ output_image = gr.Image(
251
+ label="",
252
+ type="pil",
253
+ height=350
254
  )
 
 
 
 
 
255
 
256
+ status_output = gr.Markdown("**Status:** Aguardando imagem...")
257
 
258
+ with gr.Row():
259
+ download_btn = gr.Button("📥 Baixar Resultado", size="lg")
260
+ reset_btn = gr.Button("🔄 Resetar Tudo", variant="secondary", size="lg")
 
 
261
 
262
+ download_file = gr.File(label="Download", visible=False)
263
+
264
+ # Exemplos
265
+ with gr.Accordion("💡 Exemplos de Prompts", open=False):
266
+ gr.Markdown("""
267
+ ### 🎯 Exemplos de prompts efetivos:
268
+
269
+ **Para objetos realistas:**
270
+ - `a red sports car, photorealistic, detailed, 4k`
271
+ - `a beautiful yellow sunflower, vibrant colors, professional photo`
272
+ - `a modern silver laptop, sleek design, high quality`
273
+ - `a cute golden retriever puppy, fluffy, professional portrait`
274
+
275
+ **Para estilo artístico:**
276
+ - `a magical glowing crystal, fantasy art, ethereal lighting`
277
+ - `a steampunk mechanical device, intricate gears, brass and copper`
278
+ - `a neon cyberpunk sign, glowing letters, futuristic`
279
+
280
+ **Dicas:**
281
+ - ✅ Use inglês para melhores resultados
282
+ - ✅ Seja específico: cores, estilo, qualidade
283
+ - ✅ Adicione: "photorealistic, high quality, detailed"
284
+ - ✅ Para remoção: deixe em branco ou use "smooth background"
285
+ """)
286
+
287
+ # Guia de uso
288
+ gr.Markdown("""
289
+ ---
290
+ ### 📖 Como usar:
291
+
292
+ 1. **Carregue a imagem** - Clique ou arraste para a área de upload
293
+ 2. **Marque o objeto** - Use o pincel para pintar sobre o que quer substituir/remover
294
+ 3. **Escolha a ação**:
295
+ - **Substituir**: Descreva o novo objeto em inglês
296
+ - **Remover**: O objeto será removido e preenchido inteligentemente
297
+ 4. **Ajuste configurações** (opcional) - Steps e Guidance Scale
298
+ 5. **Clique em Processar** - Aguarde a IA gerar o resultado
299
+ 6. **Baixe o resultado** - Se gostar, clique em Baixar
300
+
301
+ **⚠️ Importante:**
302
+ - Primeira execução pode demorar (carregando modelo ~2GB)
303
+ - Marque bem a área do objeto com o pincel
304
+ - Use prompts em inglês para melhor qualidade
305
+ - GPU acelera significativamente o processo
306
+ """)
307
+
308
+ # Funções de callback
309
+
310
+ def update_brush_image(image):
311
+ """Atualiza a imagem no brush quando nova imagem é carregada"""
312
+ if image is None:
313
+ return None, None, "❌ Carregue uma imagem primeiro"
314
+
315
+ img = resize_image(image, MAX_SIZE)
316
+ return img, img, "✅ Imagem carregada! Use o pincel para marcar o objeto"
317
+
318
+ input_image.change(
319
+ fn=update_brush_image,
320
+ inputs=[input_image],
321
+ outputs=[brush_image, original_image_state, status_output]
322
+ )
323
+
324
+ def toggle_prompt_visibility(action):
325
+ """Mostra/esconde prompt baseado na ação"""
326
+ return gr.update(visible=(action == "replace"))
327
+
328
+ action_radio.change(
329
+ fn=toggle_prompt_visibility,
330
+ inputs=[action_radio],
331
+ outputs=[replacement_prompt]
332
+ )
333
+
334
+ def process_image(original_img, brush_data, action, prompt, neg_prompt, steps, guidance):
335
+ """Processa a imagem com inpainting"""
336
+ try:
337
+ if original_img is None:
338
+ return None, "❌ Carregue uma imagem primeiro!"
339
 
340
+ if brush_data is None:
341
+ return None, "❌ Marque o objeto com o pincel!"
 
 
342
 
343
+ # Extrair imagem e máscara do brush
344
+ if isinstance(brush_data, dict):
345
+ if 'background' in brush_data:
346
+ img = brush_data['background']
347
+ else:
348
+ img = brush_data.get('image', original_img)
349
+
350
+ # Máscara das áreas pintadas
351
+ if 'layers' in brush_data and brush_data['layers']:
352
+ # Criar máscara a partir das camadas
353
+ mask = Image.new('L', img.size, 0)
354
+ for layer in brush_data['layers']:
355
+ if isinstance(layer, np.ndarray):
356
+ layer_mask = Image.fromarray(layer).convert('L')
357
+ mask = Image.composite(
358
+ Image.new('L', img.size, 255),
359
+ mask,
360
+ layer_mask
361
+ )
362
+ else:
363
+ return None, "❌ Pinte sobre o objeto que deseja modificar!"
364
+ else:
365
+ img = original_img
366
+ mask = Image.new('L', img.size, 255)
367
 
368
+ # Verificar se a máscara não está vazia
369
+ mask_array = np.array(mask)
370
+ if mask_array.max() == 0:
371
+ return None, "❌ Marque o objeto com o pincel primeiro!"
 
 
372
 
373
+ # Redimensionar
374
+ img = resize_image(img, MAX_SIZE)
375
+ mask = mask.resize(img.size, Image.Resampling.LANCZOS)
376
 
377
+ # Processar baseado na ação
378
+ if action == "replace":
379
+ if not prompt or len(prompt.strip()) < 3:
380
+ return None, "❌ Descreva o novo objeto!"
381
+
382
+ result, status = smart_inpaint(img, mask, prompt, neg_prompt, steps, guidance)
383
+ else: # remove
384
+ result, status = remove_object_smart(img, mask)
385
 
386
+ return result, status
387
 
388
+ except Exception as e:
389
+ error = f"❌ Erro: {str(e)}"
390
+ log_msg(error)
391
+ return None, error
392
+
393
+ process_btn.click(
394
+ fn=process_image,
395
+ inputs=[original_image_state, brush_image, action_radio,
396
+ replacement_prompt, negative_prompt, steps_slider, guidance_slider],
397
+ outputs=[output_image, status_output]
398
+ )
399
+
400
+ def save_result(image):
401
+ """Salva resultado"""
402
+ if image is None:
403
+ return None
404
+
405
+ temp = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
406
+ image.save(temp.name, "PNG", optimize=True)
407
+ return temp.name
408
+
409
+ download_btn.click(
410
+ fn=save_result,
411
+ inputs=[output_image],
412
+ outputs=[download_file]
413
+ )
414
+
415
+ def reset_all():
416
+ """Reseta tudo"""
417
+ return None, None, None, None, None, "🔄 Tudo resetado! Comece novamente"
418
+
419
+ reset_btn.click(
420
+ fn=reset_all,
421
+ outputs=[input_image, brush_image, output_image, mask_state,
422
+ original_image_state, status_output]
423
+ )
424
+
425
+ def clear_mask(img):
426
+ """Limpa apenas a máscara"""
427
+ if img:
428
+ return img
429
+ return None
430
+
431
+ clear_mask_btn.click(
432
+ fn=clear_mask,
433
+ inputs=[original_image_state],
434
+ outputs=[brush_image]
435
+ )
436
 
437
  gr.HTML("""
438
+ <div style="text-align: center; margin-top: 30px; padding: 20px; color: #666;
439
+ border-top: 1px solid #e0e0e0;">
440
+ <p style="margin: 5px 0;"><strong>✨ Object Replacer AI ✨</strong></p>
441
+ <p style="font-size: 0.9em; margin: 5px 0;">
442
+ 🎨 Stable Diffusion Inpainting • 🖌️ Interface Intuitiva • ⚡ Resultados Profissionais
443
+ </p>
444
+ <p style="font-size: 0.8em; color: #999; margin-top: 10px;">
445
+ Dica: Para melhores resultados, marque bem o objeto e use prompts descritivos em inglês
446
  </p>
447
  </div>
448
  """)
449
 
450
  if __name__ == "__main__":
451
+ log_msg(f"✅ Sistema pronto! Dispositivo: {DEVICE}")
452
+ log_msg("⚡ Modelo será carregado na primeira geração")
453
 
454
  demo.launch(
455
  server_name="0.0.0.0",