Spaces:
Build error
Build error
created app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from diffusers import StableDiffusionInpaintPipeline
|
| 3 |
+
import gradio as gr
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
# Ensure we use GPU if available
|
| 8 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 9 |
+
|
| 10 |
+
def load_model():
|
| 11 |
+
"""Load ControlNet Inpainting model."""
|
| 12 |
+
pipe = StableDiffusionInpaintPipeline.from_pretrained(
|
| 13 |
+
"lllyasviel/control_v11p_sd15_inpaint",
|
| 14 |
+
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32
|
| 15 |
+
).to(device)
|
| 16 |
+
return pipe
|
| 17 |
+
|
| 18 |
+
pipe = load_model()
|
| 19 |
+
|
| 20 |
+
def inpaint(image_editor_output, prompt):
|
| 21 |
+
"""Perform inpainting using the uploaded image and mask."""
|
| 22 |
+
print(f"image_editor_output:{image_editor_output}")
|
| 23 |
+
|
| 24 |
+
if not isinstance(image_editor_output, dict) or "background" not in image_editor_output or "layers" not in image_editor_output:
|
| 25 |
+
raise ValueError("Invalid input. Please upload an image and paint a mask.")
|
| 26 |
+
|
| 27 |
+
# Extract the base image (background or composite)
|
| 28 |
+
image = Image.fromarray(image_editor_output["composite"]).convert("RGB") # Ensure image is in RGB format
|
| 29 |
+
|
| 30 |
+
# Extract the first layer (mask) and convert to grayscale
|
| 31 |
+
mask_array = np.array(image_editor_output["layers"][0], dtype=np.uint8)
|
| 32 |
+
mask = Image.fromarray(mask_array[:, :, 3]).convert("L") # Use the alpha channel
|
| 33 |
+
|
| 34 |
+
# Resize mask to match image size if needed
|
| 35 |
+
if mask.size != image.size:
|
| 36 |
+
mask = mask.resize(image.size, Image.LANCZOS)
|
| 37 |
+
|
| 38 |
+
# Perform inpainting
|
| 39 |
+
result = pipe(prompt=prompt, image=image, mask_image=mask).images[0]
|
| 40 |
+
return result
|
| 41 |
+
|
| 42 |
+
# Gradio UI with ImageEditor for inpainting
|
| 43 |
+
demo = gr.Interface(
|
| 44 |
+
fn=inpaint,
|
| 45 |
+
inputs=[
|
| 46 |
+
gr.ImageEditor(label="Upload & Paint Image (White areas will be inpainted)"),
|
| 47 |
+
gr.Textbox(label="Prompt for Inpainting"),
|
| 48 |
+
],
|
| 49 |
+
outputs=gr.Image(type="pil", label="Generated Image"),
|
| 50 |
+
title="ControlNet Inpainting",
|
| 51 |
+
description="Upload an image, paint directly on it to define mask areas, and provide a text prompt.",
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
demo.launch()
|