Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -9,6 +9,8 @@ from PIL import Image
|
|
| 9 |
import numpy as np
|
| 10 |
import sys
|
| 11 |
import os
|
|
|
|
|
|
|
| 12 |
|
| 13 |
print("=" * 60)
|
| 14 |
print("🚀 INICIANDO APP 3: BACKGROUND REMOVER")
|
|
@@ -30,7 +32,7 @@ except ImportError:
|
|
| 30 |
def remove_background(image):
|
| 31 |
"""Remove o fundo da imagem"""
|
| 32 |
if image is None:
|
| 33 |
-
return None, "❌ Por favor, envie uma imagem primeiro"
|
| 34 |
|
| 35 |
try:
|
| 36 |
# Converte para PIL se necessário
|
|
@@ -52,12 +54,15 @@ def remove_background(image):
|
|
| 52 |
output = create_simple_transparency(image)
|
| 53 |
print("⚠️ Usando método fallback")
|
| 54 |
|
| 55 |
-
|
|
|
|
|
|
|
|
|
|
| 56 |
|
| 57 |
except Exception as e:
|
| 58 |
error_msg = f"❌ Erro ao remover fundo: {str(e)}"
|
| 59 |
print(error_msg)
|
| 60 |
-
return None, error_msg
|
| 61 |
|
| 62 |
def create_simple_transparency(image):
|
| 63 |
"""Método fallback para criar transparência"""
|
|
@@ -85,10 +90,25 @@ def create_simple_transparency(image):
|
|
| 85 |
result = Image.fromarray(np.dstack([img_array, alpha]))
|
| 86 |
return result
|
| 87 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
def add_solid_background(image, bg_color):
|
| 89 |
"""Adiciona fundo sólido colorido"""
|
| 90 |
if image is None:
|
| 91 |
-
return None, "❌ Remova o fundo primeiro"
|
| 92 |
|
| 93 |
try:
|
| 94 |
# Converte hex para RGB
|
|
@@ -103,15 +123,18 @@ def add_solid_background(image, bg_color):
|
|
| 103 |
else:
|
| 104 |
background.paste(image, (0, 0))
|
| 105 |
|
| 106 |
-
|
|
|
|
|
|
|
|
|
|
| 107 |
|
| 108 |
except Exception as e:
|
| 109 |
-
return None, f"❌ Erro: {str(e)}"
|
| 110 |
|
| 111 |
def add_gradient_background(image, color1, color2):
|
| 112 |
"""Adiciona fundo com gradiente"""
|
| 113 |
if image is None:
|
| 114 |
-
return None, "❌ Remova o fundo primeiro"
|
| 115 |
|
| 116 |
try:
|
| 117 |
# Converte cores
|
|
@@ -134,15 +157,18 @@ def add_gradient_background(image, color1, color2):
|
|
| 134 |
else:
|
| 135 |
background.paste(image, (0, 0))
|
| 136 |
|
| 137 |
-
|
|
|
|
|
|
|
|
|
|
| 138 |
|
| 139 |
except Exception as e:
|
| 140 |
-
return None, f"❌ Erro: {str(e)}"
|
| 141 |
|
| 142 |
def add_blur_background(image, blur_strength):
|
| 143 |
"""Adiciona fundo desfocado da própria imagem"""
|
| 144 |
if image is None:
|
| 145 |
-
return None, "❌ Remova o fundo primeiro"
|
| 146 |
|
| 147 |
try:
|
| 148 |
from PIL import ImageFilter
|
|
@@ -158,16 +184,19 @@ def add_blur_background(image, blur_strength):
|
|
| 158 |
if image.mode == 'RGBA':
|
| 159 |
blurred.paste(image, (0, 0), image)
|
| 160 |
|
| 161 |
-
|
|
|
|
|
|
|
|
|
|
| 162 |
|
| 163 |
except Exception as e:
|
| 164 |
-
return None, f"❌ Erro: {str(e)}"
|
| 165 |
|
| 166 |
# ========== INTERFACE GRADIO ==========
|
| 167 |
|
| 168 |
print("🎨 Criando interface Background Remover...")
|
| 169 |
|
| 170 |
-
with gr.Blocks(title="🎨 Background Remover - Photoshop AI App 3") as demo:
|
| 171 |
gr.Markdown("""
|
| 172 |
# 🎨 Background Remover
|
| 173 |
### Remove fundos de imagens automaticamente usando IA
|
|
@@ -176,7 +205,7 @@ with gr.Blocks(title="🎨 Background Remover - Photoshop AI App 3") as demo:
|
|
| 176 |
1. 📸 Faça upload de uma imagem
|
| 177 |
2. ✂️ Clique em "Remover Fundo"
|
| 178 |
3. 🎨 Adicione um novo fundo (opcional)
|
| 179 |
-
4. 💾 Baixe o resultado
|
| 180 |
""")
|
| 181 |
|
| 182 |
with gr.Row():
|
|
@@ -206,25 +235,20 @@ with gr.Blocks(title="🎨 Background Remover - Photoshop AI App 3") as demo:
|
|
| 206 |
output_image = gr.Image(label="✨ Resultado", type="pil")
|
| 207 |
status_text = gr.Textbox(label="📊 Status", interactive=False)
|
| 208 |
|
| 209 |
-
#
|
| 210 |
-
|
| 211 |
-
download_btn = gr.DownloadButton(
|
| 212 |
-
label="💾 Baixar Imagem Processada",
|
| 213 |
-
variant="primary",
|
| 214 |
-
size="lg",
|
| 215 |
-
visible=False
|
| 216 |
-
)
|
| 217 |
|
| 218 |
# Exemplos
|
| 219 |
gr.Markdown("### 📋 Exemplos")
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
|
|
|
| 228 |
|
| 229 |
# Informações
|
| 230 |
gr.Markdown("""
|
|
@@ -233,85 +257,42 @@ with gr.Blocks(title="🎨 Background Remover - Photoshop AI App 3") as demo:
|
|
| 233 |
- ✅ Processamento automático com IA
|
| 234 |
- ✅ Exporta PNG com transparência
|
| 235 |
- ✅ Adicione fundos personalizados
|
| 236 |
-
- ✅ Download direto da imagem
|
| 237 |
|
| 238 |
### 💡 Dicas
|
| 239 |
- Use imagens com boa iluminação para melhores resultados
|
| 240 |
- Fundos uniformes são mais fáceis de remover
|
| 241 |
- O PNG mantém a transparência
|
| 242 |
- Experimente diferentes fundos para ver o que fica melhor
|
|
|
|
| 243 |
|
| 244 |
---
|
| 245 |
**🔗 Parte do Photoshop AI Ecosystem** | App 3 de 10
|
| 246 |
""")
|
| 247 |
|
| 248 |
-
#
|
| 249 |
-
def prepare_download(image):
|
| 250 |
-
"""Prepara imagem para download e mostra botão"""
|
| 251 |
-
if image is None:
|
| 252 |
-
return gr.DownloadButton(visible=False), None
|
| 253 |
-
|
| 254 |
-
# Salva temporariamente
|
| 255 |
-
import tempfile
|
| 256 |
-
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
|
| 257 |
-
image.save(temp_file.name, format="PNG")
|
| 258 |
-
|
| 259 |
-
return gr.DownloadButton(
|
| 260 |
-
label="💾 Baixar Imagem Processada",
|
| 261 |
-
value=temp_file.name,
|
| 262 |
-
variant="primary",
|
| 263 |
-
size="lg",
|
| 264 |
-
visible=True
|
| 265 |
-
), temp_file.name
|
| 266 |
-
|
| 267 |
-
# Event handlers com download
|
| 268 |
-
def process_and_prepare_download(image):
|
| 269 |
-
"""Remove fundo e prepara download"""
|
| 270 |
-
result_image, status = remove_background(image)
|
| 271 |
-
download_button, file_path = prepare_download(result_image)
|
| 272 |
-
return result_image, status, download_button
|
| 273 |
-
|
| 274 |
-
def add_solid_and_prepare_download(image, color):
|
| 275 |
-
"""Adiciona cor e prepara download"""
|
| 276 |
-
result_image, status = add_solid_background(image, color)
|
| 277 |
-
download_button, file_path = prepare_download(result_image)
|
| 278 |
-
return result_image, status, download_button
|
| 279 |
-
|
| 280 |
-
def add_gradient_and_prepare_download(image, c1, c2):
|
| 281 |
-
"""Adiciona gradiente e prepara download"""
|
| 282 |
-
result_image, status = add_gradient_background(image, c1, c2)
|
| 283 |
-
download_button, file_path = prepare_download(result_image)
|
| 284 |
-
return result_image, status, download_button
|
| 285 |
-
|
| 286 |
-
def add_blur_and_prepare_download(image, strength):
|
| 287 |
-
"""Adiciona desfoque e prepara download"""
|
| 288 |
-
result_image, status = add_blur_background(image, strength)
|
| 289 |
-
download_button, file_path = prepare_download(result_image)
|
| 290 |
-
return result_image, status, download_button
|
| 291 |
-
|
| 292 |
-
# Conecta eventos
|
| 293 |
remove_btn.click(
|
| 294 |
-
fn=
|
| 295 |
inputs=[input_image],
|
| 296 |
-
outputs=[output_image, status_text,
|
| 297 |
)
|
| 298 |
|
| 299 |
solid_btn.click(
|
| 300 |
-
fn=
|
| 301 |
inputs=[output_image, bg_color],
|
| 302 |
-
outputs=[output_image, status_text,
|
| 303 |
)
|
| 304 |
|
| 305 |
gradient_btn.click(
|
| 306 |
-
fn=
|
| 307 |
inputs=[output_image, grad_color1, grad_color2],
|
| 308 |
-
outputs=[output_image, status_text,
|
| 309 |
)
|
| 310 |
|
| 311 |
blur_btn.click(
|
| 312 |
-
fn=
|
| 313 |
inputs=[output_image, blur_strength],
|
| 314 |
-
outputs=[output_image, status_text,
|
| 315 |
)
|
| 316 |
|
| 317 |
print("=" * 60)
|
|
|
|
| 9 |
import numpy as np
|
| 10 |
import sys
|
| 11 |
import os
|
| 12 |
+
import tempfile
|
| 13 |
+
from datetime import datetime
|
| 14 |
|
| 15 |
print("=" * 60)
|
| 16 |
print("🚀 INICIANDO APP 3: BACKGROUND REMOVER")
|
|
|
|
| 32 |
def remove_background(image):
|
| 33 |
"""Remove o fundo da imagem"""
|
| 34 |
if image is None:
|
| 35 |
+
return None, "❌ Por favor, envie uma imagem primeiro", None
|
| 36 |
|
| 37 |
try:
|
| 38 |
# Converte para PIL se necessário
|
|
|
|
| 54 |
output = create_simple_transparency(image)
|
| 55 |
print("⚠️ Usando método fallback")
|
| 56 |
|
| 57 |
+
# Salva para download
|
| 58 |
+
temp_file = save_for_download(output)
|
| 59 |
+
|
| 60 |
+
return output, "✅ Fundo removido com sucesso!", temp_file
|
| 61 |
|
| 62 |
except Exception as e:
|
| 63 |
error_msg = f"❌ Erro ao remover fundo: {str(e)}"
|
| 64 |
print(error_msg)
|
| 65 |
+
return None, error_msg, None
|
| 66 |
|
| 67 |
def create_simple_transparency(image):
|
| 68 |
"""Método fallback para criar transparência"""
|
|
|
|
| 90 |
result = Image.fromarray(np.dstack([img_array, alpha]))
|
| 91 |
return result
|
| 92 |
|
| 93 |
+
def save_for_download(image):
|
| 94 |
+
"""Salva imagem temporariamente para download"""
|
| 95 |
+
if image is None:
|
| 96 |
+
return None
|
| 97 |
+
|
| 98 |
+
# Cria arquivo temporário
|
| 99 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 100 |
+
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=f"_bg_removed_{timestamp}.png")
|
| 101 |
+
|
| 102 |
+
# Salva imagem
|
| 103 |
+
image.save(temp_file.name, format="PNG")
|
| 104 |
+
print(f"💾 Imagem salva: {temp_file.name}")
|
| 105 |
+
|
| 106 |
+
return temp_file.name
|
| 107 |
+
|
| 108 |
def add_solid_background(image, bg_color):
|
| 109 |
"""Adiciona fundo sólido colorido"""
|
| 110 |
if image is None:
|
| 111 |
+
return None, "❌ Remova o fundo primeiro", None
|
| 112 |
|
| 113 |
try:
|
| 114 |
# Converte hex para RGB
|
|
|
|
| 123 |
else:
|
| 124 |
background.paste(image, (0, 0))
|
| 125 |
|
| 126 |
+
# Salva para download
|
| 127 |
+
temp_file = save_for_download(background)
|
| 128 |
+
|
| 129 |
+
return background, f"✅ Fundo {bg_color} adicionado!", temp_file
|
| 130 |
|
| 131 |
except Exception as e:
|
| 132 |
+
return None, f"❌ Erro: {str(e)}", None
|
| 133 |
|
| 134 |
def add_gradient_background(image, color1, color2):
|
| 135 |
"""Adiciona fundo com gradiente"""
|
| 136 |
if image is None:
|
| 137 |
+
return None, "❌ Remova o fundo primeiro", None
|
| 138 |
|
| 139 |
try:
|
| 140 |
# Converte cores
|
|
|
|
| 157 |
else:
|
| 158 |
background.paste(image, (0, 0))
|
| 159 |
|
| 160 |
+
# Salva para download
|
| 161 |
+
temp_file = save_for_download(background)
|
| 162 |
+
|
| 163 |
+
return background, "✅ Gradiente adicionado!", temp_file
|
| 164 |
|
| 165 |
except Exception as e:
|
| 166 |
+
return None, f"❌ Erro: {str(e)}", None
|
| 167 |
|
| 168 |
def add_blur_background(image, blur_strength):
|
| 169 |
"""Adiciona fundo desfocado da própria imagem"""
|
| 170 |
if image is None:
|
| 171 |
+
return None, "❌ Remova o fundo primeiro", None
|
| 172 |
|
| 173 |
try:
|
| 174 |
from PIL import ImageFilter
|
|
|
|
| 184 |
if image.mode == 'RGBA':
|
| 185 |
blurred.paste(image, (0, 0), image)
|
| 186 |
|
| 187 |
+
# Salva para download
|
| 188 |
+
temp_file = save_for_download(blurred)
|
| 189 |
+
|
| 190 |
+
return blurred, "✅ Fundo desfocado adicionado!", temp_file
|
| 191 |
|
| 192 |
except Exception as e:
|
| 193 |
+
return None, f"❌ Erro: {str(e)}", None
|
| 194 |
|
| 195 |
# ========== INTERFACE GRADIO ==========
|
| 196 |
|
| 197 |
print("🎨 Criando interface Background Remover...")
|
| 198 |
|
| 199 |
+
with gr.Blocks(title="🎨 Background Remover - Photoshop AI App 3", theme=gr.themes.Soft()) as demo:
|
| 200 |
gr.Markdown("""
|
| 201 |
# 🎨 Background Remover
|
| 202 |
### Remove fundos de imagens automaticamente usando IA
|
|
|
|
| 205 |
1. 📸 Faça upload de uma imagem
|
| 206 |
2. ✂️ Clique em "Remover Fundo"
|
| 207 |
3. 🎨 Adicione um novo fundo (opcional)
|
| 208 |
+
4. 💾 Baixe o resultado usando o botão abaixo
|
| 209 |
""")
|
| 210 |
|
| 211 |
with gr.Row():
|
|
|
|
| 235 |
output_image = gr.Image(label="✨ Resultado", type="pil")
|
| 236 |
status_text = gr.Textbox(label="📊 Status", interactive=False)
|
| 237 |
|
| 238 |
+
# Arquivo para download
|
| 239 |
+
download_file = gr.File(label="💾 Baixar Imagem Processada", visible=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 240 |
|
| 241 |
# Exemplos
|
| 242 |
gr.Markdown("### 📋 Exemplos")
|
| 243 |
+
if os.path.exists("examples"):
|
| 244 |
+
gr.Examples(
|
| 245 |
+
examples=[
|
| 246 |
+
["examples/person.jpg"],
|
| 247 |
+
["examples/product.jpg"],
|
| 248 |
+
],
|
| 249 |
+
inputs=input_image,
|
| 250 |
+
label="Clique para testar"
|
| 251 |
+
)
|
| 252 |
|
| 253 |
# Informações
|
| 254 |
gr.Markdown("""
|
|
|
|
| 257 |
- ✅ Processamento automático com IA
|
| 258 |
- ✅ Exporta PNG com transparência
|
| 259 |
- ✅ Adicione fundos personalizados
|
| 260 |
+
- ✅ Download direto da imagem processada
|
| 261 |
|
| 262 |
### 💡 Dicas
|
| 263 |
- Use imagens com boa iluminação para melhores resultados
|
| 264 |
- Fundos uniformes são mais fáceis de remover
|
| 265 |
- O PNG mantém a transparência
|
| 266 |
- Experimente diferentes fundos para ver o que fica melhor
|
| 267 |
+
- Clique no arquivo acima para baixar a imagem
|
| 268 |
|
| 269 |
---
|
| 270 |
**🔗 Parte do Photoshop AI Ecosystem** | App 3 de 10
|
| 271 |
""")
|
| 272 |
|
| 273 |
+
# Event handlers
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 274 |
remove_btn.click(
|
| 275 |
+
fn=remove_background,
|
| 276 |
inputs=[input_image],
|
| 277 |
+
outputs=[output_image, status_text, download_file]
|
| 278 |
)
|
| 279 |
|
| 280 |
solid_btn.click(
|
| 281 |
+
fn=add_solid_background,
|
| 282 |
inputs=[output_image, bg_color],
|
| 283 |
+
outputs=[output_image, status_text, download_file]
|
| 284 |
)
|
| 285 |
|
| 286 |
gradient_btn.click(
|
| 287 |
+
fn=add_gradient_background,
|
| 288 |
inputs=[output_image, grad_color1, grad_color2],
|
| 289 |
+
outputs=[output_image, status_text, download_file]
|
| 290 |
)
|
| 291 |
|
| 292 |
blur_btn.click(
|
| 293 |
+
fn=add_blur_background,
|
| 294 |
inputs=[output_image, blur_strength],
|
| 295 |
+
outputs=[output_image, status_text, download_file]
|
| 296 |
)
|
| 297 |
|
| 298 |
print("=" * 60)
|