linfanluntan abhishek HF staff commited on
Commit
87b56d3
0 Parent(s):

Duplicate from abhishek/StableSAM

Browse files

Co-authored-by: Abhishek Thakur <abhishek@users.noreply.huggingface.co>

.gitattributes ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: StableSAM
3
+ emoji: 🍀
4
+ colorFrom: blue
5
+ colorTo: yellow
6
+ sdk: gradio
7
+ sdk_version: 3.25.0
8
+ app_file: app.py
9
+ pinned: false
10
+ duplicated_from: abhishek/StableSAM
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
__pycache__/app.cpython-38.pyc ADDED
Binary file (4.26 kB). View file
 
__pycache__/controlnet_inpaint.cpython-38.pyc ADDED
Binary file (35.9 kB). View file
 
app.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import torch
4
+ from diffusers import StableDiffusionInpaintPipeline
5
+ from PIL import Image
6
+ from segment_anything import SamPredictor, sam_model_registry, SamAutomaticMaskGenerator
7
+ from diffusers import ControlNetModel
8
+ from diffusers import UniPCMultistepScheduler
9
+ from controlnet_inpaint import StableDiffusionControlNetInpaintPipeline
10
+ import colorsys
11
+
12
+ sam_checkpoint = "sam_vit_h_4b8939.pth"
13
+ model_type = "vit_h"
14
+ device = "cuda"
15
+
16
+
17
+ sam = sam_model_registry[model_type](checkpoint=sam_checkpoint)
18
+ sam.to(device=device)
19
+ predictor = SamPredictor(sam)
20
+ mask_generator = SamAutomaticMaskGenerator(sam)
21
+
22
+ # pipe = StableDiffusionInpaintPipeline.from_pretrained(
23
+ # "stabilityai/stable-diffusion-2-inpainting",
24
+ # torch_dtype=torch.float16,
25
+ # )
26
+ # pipe = pipe.to("cuda")
27
+
28
+ controlnet = ControlNetModel.from_pretrained(
29
+ "lllyasviel/sd-controlnet-seg",
30
+ torch_dtype=torch.float16,
31
+ )
32
+ pipe = StableDiffusionControlNetInpaintPipeline.from_pretrained(
33
+ "runwayml/stable-diffusion-inpainting",
34
+ controlnet=controlnet,
35
+ torch_dtype=torch.float16,
36
+ )
37
+ pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
38
+ pipe.enable_model_cpu_offload()
39
+ pipe.enable_xformers_memory_efficient_attention()
40
+
41
+
42
+ with gr.Blocks() as demo:
43
+ gr.Markdown("# StableSAM: Stable Diffusion + Segment Anything Model")
44
+ gr.Markdown(
45
+ """
46
+ To try the demo, upload an image and select object(s) you want to inpaint.
47
+ Write a prompt & a negative prompt to control the inpainting.
48
+ Click on the "Submit" button to inpaint the selected object(s).
49
+ Check "Background" to inpaint the background instead of the selected object(s).
50
+
51
+ If the demo is slow, clone the space to your own HF account and run on a GPU.
52
+ """
53
+ )
54
+ selected_pixels = gr.State([])
55
+ with gr.Row():
56
+ input_img = gr.Image(label="Input")
57
+ mask_img = gr.Image(label="Mask", interactive=False)
58
+ seg_img = gr.Image(label="Segmentation", interactive=False)
59
+ output_img = gr.Image(label="Output", interactive=False)
60
+
61
+ with gr.Row():
62
+ prompt_text = gr.Textbox(lines=1, label="Prompt")
63
+ negative_prompt_text = gr.Textbox(lines=1, label="Negative Prompt")
64
+ is_background = gr.Checkbox(label="Background")
65
+
66
+ with gr.Row():
67
+ submit = gr.Button("Submit")
68
+ clear = gr.Button("Clear")
69
+
70
+ def generate_mask(image, bg, sel_pix, evt: gr.SelectData):
71
+ sel_pix.append(evt.index)
72
+ predictor.set_image(image)
73
+ input_point = np.array(sel_pix)
74
+ input_label = np.ones(input_point.shape[0])
75
+ mask, _, _ = predictor.predict(
76
+ point_coords=input_point,
77
+ point_labels=input_label,
78
+ multimask_output=False,
79
+ )
80
+ # clear torch cache
81
+ torch.cuda.empty_cache()
82
+ if bg:
83
+ mask = np.logical_not(mask)
84
+ mask = Image.fromarray(mask[0, :, :])
85
+ segs = mask_generator.generate(image)
86
+ boolean_masks = [s["segmentation"] for s in segs]
87
+ finseg = np.zeros((boolean_masks[0].shape[0], boolean_masks[0].shape[1], 3), dtype=np.uint8)
88
+ # Loop over the boolean masks and assign a unique color to each class
89
+ for class_id, boolean_mask in enumerate(boolean_masks):
90
+ hue = class_id * 1.0 / len(boolean_masks)
91
+ rgb = tuple(int(i * 255) for i in colorsys.hsv_to_rgb(hue, 1, 1))
92
+ rgb_mask = np.zeros((boolean_mask.shape[0], boolean_mask.shape[1], 3), dtype=np.uint8)
93
+ rgb_mask[:, :, 0] = boolean_mask * rgb[0]
94
+ rgb_mask[:, :, 1] = boolean_mask * rgb[1]
95
+ rgb_mask[:, :, 2] = boolean_mask * rgb[2]
96
+ finseg += rgb_mask
97
+
98
+ torch.cuda.empty_cache()
99
+
100
+ return mask, finseg
101
+
102
+ def inpaint(image, mask, seg_img, prompt, negative_prompt):
103
+ image = Image.fromarray(image)
104
+ mask = Image.fromarray(mask)
105
+ seg_img = Image.fromarray(seg_img)
106
+
107
+ image = image.resize((512, 512))
108
+ mask = mask.resize((512, 512))
109
+ seg_img = seg_img.resize((512, 512))
110
+
111
+ output = pipe(
112
+ prompt,
113
+ image,
114
+ mask,
115
+ seg_img,
116
+ negative_prompt=negative_prompt,
117
+ num_inference_steps=20,
118
+ ).images[0]
119
+ torch.cuda.empty_cache()
120
+ return output
121
+
122
+ def _clear(sel_pix, img, mask, seg, out, prompt, neg_prompt, bg):
123
+ sel_pix = []
124
+ img = None
125
+ mask = None
126
+ seg = None
127
+ out = None
128
+ prompt = ""
129
+ neg_prompt = ""
130
+ bg = False
131
+ return img, mask, seg, out, prompt, neg_prompt, bg
132
+
133
+ input_img.select(
134
+ generate_mask,
135
+ [input_img, is_background, selected_pixels],
136
+ [mask_img, seg_img],
137
+ )
138
+ submit.click(
139
+ inpaint,
140
+ inputs=[input_img, mask_img, seg_img, prompt_text, negative_prompt_text],
141
+ outputs=[output_img],
142
+ )
143
+ clear.click(
144
+ _clear,
145
+ inputs=[
146
+ selected_pixels,
147
+ input_img,
148
+ mask_img,
149
+ seg_img,
150
+ output_img,
151
+ prompt_text,
152
+ negative_prompt_text,
153
+ is_background,
154
+ ],
155
+ outputs=[
156
+ input_img,
157
+ mask_img,
158
+ seg_img,
159
+ output_img,
160
+ prompt_text,
161
+ negative_prompt_text,
162
+ is_background,
163
+ ],
164
+ )
165
+
166
+ if __name__ == "__main__":
167
+ demo.launch()
controlnet_inpaint.py ADDED
@@ -0,0 +1,1077 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # All the code in this file has been taken from: https://github.com/huggingface/diffusers/blob/main/examples/community/stable_diffusion_controlnet_inpaint.py
2
+ # Inspired by: https://github.com/haofanwang/ControlNet-for-Diffusers/
3
+
4
+ import inspect
5
+ from typing import Any, Callable, Dict, List, Optional, Union
6
+
7
+ import numpy as np
8
+ import PIL.Image
9
+ import torch
10
+ import torch.nn.functional as F
11
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
12
+
13
+ from diffusers import AutoencoderKL, ControlNetModel, DiffusionPipeline, UNet2DConditionModel, logging
14
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput, StableDiffusionSafetyChecker
15
+ from diffusers.schedulers import KarrasDiffusionSchedulers
16
+ from diffusers.utils import (
17
+ PIL_INTERPOLATION,
18
+ is_accelerate_available,
19
+ is_accelerate_version,
20
+ randn_tensor,
21
+ replace_example_docstring,
22
+ )
23
+
24
+
25
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
26
+
27
+ EXAMPLE_DOC_STRING = """
28
+ Examples:
29
+ ```py
30
+ >>> import numpy as np
31
+ >>> import torch
32
+ >>> from PIL import Image
33
+ >>> from stable_diffusion_controlnet_inpaint import StableDiffusionControlNetInpaintPipeline
34
+
35
+ >>> from transformers import AutoImageProcessor, UperNetForSemanticSegmentation
36
+ >>> from diffusers import ControlNetModel, UniPCMultistepScheduler
37
+ >>> from diffusers.utils import load_image
38
+
39
+ >>> def ade_palette():
40
+ return [[120, 120, 120], [180, 120, 120], [6, 230, 230], [80, 50, 50],
41
+ [4, 200, 3], [120, 120, 80], [140, 140, 140], [204, 5, 255],
42
+ [230, 230, 230], [4, 250, 7], [224, 5, 255], [235, 255, 7],
43
+ [150, 5, 61], [120, 120, 70], [8, 255, 51], [255, 6, 82],
44
+ [143, 255, 140], [204, 255, 4], [255, 51, 7], [204, 70, 3],
45
+ [0, 102, 200], [61, 230, 250], [255, 6, 51], [11, 102, 255],
46
+ [255, 7, 71], [255, 9, 224], [9, 7, 230], [220, 220, 220],
47
+ [255, 9, 92], [112, 9, 255], [8, 255, 214], [7, 255, 224],
48
+ [255, 184, 6], [10, 255, 71], [255, 41, 10], [7, 255, 255],
49
+ [224, 255, 8], [102, 8, 255], [255, 61, 6], [255, 194, 7],
50
+ [255, 122, 8], [0, 255, 20], [255, 8, 41], [255, 5, 153],
51
+ [6, 51, 255], [235, 12, 255], [160, 150, 20], [0, 163, 255],
52
+ [140, 140, 140], [250, 10, 15], [20, 255, 0], [31, 255, 0],
53
+ [255, 31, 0], [255, 224, 0], [153, 255, 0], [0, 0, 255],
54
+ [255, 71, 0], [0, 235, 255], [0, 173, 255], [31, 0, 255],
55
+ [11, 200, 200], [255, 82, 0], [0, 255, 245], [0, 61, 255],
56
+ [0, 255, 112], [0, 255, 133], [255, 0, 0], [255, 163, 0],
57
+ [255, 102, 0], [194, 255, 0], [0, 143, 255], [51, 255, 0],
58
+ [0, 82, 255], [0, 255, 41], [0, 255, 173], [10, 0, 255],
59
+ [173, 255, 0], [0, 255, 153], [255, 92, 0], [255, 0, 255],
60
+ [255, 0, 245], [255, 0, 102], [255, 173, 0], [255, 0, 20],
61
+ [255, 184, 184], [0, 31, 255], [0, 255, 61], [0, 71, 255],
62
+ [255, 0, 204], [0, 255, 194], [0, 255, 82], [0, 10, 255],
63
+ [0, 112, 255], [51, 0, 255], [0, 194, 255], [0, 122, 255],
64
+ [0, 255, 163], [255, 153, 0], [0, 255, 10], [255, 112, 0],
65
+ [143, 255, 0], [82, 0, 255], [163, 255, 0], [255, 235, 0],
66
+ [8, 184, 170], [133, 0, 255], [0, 255, 92], [184, 0, 255],
67
+ [255, 0, 31], [0, 184, 255], [0, 214, 255], [255, 0, 112],
68
+ [92, 255, 0], [0, 224, 255], [112, 224, 255], [70, 184, 160],
69
+ [163, 0, 255], [153, 0, 255], [71, 255, 0], [255, 0, 163],
70
+ [255, 204, 0], [255, 0, 143], [0, 255, 235], [133, 255, 0],
71
+ [255, 0, 235], [245, 0, 255], [255, 0, 122], [255, 245, 0],
72
+ [10, 190, 212], [214, 255, 0], [0, 204, 255], [20, 0, 255],
73
+ [255, 255, 0], [0, 153, 255], [0, 41, 255], [0, 255, 204],
74
+ [41, 0, 255], [41, 255, 0], [173, 0, 255], [0, 245, 255],
75
+ [71, 0, 255], [122, 0, 255], [0, 255, 184], [0, 92, 255],
76
+ [184, 255, 0], [0, 133, 255], [255, 214, 0], [25, 194, 194],
77
+ [102, 255, 0], [92, 0, 255]]
78
+
79
+ >>> image_processor = AutoImageProcessor.from_pretrained("openmmlab/upernet-convnext-small")
80
+ >>> image_segmentor = UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-convnext-small")
81
+
82
+ >>> controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-seg", torch_dtype=torch.float16)
83
+
84
+ >>> pipe = StableDiffusionControlNetInpaintPipeline.from_pretrained(
85
+ "runwayml/stable-diffusion-inpainting", controlnet=controlnet, safety_checker=None, torch_dtype=torch.float16
86
+ )
87
+
88
+ >>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
89
+ >>> pipe.enable_xformers_memory_efficient_attention()
90
+ >>> pipe.enable_model_cpu_offload()
91
+
92
+ >>> def image_to_seg(image):
93
+ pixel_values = image_processor(image, return_tensors="pt").pixel_values
94
+ with torch.no_grad():
95
+ outputs = image_segmentor(pixel_values)
96
+ seg = image_processor.post_process_semantic_segmentation(outputs, target_sizes=[image.size[::-1]])[0]
97
+ color_seg = np.zeros((seg.shape[0], seg.shape[1], 3), dtype=np.uint8) # height, width, 3
98
+ palette = np.array(ade_palette())
99
+ for label, color in enumerate(palette):
100
+ color_seg[seg == label, :] = color
101
+ color_seg = color_seg.astype(np.uint8)
102
+ seg_image = Image.fromarray(color_seg)
103
+ return seg_image
104
+
105
+ >>> image = load_image(
106
+ "https://github.com/CompVis/latent-diffusion/raw/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
107
+ )
108
+
109
+ >>> mask_image = load_image(
110
+ "https://github.com/CompVis/latent-diffusion/raw/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
111
+ )
112
+
113
+ >>> controlnet_conditioning_image = image_to_seg(image)
114
+
115
+ >>> image = pipe(
116
+ "Face of a yellow cat, high resolution, sitting on a park bench",
117
+ image,
118
+ mask_image,
119
+ controlnet_conditioning_image,
120
+ num_inference_steps=20,
121
+ ).images[0]
122
+
123
+ >>> image.save("out.png")
124
+ ```
125
+ """
126
+
127
+
128
+ def prepare_image(image):
129
+ if isinstance(image, torch.Tensor):
130
+ # Batch single image
131
+ if image.ndim == 3:
132
+ image = image.unsqueeze(0)
133
+
134
+ image = image.to(dtype=torch.float32)
135
+ else:
136
+ # preprocess image
137
+ if isinstance(image, (PIL.Image.Image, np.ndarray)):
138
+ image = [image]
139
+
140
+ if isinstance(image, list) and isinstance(image[0], PIL.Image.Image):
141
+ image = [np.array(i.convert("RGB"))[None, :] for i in image]
142
+ image = np.concatenate(image, axis=0)
143
+ elif isinstance(image, list) and isinstance(image[0], np.ndarray):
144
+ image = np.concatenate([i[None, :] for i in image], axis=0)
145
+
146
+ image = image.transpose(0, 3, 1, 2)
147
+ image = torch.from_numpy(image).to(dtype=torch.float32) / 127.5 - 1.0
148
+
149
+ return image
150
+
151
+
152
+ def prepare_mask_image(mask_image):
153
+ if isinstance(mask_image, torch.Tensor):
154
+ if mask_image.ndim == 2:
155
+ # Batch and add channel dim for single mask
156
+ mask_image = mask_image.unsqueeze(0).unsqueeze(0)
157
+ elif mask_image.ndim == 3 and mask_image.shape[0] == 1:
158
+ # Single mask, the 0'th dimension is considered to be
159
+ # the existing batch size of 1
160
+ mask_image = mask_image.unsqueeze(0)
161
+ elif mask_image.ndim == 3 and mask_image.shape[0] != 1:
162
+ # Batch of mask, the 0'th dimension is considered to be
163
+ # the batching dimension
164
+ mask_image = mask_image.unsqueeze(1)
165
+
166
+ # Binarize mask
167
+ mask_image[mask_image < 0.5] = 0
168
+ mask_image[mask_image >= 0.5] = 1
169
+ else:
170
+ # preprocess mask
171
+ if isinstance(mask_image, (PIL.Image.Image, np.ndarray)):
172
+ mask_image = [mask_image]
173
+
174
+ if isinstance(mask_image, list) and isinstance(mask_image[0], PIL.Image.Image):
175
+ mask_image = np.concatenate([np.array(m.convert("L"))[None, None, :] for m in mask_image], axis=0)
176
+ mask_image = mask_image.astype(np.float32) / 255.0
177
+ elif isinstance(mask_image, list) and isinstance(mask_image[0], np.ndarray):
178
+ mask_image = np.concatenate([m[None, None, :] for m in mask_image], axis=0)
179
+
180
+ mask_image[mask_image < 0.5] = 0
181
+ mask_image[mask_image >= 0.5] = 1
182
+ mask_image = torch.from_numpy(mask_image)
183
+
184
+ return mask_image
185
+
186
+
187
+ def prepare_controlnet_conditioning_image(
188
+ controlnet_conditioning_image, width, height, batch_size, num_images_per_prompt, device, dtype
189
+ ):
190
+ if not isinstance(controlnet_conditioning_image, torch.Tensor):
191
+ if isinstance(controlnet_conditioning_image, PIL.Image.Image):
192
+ controlnet_conditioning_image = [controlnet_conditioning_image]
193
+
194
+ if isinstance(controlnet_conditioning_image[0], PIL.Image.Image):
195
+ controlnet_conditioning_image = [
196
+ np.array(i.resize((width, height), resample=PIL_INTERPOLATION["lanczos"]))[None, :]
197
+ for i in controlnet_conditioning_image
198
+ ]
199
+ controlnet_conditioning_image = np.concatenate(controlnet_conditioning_image, axis=0)
200
+ controlnet_conditioning_image = np.array(controlnet_conditioning_image).astype(np.float32) / 255.0
201
+ controlnet_conditioning_image = controlnet_conditioning_image.transpose(0, 3, 1, 2)
202
+ controlnet_conditioning_image = torch.from_numpy(controlnet_conditioning_image)
203
+ elif isinstance(controlnet_conditioning_image[0], torch.Tensor):
204
+ controlnet_conditioning_image = torch.cat(controlnet_conditioning_image, dim=0)
205
+
206
+ image_batch_size = controlnet_conditioning_image.shape[0]
207
+
208
+ if image_batch_size == 1:
209
+ repeat_by = batch_size
210
+ else:
211
+ # image batch size is the same as prompt batch size
212
+ repeat_by = num_images_per_prompt
213
+
214
+ controlnet_conditioning_image = controlnet_conditioning_image.repeat_interleave(repeat_by, dim=0)
215
+
216
+ controlnet_conditioning_image = controlnet_conditioning_image.to(device=device, dtype=dtype)
217
+
218
+ return controlnet_conditioning_image
219
+
220
+
221
+ class StableDiffusionControlNetInpaintPipeline(DiffusionPipeline):
222
+ """
223
+ Inspired by: https://github.com/haofanwang/ControlNet-for-Diffusers/
224
+ """
225
+
226
+ _optional_components = ["safety_checker", "feature_extractor"]
227
+
228
+ def __init__(
229
+ self,
230
+ vae: AutoencoderKL,
231
+ text_encoder: CLIPTextModel,
232
+ tokenizer: CLIPTokenizer,
233
+ unet: UNet2DConditionModel,
234
+ controlnet: ControlNetModel,
235
+ scheduler: KarrasDiffusionSchedulers,
236
+ safety_checker: StableDiffusionSafetyChecker,
237
+ feature_extractor: CLIPImageProcessor,
238
+ requires_safety_checker: bool = True,
239
+ ):
240
+ super().__init__()
241
+
242
+ if safety_checker is None and requires_safety_checker:
243
+ logger.warning(
244
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
245
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
246
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
247
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
248
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
249
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
250
+ )
251
+
252
+ if safety_checker is not None and feature_extractor is None:
253
+ raise ValueError(
254
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
255
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
256
+ )
257
+
258
+ self.register_modules(
259
+ vae=vae,
260
+ text_encoder=text_encoder,
261
+ tokenizer=tokenizer,
262
+ unet=unet,
263
+ controlnet=controlnet,
264
+ scheduler=scheduler,
265
+ safety_checker=safety_checker,
266
+ feature_extractor=feature_extractor,
267
+ )
268
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
269
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
270
+
271
+ def enable_vae_slicing(self):
272
+ r"""
273
+ Enable sliced VAE decoding.
274
+
275
+ When this option is enabled, the VAE will split the input tensor in slices to compute decoding in several
276
+ steps. This is useful to save some memory and allow larger batch sizes.
277
+ """
278
+ self.vae.enable_slicing()
279
+
280
+ def disable_vae_slicing(self):
281
+ r"""
282
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously invoked, this method will go back to
283
+ computing decoding in one step.
284
+ """
285
+ self.vae.disable_slicing()
286
+
287
+ def enable_sequential_cpu_offload(self, gpu_id=0):
288
+ r"""
289
+ Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet,
290
+ text_encoder, vae, controlnet, and safety checker have their state dicts saved to CPU and then are moved to a
291
+ `torch.device('meta') and loaded to GPU only when their specific submodule has its `forward` method called.
292
+ Note that offloading happens on a submodule basis. Memory savings are higher than with
293
+ `enable_model_cpu_offload`, but performance is lower.
294
+ """
295
+ if is_accelerate_available():
296
+ from accelerate import cpu_offload
297
+ else:
298
+ raise ImportError("Please install accelerate via `pip install accelerate`")
299
+
300
+ device = torch.device(f"cuda:{gpu_id}")
301
+
302
+ for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.controlnet]:
303
+ cpu_offload(cpu_offloaded_model, device)
304
+
305
+ if self.safety_checker is not None:
306
+ cpu_offload(self.safety_checker, execution_device=device, offload_buffers=True)
307
+
308
+ def enable_model_cpu_offload(self, gpu_id=0):
309
+ r"""
310
+ Offloads all models to CPU using accelerate, reducing memory usage with a low impact on performance. Compared
311
+ to `enable_sequential_cpu_offload`, this method moves one whole model at a time to the GPU when its `forward`
312
+ method is called, and the model remains in GPU until the next model runs. Memory savings are lower than with
313
+ `enable_sequential_cpu_offload`, but performance is much better due to the iterative execution of the `unet`.
314
+ """
315
+ if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"):
316
+ from accelerate import cpu_offload_with_hook
317
+ else:
318
+ raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.")
319
+
320
+ device = torch.device(f"cuda:{gpu_id}")
321
+
322
+ hook = None
323
+ for cpu_offloaded_model in [self.text_encoder, self.unet, self.vae]:
324
+ _, hook = cpu_offload_with_hook(cpu_offloaded_model, device, prev_module_hook=hook)
325
+
326
+ if self.safety_checker is not None:
327
+ # the safety checker can offload the vae again
328
+ _, hook = cpu_offload_with_hook(self.safety_checker, device, prev_module_hook=hook)
329
+
330
+ # control net hook has be manually offloaded as it alternates with unet
331
+ cpu_offload_with_hook(self.controlnet, device)
332
+
333
+ # We'll offload the last model manually.
334
+ self.final_offload_hook = hook
335
+
336
+ @property
337
+ def _execution_device(self):
338
+ r"""
339
+ Returns the device on which the pipeline's models will be executed. After calling
340
+ `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
341
+ hooks.
342
+ """
343
+ if not hasattr(self.unet, "_hf_hook"):
344
+ return self.device
345
+ for module in self.unet.modules():
346
+ if (
347
+ hasattr(module, "_hf_hook")
348
+ and hasattr(module._hf_hook, "execution_device")
349
+ and module._hf_hook.execution_device is not None
350
+ ):
351
+ return torch.device(module._hf_hook.execution_device)
352
+ return self.device
353
+
354
+ def _encode_prompt(
355
+ self,
356
+ prompt,
357
+ device,
358
+ num_images_per_prompt,
359
+ do_classifier_free_guidance,
360
+ negative_prompt=None,
361
+ prompt_embeds: Optional[torch.FloatTensor] = None,
362
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
363
+ ):
364
+ r"""
365
+ Encodes the prompt into text encoder hidden states.
366
+
367
+ Args:
368
+ prompt (`str` or `List[str]`, *optional*):
369
+ prompt to be encoded
370
+ device: (`torch.device`):
371
+ torch device
372
+ num_images_per_prompt (`int`):
373
+ number of images that should be generated per prompt
374
+ do_classifier_free_guidance (`bool`):
375
+ whether to use classifier free guidance or not
376
+ negative_prompt (`str` or `List[str]`, *optional*):
377
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass `negative_prompt_embeds` instead.
378
+ Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
379
+ prompt_embeds (`torch.FloatTensor`, *optional*):
380
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
381
+ provided, text embeddings will be generated from `prompt` input argument.
382
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
383
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
384
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
385
+ argument.
386
+ """
387
+ if prompt is not None and isinstance(prompt, str):
388
+ batch_size = 1
389
+ elif prompt is not None and isinstance(prompt, list):
390
+ batch_size = len(prompt)
391
+ else:
392
+ batch_size = prompt_embeds.shape[0]
393
+
394
+ if prompt_embeds is None:
395
+ text_inputs = self.tokenizer(
396
+ prompt,
397
+ padding="max_length",
398
+ max_length=self.tokenizer.model_max_length,
399
+ truncation=True,
400
+ return_tensors="pt",
401
+ )
402
+ text_input_ids = text_inputs.input_ids
403
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
404
+
405
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
406
+ text_input_ids, untruncated_ids
407
+ ):
408
+ removed_text = self.tokenizer.batch_decode(
409
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
410
+ )
411
+ logger.warning(
412
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
413
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
414
+ )
415
+
416
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
417
+ attention_mask = text_inputs.attention_mask.to(device)
418
+ else:
419
+ attention_mask = None
420
+
421
+ prompt_embeds = self.text_encoder(
422
+ text_input_ids.to(device),
423
+ attention_mask=attention_mask,
424
+ )
425
+ prompt_embeds = prompt_embeds[0]
426
+
427
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
428
+
429
+ bs_embed, seq_len, _ = prompt_embeds.shape
430
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
431
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
432
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
433
+
434
+ # get unconditional embeddings for classifier free guidance
435
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
436
+ uncond_tokens: List[str]
437
+ if negative_prompt is None:
438
+ uncond_tokens = [""] * batch_size
439
+ elif type(prompt) is not type(negative_prompt):
440
+ raise TypeError(
441
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
442
+ f" {type(prompt)}."
443
+ )
444
+ elif isinstance(negative_prompt, str):
445
+ uncond_tokens = [negative_prompt]
446
+ elif batch_size != len(negative_prompt):
447
+ raise ValueError(
448
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
449
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
450
+ " the batch size of `prompt`."
451
+ )
452
+ else:
453
+ uncond_tokens = negative_prompt
454
+
455
+ max_length = prompt_embeds.shape[1]
456
+ uncond_input = self.tokenizer(
457
+ uncond_tokens,
458
+ padding="max_length",
459
+ max_length=max_length,
460
+ truncation=True,
461
+ return_tensors="pt",
462
+ )
463
+
464
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
465
+ attention_mask = uncond_input.attention_mask.to(device)
466
+ else:
467
+ attention_mask = None
468
+
469
+ negative_prompt_embeds = self.text_encoder(
470
+ uncond_input.input_ids.to(device),
471
+ attention_mask=attention_mask,
472
+ )
473
+ negative_prompt_embeds = negative_prompt_embeds[0]
474
+
475
+ if do_classifier_free_guidance:
476
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
477
+ seq_len = negative_prompt_embeds.shape[1]
478
+
479
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
480
+
481
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
482
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
483
+
484
+ # For classifier free guidance, we need to do two forward passes.
485
+ # Here we concatenate the unconditional and text embeddings into a single batch
486
+ # to avoid doing two forward passes
487
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
488
+
489
+ return prompt_embeds
490
+
491
+ def run_safety_checker(self, image, device, dtype):
492
+ if self.safety_checker is not None:
493
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(device)
494
+ image, has_nsfw_concept = self.safety_checker(
495
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
496
+ )
497
+ else:
498
+ has_nsfw_concept = None
499
+ return image, has_nsfw_concept
500
+
501
+ def decode_latents(self, latents):
502
+ latents = 1 / self.vae.config.scaling_factor * latents
503
+ image = self.vae.decode(latents).sample
504
+ image = (image / 2 + 0.5).clamp(0, 1)
505
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
506
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
507
+ return image
508
+
509
+ def prepare_extra_step_kwargs(self, generator, eta):
510
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
511
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
512
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
513
+ # and should be between [0, 1]
514
+
515
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
516
+ extra_step_kwargs = {}
517
+ if accepts_eta:
518
+ extra_step_kwargs["eta"] = eta
519
+
520
+ # check if the scheduler accepts generator
521
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
522
+ if accepts_generator:
523
+ extra_step_kwargs["generator"] = generator
524
+ return extra_step_kwargs
525
+
526
+ def check_inputs(
527
+ self,
528
+ prompt,
529
+ image,
530
+ mask_image,
531
+ controlnet_conditioning_image,
532
+ height,
533
+ width,
534
+ callback_steps,
535
+ negative_prompt=None,
536
+ prompt_embeds=None,
537
+ negative_prompt_embeds=None,
538
+ ):
539
+ if height % 8 != 0 or width % 8 != 0:
540
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
541
+
542
+ if (callback_steps is None) or (
543
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
544
+ ):
545
+ raise ValueError(
546
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
547
+ f" {type(callback_steps)}."
548
+ )
549
+
550
+ if prompt is not None and prompt_embeds is not None:
551
+ raise ValueError(
552
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
553
+ " only forward one of the two."
554
+ )
555
+ elif prompt is None and prompt_embeds is None:
556
+ raise ValueError(
557
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
558
+ )
559
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
560
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
561
+
562
+ if negative_prompt is not None and negative_prompt_embeds is not None:
563
+ raise ValueError(
564
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
565
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
566
+ )
567
+
568
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
569
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
570
+ raise ValueError(
571
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
572
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
573
+ f" {negative_prompt_embeds.shape}."
574
+ )
575
+
576
+ controlnet_cond_image_is_pil = isinstance(controlnet_conditioning_image, PIL.Image.Image)
577
+ controlnet_cond_image_is_tensor = isinstance(controlnet_conditioning_image, torch.Tensor)
578
+ controlnet_cond_image_is_pil_list = isinstance(controlnet_conditioning_image, list) and isinstance(
579
+ controlnet_conditioning_image[0], PIL.Image.Image
580
+ )
581
+ controlnet_cond_image_is_tensor_list = isinstance(controlnet_conditioning_image, list) and isinstance(
582
+ controlnet_conditioning_image[0], torch.Tensor
583
+ )
584
+
585
+ if (
586
+ not controlnet_cond_image_is_pil
587
+ and not controlnet_cond_image_is_tensor
588
+ and not controlnet_cond_image_is_pil_list
589
+ and not controlnet_cond_image_is_tensor_list
590
+ ):
591
+ raise TypeError(
592
+ "image must be passed and be one of PIL image, torch tensor, list of PIL images, or list of torch tensors"
593
+ )
594
+
595
+ if controlnet_cond_image_is_pil:
596
+ controlnet_cond_image_batch_size = 1
597
+ elif controlnet_cond_image_is_tensor:
598
+ controlnet_cond_image_batch_size = controlnet_conditioning_image.shape[0]
599
+ elif controlnet_cond_image_is_pil_list:
600
+ controlnet_cond_image_batch_size = len(controlnet_conditioning_image)
601
+ elif controlnet_cond_image_is_tensor_list:
602
+ controlnet_cond_image_batch_size = len(controlnet_conditioning_image)
603
+
604
+ if prompt is not None and isinstance(prompt, str):
605
+ prompt_batch_size = 1
606
+ elif prompt is not None and isinstance(prompt, list):
607
+ prompt_batch_size = len(prompt)
608
+ elif prompt_embeds is not None:
609
+ prompt_batch_size = prompt_embeds.shape[0]
610
+
611
+ if controlnet_cond_image_batch_size != 1 and controlnet_cond_image_batch_size != prompt_batch_size:
612
+ raise ValueError(
613
+ f"If image batch size is not 1, image batch size must be same as prompt batch size. image batch size: {controlnet_cond_image_batch_size}, prompt batch size: {prompt_batch_size}"
614
+ )
615
+
616
+ if isinstance(image, torch.Tensor) and not isinstance(mask_image, torch.Tensor):
617
+ raise TypeError("if `image` is a tensor, `mask_image` must also be a tensor")
618
+
619
+ if isinstance(image, PIL.Image.Image) and not isinstance(mask_image, PIL.Image.Image):
620
+ raise TypeError("if `image` is a PIL image, `mask_image` must also be a PIL image")
621
+
622
+ if isinstance(image, torch.Tensor):
623
+ if image.ndim != 3 and image.ndim != 4:
624
+ raise ValueError("`image` must have 3 or 4 dimensions")
625
+
626
+ if mask_image.ndim != 2 and mask_image.ndim != 3 and mask_image.ndim != 4:
627
+ raise ValueError("`mask_image` must have 2, 3, or 4 dimensions")
628
+
629
+ if image.ndim == 3:
630
+ image_batch_size = 1
631
+ image_channels, image_height, image_width = image.shape
632
+ elif image.ndim == 4:
633
+ image_batch_size, image_channels, image_height, image_width = image.shape
634
+
635
+ if mask_image.ndim == 2:
636
+ mask_image_batch_size = 1
637
+ mask_image_channels = 1
638
+ mask_image_height, mask_image_width = mask_image.shape
639
+ elif mask_image.ndim == 3:
640
+ mask_image_channels = 1
641
+ mask_image_batch_size, mask_image_height, mask_image_width = mask_image.shape
642
+ elif mask_image.ndim == 4:
643
+ mask_image_batch_size, mask_image_channels, mask_image_height, mask_image_width = mask_image.shape
644
+
645
+ if image_channels != 3:
646
+ raise ValueError("`image` must have 3 channels")
647
+
648
+ if mask_image_channels != 1:
649
+ raise ValueError("`mask_image` must have 1 channel")
650
+
651
+ if image_batch_size != mask_image_batch_size:
652
+ raise ValueError("`image` and `mask_image` mush have the same batch sizes")
653
+
654
+ if image_height != mask_image_height or image_width != mask_image_width:
655
+ raise ValueError("`image` and `mask_image` must have the same height and width dimensions")
656
+
657
+ if image.min() < -1 or image.max() > 1:
658
+ raise ValueError("`image` should be in range [-1, 1]")
659
+
660
+ if mask_image.min() < 0 or mask_image.max() > 1:
661
+ raise ValueError("`mask_image` should be in range [0, 1]")
662
+ else:
663
+ mask_image_channels = 1
664
+ image_channels = 3
665
+
666
+ single_image_latent_channels = self.vae.config.latent_channels
667
+
668
+ total_latent_channels = single_image_latent_channels * 2 + mask_image_channels
669
+
670
+ if total_latent_channels != self.unet.config.in_channels:
671
+ raise ValueError(
672
+ f"The config of `pipeline.unet` expects {self.unet.config.in_channels} but received"
673
+ f" non inpainting latent channels: {single_image_latent_channels},"
674
+ f" mask channels: {mask_image_channels}, and masked image channels: {single_image_latent_channels}."
675
+ f" Please verify the config of `pipeline.unet` and the `mask_image` and `image` inputs."
676
+ )
677
+
678
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
679
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
680
+ if isinstance(generator, list) and len(generator) != batch_size:
681
+ raise ValueError(
682
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
683
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
684
+ )
685
+
686
+ if latents is None:
687
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
688
+ else:
689
+ latents = latents.to(device)
690
+
691
+ # scale the initial noise by the standard deviation required by the scheduler
692
+ latents = latents * self.scheduler.init_noise_sigma
693
+
694
+ return latents
695
+
696
+ def prepare_mask_latents(self, mask_image, batch_size, height, width, dtype, device, do_classifier_free_guidance):
697
+ # resize the mask to latents shape as we concatenate the mask to the latents
698
+ # we do that before converting to dtype to avoid breaking in case we're using cpu_offload
699
+ # and half precision
700
+ mask_image = F.interpolate(mask_image, size=(height // self.vae_scale_factor, width // self.vae_scale_factor))
701
+ mask_image = mask_image.to(device=device, dtype=dtype)
702
+
703
+ # duplicate mask for each generation per prompt, using mps friendly method
704
+ if mask_image.shape[0] < batch_size:
705
+ if not batch_size % mask_image.shape[0] == 0:
706
+ raise ValueError(
707
+ "The passed mask and the required batch size don't match. Masks are supposed to be duplicated to"
708
+ f" a total batch size of {batch_size}, but {mask_image.shape[0]} masks were passed. Make sure the number"
709
+ " of masks that you pass is divisible by the total requested batch size."
710
+ )
711
+ mask_image = mask_image.repeat(batch_size // mask_image.shape[0], 1, 1, 1)
712
+
713
+ mask_image = torch.cat([mask_image] * 2) if do_classifier_free_guidance else mask_image
714
+
715
+ mask_image_latents = mask_image
716
+
717
+ return mask_image_latents
718
+
719
+ def prepare_masked_image_latents(
720
+ self, masked_image, batch_size, height, width, dtype, device, generator, do_classifier_free_guidance
721
+ ):
722
+ masked_image = masked_image.to(device=device, dtype=dtype)
723
+
724
+ # encode the mask image into latents space so we can concatenate it to the latents
725
+ if isinstance(generator, list):
726
+ masked_image_latents = [
727
+ self.vae.encode(masked_image[i : i + 1]).latent_dist.sample(generator=generator[i])
728
+ for i in range(batch_size)
729
+ ]
730
+ masked_image_latents = torch.cat(masked_image_latents, dim=0)
731
+ else:
732
+ masked_image_latents = self.vae.encode(masked_image).latent_dist.sample(generator=generator)
733
+ masked_image_latents = self.vae.config.scaling_factor * masked_image_latents
734
+
735
+ # duplicate masked_image_latents for each generation per prompt, using mps friendly method
736
+ if masked_image_latents.shape[0] < batch_size:
737
+ if not batch_size % masked_image_latents.shape[0] == 0:
738
+ raise ValueError(
739
+ "The passed images and the required batch size don't match. Images are supposed to be duplicated"
740
+ f" to a total batch size of {batch_size}, but {masked_image_latents.shape[0]} images were passed."
741
+ " Make sure the number of images that you pass is divisible by the total requested batch size."
742
+ )
743
+ masked_image_latents = masked_image_latents.repeat(batch_size // masked_image_latents.shape[0], 1, 1, 1)
744
+
745
+ masked_image_latents = (
746
+ torch.cat([masked_image_latents] * 2) if do_classifier_free_guidance else masked_image_latents
747
+ )
748
+
749
+ # aligning device to prevent device errors when concating it with the latent model input
750
+ masked_image_latents = masked_image_latents.to(device=device, dtype=dtype)
751
+ return masked_image_latents
752
+
753
+ def _default_height_width(self, height, width, image):
754
+ if isinstance(image, list):
755
+ image = image[0]
756
+
757
+ if height is None:
758
+ if isinstance(image, PIL.Image.Image):
759
+ height = image.height
760
+ elif isinstance(image, torch.Tensor):
761
+ height = image.shape[3]
762
+
763
+ height = (height // 8) * 8 # round down to nearest multiple of 8
764
+
765
+ if width is None:
766
+ if isinstance(image, PIL.Image.Image):
767
+ width = image.width
768
+ elif isinstance(image, torch.Tensor):
769
+ width = image.shape[2]
770
+
771
+ width = (width // 8) * 8 # round down to nearest multiple of 8
772
+
773
+ return height, width
774
+
775
+ @torch.no_grad()
776
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
777
+ def __call__(
778
+ self,
779
+ prompt: Union[str, List[str]] = None,
780
+ image: Union[torch.Tensor, PIL.Image.Image] = None,
781
+ mask_image: Union[torch.Tensor, PIL.Image.Image] = None,
782
+ controlnet_conditioning_image: Union[
783
+ torch.FloatTensor, PIL.Image.Image, List[torch.FloatTensor], List[PIL.Image.Image]
784
+ ] = None,
785
+ height: Optional[int] = None,
786
+ width: Optional[int] = None,
787
+ num_inference_steps: int = 50,
788
+ guidance_scale: float = 7.5,
789
+ negative_prompt: Optional[Union[str, List[str]]] = None,
790
+ num_images_per_prompt: Optional[int] = 1,
791
+ eta: float = 0.0,
792
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
793
+ latents: Optional[torch.FloatTensor] = None,
794
+ prompt_embeds: Optional[torch.FloatTensor] = None,
795
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
796
+ output_type: Optional[str] = "pil",
797
+ return_dict: bool = True,
798
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
799
+ callback_steps: int = 1,
800
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
801
+ controlnet_conditioning_scale: float = 1.0,
802
+ ):
803
+ r"""
804
+ Function invoked when calling the pipeline for generation.
805
+
806
+ Args:
807
+ prompt (`str` or `List[str]`, *optional*):
808
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
809
+ instead.
810
+ image (`torch.Tensor` or `PIL.Image.Image`):
811
+ `Image`, or tensor representing an image batch which will be inpainted, *i.e.* parts of the image will
812
+ be masked out with `mask_image` and repainted according to `prompt`.
813
+ mask_image (`torch.Tensor` or `PIL.Image.Image`):
814
+ `Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be
815
+ repainted, while black pixels will be preserved. If `mask_image` is a PIL image, it will be converted
816
+ to a single channel (luminance) before use. If it's a tensor, it should contain one color channel (L)
817
+ instead of 3, so the expected shape would be `(B, H, W, 1)`.
818
+ controlnet_conditioning_image (`torch.FloatTensor`, `PIL.Image.Image`, `List[torch.FloatTensor]` or `List[PIL.Image.Image]`):
819
+ The ControlNet input condition. ControlNet uses this input condition to generate guidance to Unet. If
820
+ the type is specified as `Torch.FloatTensor`, it is passed to ControlNet as is. PIL.Image.Image` can
821
+ also be accepted as an image. The control image is automatically resized to fit the output image.
822
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
823
+ The height in pixels of the generated image.
824
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
825
+ The width in pixels of the generated image.
826
+ num_inference_steps (`int`, *optional*, defaults to 50):
827
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
828
+ expense of slower inference.
829
+ guidance_scale (`float`, *optional*, defaults to 7.5):
830
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
831
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
832
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
833
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
834
+ usually at the expense of lower image quality.
835
+ negative_prompt (`str` or `List[str]`, *optional*):
836
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass `negative_prompt_embeds` instead.
837
+ Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
838
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
839
+ The number of images to generate per prompt.
840
+ eta (`float`, *optional*, defaults to 0.0):
841
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
842
+ [`schedulers.DDIMScheduler`], will be ignored for others.
843
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
844
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
845
+ to make generation deterministic.
846
+ latents (`torch.FloatTensor`, *optional*):
847
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
848
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
849
+ tensor will ge generated by sampling using the supplied random `generator`.
850
+ prompt_embeds (`torch.FloatTensor`, *optional*):
851
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
852
+ provided, text embeddings will be generated from `prompt` input argument.
853
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
854
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
855
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
856
+ argument.
857
+ output_type (`str`, *optional*, defaults to `"pil"`):
858
+ The output format of the generate image. Choose between
859
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
860
+ return_dict (`bool`, *optional*, defaults to `True`):
861
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
862
+ plain tuple.
863
+ callback (`Callable`, *optional*):
864
+ A function that will be called every `callback_steps` steps during inference. The function will be
865
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
866
+ callback_steps (`int`, *optional*, defaults to 1):
867
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
868
+ called at every step.
869
+ cross_attention_kwargs (`dict`, *optional*):
870
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
871
+ `self.processor` in
872
+ [diffusers.cross_attention](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py).
873
+ controlnet_conditioning_scale (`float`, *optional*, defaults to 1.0):
874
+ The outputs of the controlnet are multiplied by `controlnet_conditioning_scale` before they are added
875
+ to the residual in the original unet.
876
+
877
+ Examples:
878
+
879
+ Returns:
880
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
881
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
882
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
883
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
884
+ (nsfw) content, according to the `safety_checker`.
885
+ """
886
+ # 0. Default height and width to unet
887
+ height, width = self._default_height_width(height, width, controlnet_conditioning_image)
888
+
889
+ # 1. Check inputs. Raise error if not correct
890
+ self.check_inputs(
891
+ prompt,
892
+ image,
893
+ mask_image,
894
+ controlnet_conditioning_image,
895
+ height,
896
+ width,
897
+ callback_steps,
898
+ negative_prompt,
899
+ prompt_embeds,
900
+ negative_prompt_embeds,
901
+ )
902
+
903
+ # 2. Define call parameters
904
+ if prompt is not None and isinstance(prompt, str):
905
+ batch_size = 1
906
+ elif prompt is not None and isinstance(prompt, list):
907
+ batch_size = len(prompt)
908
+ else:
909
+ batch_size = prompt_embeds.shape[0]
910
+
911
+ device = self._execution_device
912
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
913
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
914
+ # corresponds to doing no classifier free guidance.
915
+ do_classifier_free_guidance = guidance_scale > 1.0
916
+
917
+ # 3. Encode input prompt
918
+ prompt_embeds = self._encode_prompt(
919
+ prompt,
920
+ device,
921
+ num_images_per_prompt,
922
+ do_classifier_free_guidance,
923
+ negative_prompt,
924
+ prompt_embeds=prompt_embeds,
925
+ negative_prompt_embeds=negative_prompt_embeds,
926
+ )
927
+
928
+ # 4. Prepare mask, image, and controlnet_conditioning_image
929
+ image = prepare_image(image)
930
+
931
+ mask_image = prepare_mask_image(mask_image)
932
+
933
+ controlnet_conditioning_image = prepare_controlnet_conditioning_image(
934
+ controlnet_conditioning_image,
935
+ width,
936
+ height,
937
+ batch_size * num_images_per_prompt,
938
+ num_images_per_prompt,
939
+ device,
940
+ self.controlnet.dtype,
941
+ )
942
+
943
+ masked_image = image * (mask_image < 0.5)
944
+
945
+ # 5. Prepare timesteps
946
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
947
+ timesteps = self.scheduler.timesteps
948
+
949
+ # 6. Prepare latent variables
950
+ num_channels_latents = self.vae.config.latent_channels
951
+ latents = self.prepare_latents(
952
+ batch_size * num_images_per_prompt,
953
+ num_channels_latents,
954
+ height,
955
+ width,
956
+ prompt_embeds.dtype,
957
+ device,
958
+ generator,
959
+ latents,
960
+ )
961
+
962
+ mask_image_latents = self.prepare_mask_latents(
963
+ mask_image,
964
+ batch_size * num_images_per_prompt,
965
+ height,
966
+ width,
967
+ prompt_embeds.dtype,
968
+ device,
969
+ do_classifier_free_guidance,
970
+ )
971
+
972
+ masked_image_latents = self.prepare_masked_image_latents(
973
+ masked_image,
974
+ batch_size * num_images_per_prompt,
975
+ height,
976
+ width,
977
+ prompt_embeds.dtype,
978
+ device,
979
+ generator,
980
+ do_classifier_free_guidance,
981
+ )
982
+
983
+ if do_classifier_free_guidance:
984
+ controlnet_conditioning_image = torch.cat([controlnet_conditioning_image] * 2)
985
+
986
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
987
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
988
+
989
+ # 8. Denoising loop
990
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
991
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
992
+ for i, t in enumerate(timesteps):
993
+ # expand the latents if we are doing classifier free guidance
994
+ non_inpainting_latent_model_input = (
995
+ torch.cat([latents] * 2) if do_classifier_free_guidance else latents
996
+ )
997
+
998
+ non_inpainting_latent_model_input = self.scheduler.scale_model_input(
999
+ non_inpainting_latent_model_input, t
1000
+ )
1001
+
1002
+ inpainting_latent_model_input = torch.cat(
1003
+ [non_inpainting_latent_model_input, mask_image_latents, masked_image_latents], dim=1
1004
+ )
1005
+
1006
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
1007
+ non_inpainting_latent_model_input,
1008
+ t,
1009
+ encoder_hidden_states=prompt_embeds,
1010
+ controlnet_cond=controlnet_conditioning_image,
1011
+ return_dict=False,
1012
+ )
1013
+
1014
+ down_block_res_samples = [
1015
+ down_block_res_sample * controlnet_conditioning_scale
1016
+ for down_block_res_sample in down_block_res_samples
1017
+ ]
1018
+ mid_block_res_sample *= controlnet_conditioning_scale
1019
+
1020
+ # predict the noise residual
1021
+ noise_pred = self.unet(
1022
+ inpainting_latent_model_input,
1023
+ t,
1024
+ encoder_hidden_states=prompt_embeds,
1025
+ cross_attention_kwargs=cross_attention_kwargs,
1026
+ down_block_additional_residuals=down_block_res_samples,
1027
+ mid_block_additional_residual=mid_block_res_sample,
1028
+ ).sample
1029
+
1030
+ # perform guidance
1031
+ if do_classifier_free_guidance:
1032
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1033
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1034
+
1035
+ # compute the previous noisy sample x_t -> x_t-1
1036
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
1037
+
1038
+ # call the callback, if provided
1039
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1040
+ progress_bar.update()
1041
+ if callback is not None and i % callback_steps == 0:
1042
+ callback(i, t, latents)
1043
+
1044
+ # If we do sequential model offloading, let's offload unet and controlnet
1045
+ # manually for max memory savings
1046
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
1047
+ self.unet.to("cpu")
1048
+ self.controlnet.to("cpu")
1049
+ torch.cuda.empty_cache()
1050
+
1051
+ if output_type == "latent":
1052
+ image = latents
1053
+ has_nsfw_concept = None
1054
+ elif output_type == "pil":
1055
+ # 8. Post-processing
1056
+ image = self.decode_latents(latents)
1057
+
1058
+ # 9. Run safety checker
1059
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
1060
+
1061
+ # 10. Convert to PIL
1062
+ image = self.numpy_to_pil(image)
1063
+ else:
1064
+ # 8. Post-processing
1065
+ image = self.decode_latents(latents)
1066
+
1067
+ # 9. Run safety checker
1068
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
1069
+
1070
+ # Offload last model to CPU
1071
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
1072
+ self.final_offload_hook.offload()
1073
+
1074
+ if not return_dict:
1075
+ return (image, has_nsfw_concept)
1076
+
1077
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
requirements.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ torchvision
3
+ diffusers
4
+ git+https://github.com/facebookresearch/segment-anything.git
5
+ opencv-python
6
+ pycocotools
7
+ matplotlib
8
+ onnxruntime
9
+ onnx
10
+ transformers
11
+ accelerate
12
+ xformers
sam_vit_h_4b8939.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a7bf3b02f3ebf1267aba913ff637d9a2d5c33d3173bb679e46d9f338c26f262e
3
+ size 2564550879