Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
shivamshrirao
GitHub Repository: shivamshrirao/diffusers
Path: blob/main/examples/community/text_inpainting.py
1448 views
1
from typing import Callable, List, Optional, Union
2
3
import PIL
4
import torch
5
from transformers import (
6
CLIPImageProcessor,
7
CLIPSegForImageSegmentation,
8
CLIPSegProcessor,
9
CLIPTextModel,
10
CLIPTokenizer,
11
)
12
13
from diffusers import DiffusionPipeline
14
from diffusers.configuration_utils import FrozenDict
15
from diffusers.models import AutoencoderKL, UNet2DConditionModel
16
from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline
17
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
18
from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
19
from diffusers.utils import deprecate, is_accelerate_available, logging
20
21
22
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
23
24
25
class TextInpainting(DiffusionPipeline):
26
r"""
27
Pipeline for text based inpainting using Stable Diffusion.
28
Uses CLIPSeg to get a mask from the given text, then calls the Inpainting pipeline with the generated mask
29
30
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
31
library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
32
33
Args:
34
segmentation_model ([`CLIPSegForImageSegmentation`]):
35
CLIPSeg Model to generate mask from the given text. Please refer to the [model card]() for details.
36
segmentation_processor ([`CLIPSegProcessor`]):
37
CLIPSeg processor to get image, text features to translate prompt to English, if necessary. Please refer to the
38
[model card](https://huggingface.co/docs/transformers/model_doc/clipseg) for details.
39
vae ([`AutoencoderKL`]):
40
Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
41
text_encoder ([`CLIPTextModel`]):
42
Frozen text-encoder. Stable Diffusion uses the text portion of
43
[CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
44
the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
45
tokenizer (`CLIPTokenizer`):
46
Tokenizer of class
47
[CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
48
unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
49
scheduler ([`SchedulerMixin`]):
50
A scheduler to be used in combination with `unet` to denoise the encoded image latens. Can be one of
51
[`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
52
safety_checker ([`StableDiffusionSafetyChecker`]):
53
Classification module that estimates whether generated images could be considered offensive or harmful.
54
Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
55
feature_extractor ([`CLIPImageProcessor`]):
56
Model that extracts features from generated images to be used as inputs for the `safety_checker`.
57
"""
58
59
def __init__(
60
self,
61
segmentation_model: CLIPSegForImageSegmentation,
62
segmentation_processor: CLIPSegProcessor,
63
vae: AutoencoderKL,
64
text_encoder: CLIPTextModel,
65
tokenizer: CLIPTokenizer,
66
unet: UNet2DConditionModel,
67
scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
68
safety_checker: StableDiffusionSafetyChecker,
69
feature_extractor: CLIPImageProcessor,
70
):
71
super().__init__()
72
73
if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
74
deprecation_message = (
75
f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
76
f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
77
"to update the config accordingly as leaving `steps_offset` might led to incorrect results"
78
" in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
79
" it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
80
" file"
81
)
82
deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
83
new_config = dict(scheduler.config)
84
new_config["steps_offset"] = 1
85
scheduler._internal_dict = FrozenDict(new_config)
86
87
if hasattr(scheduler.config, "skip_prk_steps") and scheduler.config.skip_prk_steps is False:
88
deprecation_message = (
89
f"The configuration file of this scheduler: {scheduler} has not set the configuration"
90
" `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make"
91
" sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to"
92
" incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face"
93
" Hub, it would be very nice if you could open a Pull request for the"
94
" `scheduler/scheduler_config.json` file"
95
)
96
deprecate("skip_prk_steps not set", "1.0.0", deprecation_message, standard_warn=False)
97
new_config = dict(scheduler.config)
98
new_config["skip_prk_steps"] = True
99
scheduler._internal_dict = FrozenDict(new_config)
100
101
if safety_checker is None:
102
logger.warning(
103
f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
104
" that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
105
" results in services or applications open to the public. Both the diffusers team and Hugging Face"
106
" strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
107
" it only for use-cases that involve analyzing network behavior or auditing its results. For more"
108
" information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
109
)
110
111
self.register_modules(
112
segmentation_model=segmentation_model,
113
segmentation_processor=segmentation_processor,
114
vae=vae,
115
text_encoder=text_encoder,
116
tokenizer=tokenizer,
117
unet=unet,
118
scheduler=scheduler,
119
safety_checker=safety_checker,
120
feature_extractor=feature_extractor,
121
)
122
123
def enable_attention_slicing(self, slice_size: Optional[Union[str, int]] = "auto"):
124
r"""
125
Enable sliced attention computation.
126
127
When this option is enabled, the attention module will split the input tensor in slices, to compute attention
128
in several steps. This is useful to save some memory in exchange for a small speed decrease.
129
130
Args:
131
slice_size (`str` or `int`, *optional*, defaults to `"auto"`):
132
When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
133
a number is provided, uses as many slices as `attention_head_dim // slice_size`. In this case,
134
`attention_head_dim` must be a multiple of `slice_size`.
135
"""
136
if slice_size == "auto":
137
# half the attention head size is usually a good trade-off between
138
# speed and memory
139
slice_size = self.unet.config.attention_head_dim // 2
140
self.unet.set_attention_slice(slice_size)
141
142
def disable_attention_slicing(self):
143
r"""
144
Disable sliced attention computation. If `enable_attention_slicing` was previously invoked, this method will go
145
back to computing attention in one step.
146
"""
147
# set slice_size = `None` to disable `attention slicing`
148
self.enable_attention_slicing(None)
149
150
def enable_sequential_cpu_offload(self):
151
r"""
152
Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet,
153
text_encoder, vae and safety checker have their state dicts saved to CPU and then are moved to a
154
`torch.device('meta') and loaded to GPU only when their specific submodule has its `forward` method called.
155
"""
156
if is_accelerate_available():
157
from accelerate import cpu_offload
158
else:
159
raise ImportError("Please install accelerate via `pip install accelerate`")
160
161
device = torch.device("cuda")
162
163
for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]:
164
if cpu_offloaded_model is not None:
165
cpu_offload(cpu_offloaded_model, device)
166
167
@property
168
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
169
def _execution_device(self):
170
r"""
171
Returns the device on which the pipeline's models will be executed. After calling
172
`pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
173
hooks.
174
"""
175
if self.device != torch.device("meta") or not hasattr(self.unet, "_hf_hook"):
176
return self.device
177
for module in self.unet.modules():
178
if (
179
hasattr(module, "_hf_hook")
180
and hasattr(module._hf_hook, "execution_device")
181
and module._hf_hook.execution_device is not None
182
):
183
return torch.device(module._hf_hook.execution_device)
184
return self.device
185
186
@torch.no_grad()
187
def __call__(
188
self,
189
prompt: Union[str, List[str]],
190
image: Union[torch.FloatTensor, PIL.Image.Image],
191
text: str,
192
height: int = 512,
193
width: int = 512,
194
num_inference_steps: int = 50,
195
guidance_scale: float = 7.5,
196
negative_prompt: Optional[Union[str, List[str]]] = None,
197
num_images_per_prompt: Optional[int] = 1,
198
eta: float = 0.0,
199
generator: Optional[torch.Generator] = None,
200
latents: Optional[torch.FloatTensor] = None,
201
output_type: Optional[str] = "pil",
202
return_dict: bool = True,
203
callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
204
callback_steps: int = 1,
205
**kwargs,
206
):
207
r"""
208
Function invoked when calling the pipeline for generation.
209
210
Args:
211
prompt (`str` or `List[str]`):
212
The prompt or prompts to guide the image generation.
213
image (`PIL.Image.Image`):
214
`Image`, or tensor representing an image batch which will be inpainted, *i.e.* parts of the image will
215
be masked out with `mask_image` and repainted according to `prompt`.
216
text (`str``):
217
The text to use to generate the mask.
218
height (`int`, *optional*, defaults to 512):
219
The height in pixels of the generated image.
220
width (`int`, *optional*, defaults to 512):
221
The width in pixels of the generated image.
222
num_inference_steps (`int`, *optional*, defaults to 50):
223
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
224
expense of slower inference.
225
guidance_scale (`float`, *optional*, defaults to 7.5):
226
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
227
`guidance_scale` is defined as `w` of equation 2. of [Imagen
228
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
229
1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
230
usually at the expense of lower image quality.
231
negative_prompt (`str` or `List[str]`, *optional*):
232
The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
233
if `guidance_scale` is less than `1`).
234
num_images_per_prompt (`int`, *optional*, defaults to 1):
235
The number of images to generate per prompt.
236
eta (`float`, *optional*, defaults to 0.0):
237
Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
238
[`schedulers.DDIMScheduler`], will be ignored for others.
239
generator (`torch.Generator`, *optional*):
240
A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
241
deterministic.
242
latents (`torch.FloatTensor`, *optional*):
243
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
244
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
245
tensor will ge generated by sampling using the supplied random `generator`.
246
output_type (`str`, *optional*, defaults to `"pil"`):
247
The output format of the generate image. Choose between
248
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
249
return_dict (`bool`, *optional*, defaults to `True`):
250
Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
251
plain tuple.
252
callback (`Callable`, *optional*):
253
A function that will be called every `callback_steps` steps during inference. The function will be
254
called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
255
callback_steps (`int`, *optional*, defaults to 1):
256
The frequency at which the `callback` function will be called. If not specified, the callback will be
257
called at every step.
258
259
Returns:
260
[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
261
[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
262
When returning a tuple, the first element is a list with the generated images, and the second element is a
263
list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
264
(nsfw) content, according to the `safety_checker`.
265
"""
266
267
# We use the input text to generate the mask
268
inputs = self.segmentation_processor(
269
text=[text], images=[image], padding="max_length", return_tensors="pt"
270
).to(self.device)
271
outputs = self.segmentation_model(**inputs)
272
mask = torch.sigmoid(outputs.logits).cpu().detach().unsqueeze(-1).numpy()
273
mask_pil = self.numpy_to_pil(mask)[0].resize(image.size)
274
275
# Run inpainting pipeline with the generated mask
276
inpainting_pipeline = StableDiffusionInpaintPipeline(
277
vae=self.vae,
278
text_encoder=self.text_encoder,
279
tokenizer=self.tokenizer,
280
unet=self.unet,
281
scheduler=self.scheduler,
282
safety_checker=self.safety_checker,
283
feature_extractor=self.feature_extractor,
284
)
285
return inpainting_pipeline(
286
prompt=prompt,
287
image=image,
288
mask_image=mask_pil,
289
height=height,
290
width=width,
291
num_inference_steps=num_inference_steps,
292
guidance_scale=guidance_scale,
293
negative_prompt=negative_prompt,
294
num_images_per_prompt=num_images_per_prompt,
295
eta=eta,
296
generator=generator,
297
latents=latents,
298
output_type=output_type,
299
return_dict=return_dict,
300
callback=callback,
301
callback_steps=callback_steps,
302
)
303
304