Spaces:
Running
on
Zero
Running
on
Zero
File size: 11,968 Bytes
19f98dc b1d8999 19f98dc 4d0ad40 e14bb0a 19f98dc 9f7976a e14bb0a 19f98dc c2cf1ee b1d8999 4d0ad40 19f98dc 2b0aade 19f98dc b1d8999 19f98dc b1d8999 19f98dc 0c9f948 b1d8999 1447103 19f98dc 4553b9e 19f98dc 67237f1 3cc9869 73d42f6 b1d8999 3cc9869 19f98dc b1d8999 19f98dc b1d8999 19f98dc b1d8999 19f98dc b1d8999 19f98dc b1d8999 19f98dc b1d8999 19f98dc 4553b9e b1d8999 19f98dc b1d8999 19f98dc b1d8999 19f98dc b1d8999 19f98dc b1d8999 19f98dc b1d8999 19f98dc b1d8999 9f7976a cc92341 8d39edd 4553b9e 19f98dc 4d0ad40 19f98dc 67237f1 19f98dc c584662 d97d8b8 b1d8999 4d0ad40 c584662 1447103 19f98dc b1d8999 19f98dc b1d8999 19f98dc b1d8999 4d0ad40 b1d8999 4d0ad40 19f98dc b1d8999 19f98dc b1d8999 4d0ad40 b1d8999 4d0ad40 b1d8999 4d0ad40 b1d8999 4d0ad40 b1d8999 4d0ad40 b1d8999 19f98dc b1d8999 19f98dc b1d8999 19f98dc 4d0ad40 19f98dc |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 |
import secrets
from pathlib import Path
from typing import cast
import gradio as gr
import numpy as np
import spaces
import torch
from diffusers import FluxFillPipeline
from gradio.components.image_editor import EditorValue
from PIL import Image, ImageFilter, ImageOps
DEVICE = "cuda"
EXAMPLES_DIR = Path(__file__).parent / "examples"
MAX_SEED = np.iinfo(np.int32).max
SYSTEM_PROMPT = r"""This two-panel split-frame image showcases a furniture in as a product shot versus styled in a room.
[LEFT] standalone product shot image the furniture on a white background.
[RIGHT] integrated example within a room scene."""
if not torch.cuda.is_available():
def _dummy_pipe(image: Image.Image, *args, **kwargs): # noqa: ARG001
return {"images": [image]}
pipe = _dummy_pipe
else:
state_dict, network_alphas = FluxFillPipeline.lora_state_dict(
pretrained_model_name_or_path_or_dict="blanchon/FluxFillFurniture",
weight_name="pytorch_lora_weights3.safetensors",
torch_dtype=torch.bfloat16,
return_alphas=True,
)
if not all(("lora" in key or "dora_scale" in key) for key in state_dict):
msg = "Invalid LoRA checkpoint."
raise ValueError(msg)
pipe = FluxFillPipeline.from_pretrained(
"black-forest-labs/FLUX.1-Fill-dev", torch_dtype=torch.bfloat16
).to(DEVICE)
FluxFillPipeline.load_lora_into_transformer(
state_dict=state_dict,
network_alphas=network_alphas,
torch_dtype=torch.bfloat16,
transformer=pipe.transformer,
)
pipe.to(DEVICE)
def make_example(image_path: Path, mask_path: Path) -> EditorValue:
background_image = Image.open(image_path)
background_image = background_image.convert("RGB")
background = np.array(background_image)
mask_image = Image.open(mask_path)
mask_image = mask_image.convert("RGB")
mask = np.array(mask_image)
mask = mask[:, :, 0]
mask = np.where(mask == 255, 0, 255) # noqa: PLR2004
if background.shape[0] != mask.shape[0] or background.shape[1] != mask.shape[1]:
msg = "Background and mask must have the same shape"
raise ValueError(msg)
layer = np.zeros((background.shape[0], background.shape[1], 4), dtype=np.uint8)
layer[:, :, 3] = mask
composite = np.zeros((background.shape[0], background.shape[1], 4), dtype=np.uint8)
composite[:, :, :3] = background
composite[:, :, 3] = np.where(mask == 255, 0, 255) # noqa: PLR2004
return {
"background": background,
"layers": [layer],
"composite": composite,
}
@spaces.GPU(duration=150)
def infer(
furniture_image: Image.Image,
room_image: EditorValue,
prompt: str = "",
seed: int = 42,
randomize_seed: bool = False,
guidance_scale: float = 3.5,
num_inference_steps: int = 20,
max_dimension: int = 720,
progress: gr.Progress = gr.Progress(track_tqdm=True), # noqa: ARG001, B008
):
# Ensure max_dimension is a multiple of 16 (for VAE)
max_dimension = (max_dimension // 16) * 16
_room_image = room_image["background"]
if _room_image is None:
msg = "Room image is required"
raise ValueError(msg)
_room_image = cast("Image.Image", _room_image)
_room_image = ImageOps.fit(
_room_image,
(max_dimension, max_dimension),
method=Image.Resampling.LANCZOS,
centering=(0.5, 0.5),
)
_room_mask = room_image["layers"][0]
if _room_mask is None:
msg = "Room mask is required"
raise ValueError(msg)
_room_mask = cast("Image.Image", _room_mask)
_room_mask = ImageOps.fit(
_room_mask,
(max_dimension, max_dimension),
method=Image.Resampling.LANCZOS,
centering=(0.5, 0.5),
)
# _room_image.save("room_image.png")
# _room_mask_with_white_background = Image.new(
# "RGB", _room_mask.size, (255, 255, 255)
# )
# _room_mask_with_white_background.paste(_room_mask, (0, 0), _room_mask)
# _room_mask_with_white_background.save("room_mask.png")
furniture_image = ImageOps.fit(
furniture_image,
(max_dimension, max_dimension),
method=Image.Resampling.LANCZOS,
centering=(0.5, 0.5),
)
_furniture_image = Image.new(
"RGB",
(max_dimension, max_dimension),
(255, 255, 255),
)
_furniture_image.paste(furniture_image, (0, 0))
# _furniture_image.save("furniture_image.png")
_furniture_mask = Image.new("RGB", (max_dimension, max_dimension), (255, 255, 255))
image = Image.new(
"RGB",
(max_dimension * 2, max_dimension),
(255, 255, 255),
)
# Paste on the center of the image
image.paste(_furniture_image, (0, 0))
image.paste(_room_image, (max_dimension, 0))
mask = Image.new(
"RGB",
(max_dimension * 2, max_dimension),
(255, 255, 255),
)
mask.paste(_furniture_mask, (0, 0))
mask.paste(_room_mask, (max_dimension, 0), _room_mask)
# Invert the mask
mask = ImageOps.invert(mask)
# Blur the mask
mask = mask.filter(ImageFilter.GaussianBlur(radius=10))
# Convert to 3 channel
mask = mask.convert("L")
if randomize_seed:
seed = secrets.randbelow(MAX_SEED)
prompt = prompt + ".\n" + SYSTEM_PROMPT if prompt else SYSTEM_PROMPT
results_images = pipe(
prompt=prompt,
image=image,
mask_image=mask,
height=max_dimension,
width=max_dimension * 2,
num_inference_steps=num_inference_steps,
guidance_scale=guidance_scale,
num_images_per_prompt=2,
generator=torch.Generator("cpu").manual_seed(seed),
)["images"]
cropped_images = [
image.crop((max_dimension, 0, max_dimension * 2, max_dimension))
for image in results_images
]
return cropped_images, seed
intro_markdown = r"""
<div>
<div>
<div style="display: flex; justify-content: center; align-items: center; text-align: center; font-size: 40px;">
<b>AnyFurnish</b>
</div>
<br>
<div style="display: flex; justify-content: center; align-items: center; text-align: center;">
<a href="https://github.com/julien-blanchon/"><img src="https://img.shields.io/static/v1?label=Github Report&message=Github&color=green"></a>  
</div>
<br>
<div style="display: flex; text-align: center; font-size: 14px; padding-right: 300px; padding-left: 300px;">
AnyFurnish is a tool that allows you to generate furniture images using Flux.1 Fill Dev.
You can upload a furniture image and a room image, and the tool will generate a new image with the furniture in the room.
</div>
</div>
</div>
"""
css = r"""
#col-left {
margin: 0 auto;
max-width: 430px;
}
#col-mid {
margin: 0 auto;
max-width: 430px;
}
#col-right {
margin: 0 auto;
max-width: 430px;
}
#col-showcase {
margin: 0 auto;
max-width: 1100px;
}
"""
with gr.Blocks(css=css) as demo:
gr.Markdown(intro_markdown)
with gr.Row():
with gr.Column(elem_id="col-left"):
gr.HTML(
"""
<div style="display: flex; justify-content: center; align-items: center; text-align: center; font-size: 20px;">
<div>
Step 1. Upload a furniture image ⬇️
</div>
</div>
""",
max_height=50,
)
furniture_image = gr.Image(
label="Furniture Image",
type="pil",
sources=["upload"],
image_mode="RGB",
height=500,
)
furniture_prompt = gr.Text(
label="Prompt",
max_lines=1,
placeholder="Enter a custom furniture description (optional)",
container=False,
)
with gr.Column(elem_id="col-mid"):
gr.HTML(
"""
<div style="display: flex; justify-content: center; align-items: center; text-align: center; font-size: 20px;">
<div>
Step 2. Upload a room image ⬇️
</div>
</div>
""",
max_height=50,
)
room_image = gr.ImageEditor(
label="Room Image - Draw mask for inpainting",
type="pil",
sources=["upload"],
image_mode="RGBA",
layers=False,
crop_size="1:1",
brush=gr.Brush(colors=["#FFFFFF"], color_mode="fixed"),
height=500,
)
with gr.Column(elem_id="col-right"):
gr.HTML(
"""
<div style="display: flex; justify-content: center; align-items: center; text-align: center; font-size: 20px;">
<div>
Step 3. Press Run to launch
</div>
</div>
""",
max_height=50,
)
results = gr.Gallery(
label="Results",
format="png",
show_label=False,
columns=2,
height=500,
)
run_button = gr.Button("Run")
with gr.Accordion("Advanced Settings", open=False):
seed = gr.Slider(
label="Seed",
minimum=0,
maximum=MAX_SEED,
step=1,
value=0,
)
randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
with gr.Column():
max_dimension = gr.Slider(
label="Max Dimension",
minimum=512,
maximum=1024,
step=128,
value=720,
)
guidance_scale = gr.Slider(
label="Guidance Scale",
minimum=1,
maximum=30,
step=0.5,
# value=50, # noqa: ERA001
value=30,
)
num_inference_steps = gr.Slider(
label="Number of inference steps",
minimum=1,
maximum=50,
step=1,
value=20,
)
with gr.Column(elem_id="col-showcase"):
gr.HTML("""
<div style="display: flex; justify-content: center; align-items: center; text-align: center; font-size: 20px;">
<div> </div>
<br>
<div>
AnyFurnish examples in pairs of furniture and room images
</div>
</div>
""")
show_case = gr.Examples(
examples=[
[
EXAMPLES_DIR / "1" / "furniture_image.png",
make_example(
EXAMPLES_DIR / "1" / "room_image.png",
EXAMPLES_DIR / "1" / "room_mask.png",
),
],
[
EXAMPLES_DIR / "2" / "furniture_image.png",
make_example(
EXAMPLES_DIR / "2" / "room_image.png",
EXAMPLES_DIR / "2" / "room_mask.png",
),
],
],
inputs=[furniture_image, room_image],
label=None,
)
gr.on(
triggers=[run_button.click, furniture_prompt.submit],
fn=infer,
inputs=[
furniture_image,
room_image,
furniture_prompt,
seed,
randomize_seed,
guidance_scale,
num_inference_steps,
max_dimension,
],
outputs=[results, seed],
)
demo.launch()
|