nikunjkdtechnoland commited on
Commit
cbbdd92
1 Parent(s): 4b98c85

some more add more file

Browse files
iopaint/model/power_paint/powerpaint_tokenizer.py ADDED
@@ -0,0 +1,540 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import copy
4
+ import random
5
+ from typing import Any, List, Optional, Union
6
+ from transformers import CLIPTokenizer
7
+
8
+ from iopaint.schema import PowerPaintTask
9
+
10
+
11
+ def add_task_to_prompt(prompt, negative_prompt, task: PowerPaintTask):
12
+ if task == PowerPaintTask.object_remove:
13
+ promptA = prompt + " P_ctxt"
14
+ promptB = prompt + " P_ctxt"
15
+ negative_promptA = negative_prompt + " P_obj"
16
+ negative_promptB = negative_prompt + " P_obj"
17
+ elif task == PowerPaintTask.shape_guided:
18
+ promptA = prompt + " P_shape"
19
+ promptB = prompt + " P_ctxt"
20
+ negative_promptA = negative_prompt
21
+ negative_promptB = negative_prompt
22
+ elif task == PowerPaintTask.outpainting:
23
+ promptA = prompt + " P_ctxt"
24
+ promptB = prompt + " P_ctxt"
25
+ negative_promptA = negative_prompt + " P_obj"
26
+ negative_promptB = negative_prompt + " P_obj"
27
+ else:
28
+ promptA = prompt + " P_obj"
29
+ promptB = prompt + " P_obj"
30
+ negative_promptA = negative_prompt
31
+ negative_promptB = negative_prompt
32
+
33
+ return promptA, promptB, negative_promptA, negative_promptB
34
+
35
+
36
+ class PowerPaintTokenizer:
37
+ def __init__(self, tokenizer: CLIPTokenizer):
38
+ self.wrapped = tokenizer
39
+ self.token_map = {}
40
+ placeholder_tokens = ["P_ctxt", "P_shape", "P_obj"]
41
+ num_vec_per_token = 10
42
+ for placeholder_token in placeholder_tokens:
43
+ output = []
44
+ for i in range(num_vec_per_token):
45
+ ith_token = placeholder_token + f"_{i}"
46
+ output.append(ith_token)
47
+ self.token_map[placeholder_token] = output
48
+
49
+ def __getattr__(self, name: str) -> Any:
50
+ if name == "wrapped":
51
+ return super().__getattr__("wrapped")
52
+
53
+ try:
54
+ return getattr(self.wrapped, name)
55
+ except AttributeError:
56
+ try:
57
+ return super().__getattr__(name)
58
+ except AttributeError:
59
+ raise AttributeError(
60
+ "'name' cannot be found in both "
61
+ f"'{self.__class__.__name__}' and "
62
+ f"'{self.__class__.__name__}.tokenizer'."
63
+ )
64
+
65
+ def try_adding_tokens(self, tokens: Union[str, List[str]], *args, **kwargs):
66
+ """Attempt to add tokens to the tokenizer.
67
+
68
+ Args:
69
+ tokens (Union[str, List[str]]): The tokens to be added.
70
+ """
71
+ num_added_tokens = self.wrapped.add_tokens(tokens, *args, **kwargs)
72
+ assert num_added_tokens != 0, (
73
+ f"The tokenizer already contains the token {tokens}. Please pass "
74
+ "a different `placeholder_token` that is not already in the "
75
+ "tokenizer."
76
+ )
77
+
78
+ def get_token_info(self, token: str) -> dict:
79
+ """Get the information of a token, including its start and end index in
80
+ the current tokenizer.
81
+
82
+ Args:
83
+ token (str): The token to be queried.
84
+
85
+ Returns:
86
+ dict: The information of the token, including its start and end
87
+ index in current tokenizer.
88
+ """
89
+ token_ids = self.__call__(token).input_ids
90
+ start, end = token_ids[1], token_ids[-2] + 1
91
+ return {"name": token, "start": start, "end": end}
92
+
93
+ def add_placeholder_token(
94
+ self, placeholder_token: str, *args, num_vec_per_token: int = 1, **kwargs
95
+ ):
96
+ """Add placeholder tokens to the tokenizer.
97
+
98
+ Args:
99
+ placeholder_token (str): The placeholder token to be added.
100
+ num_vec_per_token (int, optional): The number of vectors of
101
+ the added placeholder token.
102
+ *args, **kwargs: The arguments for `self.wrapped.add_tokens`.
103
+ """
104
+ output = []
105
+ if num_vec_per_token == 1:
106
+ self.try_adding_tokens(placeholder_token, *args, **kwargs)
107
+ output.append(placeholder_token)
108
+ else:
109
+ output = []
110
+ for i in range(num_vec_per_token):
111
+ ith_token = placeholder_token + f"_{i}"
112
+ self.try_adding_tokens(ith_token, *args, **kwargs)
113
+ output.append(ith_token)
114
+
115
+ for token in self.token_map:
116
+ if token in placeholder_token:
117
+ raise ValueError(
118
+ f"The tokenizer already has placeholder token {token} "
119
+ f"that can get confused with {placeholder_token} "
120
+ "keep placeholder tokens independent"
121
+ )
122
+ self.token_map[placeholder_token] = output
123
+
124
+ def replace_placeholder_tokens_in_text(
125
+ self,
126
+ text: Union[str, List[str]],
127
+ vector_shuffle: bool = False,
128
+ prop_tokens_to_load: float = 1.0,
129
+ ) -> Union[str, List[str]]:
130
+ """Replace the keywords in text with placeholder tokens. This function
131
+ will be called in `self.__call__` and `self.encode`.
132
+
133
+ Args:
134
+ text (Union[str, List[str]]): The text to be processed.
135
+ vector_shuffle (bool, optional): Whether to shuffle the vectors.
136
+ Defaults to False.
137
+ prop_tokens_to_load (float, optional): The proportion of tokens to
138
+ be loaded. If 1.0, all tokens will be loaded. Defaults to 1.0.
139
+
140
+ Returns:
141
+ Union[str, List[str]]: The processed text.
142
+ """
143
+ if isinstance(text, list):
144
+ output = []
145
+ for i in range(len(text)):
146
+ output.append(
147
+ self.replace_placeholder_tokens_in_text(
148
+ text[i], vector_shuffle=vector_shuffle
149
+ )
150
+ )
151
+ return output
152
+
153
+ for placeholder_token in self.token_map:
154
+ if placeholder_token in text:
155
+ tokens = self.token_map[placeholder_token]
156
+ tokens = tokens[: 1 + int(len(tokens) * prop_tokens_to_load)]
157
+ if vector_shuffle:
158
+ tokens = copy.copy(tokens)
159
+ random.shuffle(tokens)
160
+ text = text.replace(placeholder_token, " ".join(tokens))
161
+ return text
162
+
163
+ def replace_text_with_placeholder_tokens(
164
+ self, text: Union[str, List[str]]
165
+ ) -> Union[str, List[str]]:
166
+ """Replace the placeholder tokens in text with the original keywords.
167
+ This function will be called in `self.decode`.
168
+
169
+ Args:
170
+ text (Union[str, List[str]]): The text to be processed.
171
+
172
+ Returns:
173
+ Union[str, List[str]]: The processed text.
174
+ """
175
+ if isinstance(text, list):
176
+ output = []
177
+ for i in range(len(text)):
178
+ output.append(self.replace_text_with_placeholder_tokens(text[i]))
179
+ return output
180
+
181
+ for placeholder_token, tokens in self.token_map.items():
182
+ merged_tokens = " ".join(tokens)
183
+ if merged_tokens in text:
184
+ text = text.replace(merged_tokens, placeholder_token)
185
+ return text
186
+
187
+ def __call__(
188
+ self,
189
+ text: Union[str, List[str]],
190
+ *args,
191
+ vector_shuffle: bool = False,
192
+ prop_tokens_to_load: float = 1.0,
193
+ **kwargs,
194
+ ):
195
+ """The call function of the wrapper.
196
+
197
+ Args:
198
+ text (Union[str, List[str]]): The text to be tokenized.
199
+ vector_shuffle (bool, optional): Whether to shuffle the vectors.
200
+ Defaults to False.
201
+ prop_tokens_to_load (float, optional): The proportion of tokens to
202
+ be loaded. If 1.0, all tokens will be loaded. Defaults to 1.0
203
+ *args, **kwargs: The arguments for `self.wrapped.__call__`.
204
+ """
205
+ replaced_text = self.replace_placeholder_tokens_in_text(
206
+ text, vector_shuffle=vector_shuffle, prop_tokens_to_load=prop_tokens_to_load
207
+ )
208
+
209
+ return self.wrapped.__call__(replaced_text, *args, **kwargs)
210
+
211
+ def encode(self, text: Union[str, List[str]], *args, **kwargs):
212
+ """Encode the passed text to token index.
213
+
214
+ Args:
215
+ text (Union[str, List[str]]): The text to be encode.
216
+ *args, **kwargs: The arguments for `self.wrapped.__call__`.
217
+ """
218
+ replaced_text = self.replace_placeholder_tokens_in_text(text)
219
+ return self.wrapped(replaced_text, *args, **kwargs)
220
+
221
+ def decode(
222
+ self, token_ids, return_raw: bool = False, *args, **kwargs
223
+ ) -> Union[str, List[str]]:
224
+ """Decode the token index to text.
225
+
226
+ Args:
227
+ token_ids: The token index to be decoded.
228
+ return_raw: Whether keep the placeholder token in the text.
229
+ Defaults to False.
230
+ *args, **kwargs: The arguments for `self.wrapped.decode`.
231
+
232
+ Returns:
233
+ Union[str, List[str]]: The decoded text.
234
+ """
235
+ text = self.wrapped.decode(token_ids, *args, **kwargs)
236
+ if return_raw:
237
+ return text
238
+ replaced_text = self.replace_text_with_placeholder_tokens(text)
239
+ return replaced_text
240
+
241
+
242
+ class EmbeddingLayerWithFixes(nn.Module):
243
+ """The revised embedding layer to support external embeddings. This design
244
+ of this class is inspired by https://github.com/AUTOMATIC1111/stable-
245
+ diffusion-webui/blob/22bcc7be428c94e9408f589966c2040187245d81/modules/sd_hi
246
+ jack.py#L224 # noqa.
247
+
248
+ Args:
249
+ wrapped (nn.Emebdding): The embedding layer to be wrapped.
250
+ external_embeddings (Union[dict, List[dict]], optional): The external
251
+ embeddings added to this layer. Defaults to None.
252
+ """
253
+
254
+ def __init__(
255
+ self,
256
+ wrapped: nn.Embedding,
257
+ external_embeddings: Optional[Union[dict, List[dict]]] = None,
258
+ ):
259
+ super().__init__()
260
+ self.wrapped = wrapped
261
+ self.num_embeddings = wrapped.weight.shape[0]
262
+
263
+ self.external_embeddings = []
264
+ if external_embeddings:
265
+ self.add_embeddings(external_embeddings)
266
+
267
+ self.trainable_embeddings = nn.ParameterDict()
268
+
269
+ @property
270
+ def weight(self):
271
+ """Get the weight of wrapped embedding layer."""
272
+ return self.wrapped.weight
273
+
274
+ def check_duplicate_names(self, embeddings: List[dict]):
275
+ """Check whether duplicate names exist in list of 'external
276
+ embeddings'.
277
+
278
+ Args:
279
+ embeddings (List[dict]): A list of embedding to be check.
280
+ """
281
+ names = [emb["name"] for emb in embeddings]
282
+ assert len(names) == len(set(names)), (
283
+ "Found duplicated names in 'external_embeddings'. Name list: " f"'{names}'"
284
+ )
285
+
286
+ def check_ids_overlap(self, embeddings):
287
+ """Check whether overlap exist in token ids of 'external_embeddings'.
288
+
289
+ Args:
290
+ embeddings (List[dict]): A list of embedding to be check.
291
+ """
292
+ ids_range = [[emb["start"], emb["end"], emb["name"]] for emb in embeddings]
293
+ ids_range.sort() # sort by 'start'
294
+ # check if 'end' has overlapping
295
+ for idx in range(len(ids_range) - 1):
296
+ name1, name2 = ids_range[idx][-1], ids_range[idx + 1][-1]
297
+ assert ids_range[idx][1] <= ids_range[idx + 1][0], (
298
+ f"Found ids overlapping between embeddings '{name1}' " f"and '{name2}'."
299
+ )
300
+
301
+ def add_embeddings(self, embeddings: Optional[Union[dict, List[dict]]]):
302
+ """Add external embeddings to this layer.
303
+
304
+ Use case:
305
+
306
+ >>> 1. Add token to tokenizer and get the token id.
307
+ >>> tokenizer = TokenizerWrapper('openai/clip-vit-base-patch32')
308
+ >>> # 'how much' in kiswahili
309
+ >>> tokenizer.add_placeholder_tokens('ngapi', num_vec_per_token=4)
310
+ >>>
311
+ >>> 2. Add external embeddings to the model.
312
+ >>> new_embedding = {
313
+ >>> 'name': 'ngapi', # 'how much' in kiswahili
314
+ >>> 'embedding': torch.ones(1, 15) * 4,
315
+ >>> 'start': tokenizer.get_token_info('kwaheri')['start'],
316
+ >>> 'end': tokenizer.get_token_info('kwaheri')['end'],
317
+ >>> 'trainable': False # if True, will registry as a parameter
318
+ >>> }
319
+ >>> embedding_layer = nn.Embedding(10, 15)
320
+ >>> embedding_layer_wrapper = EmbeddingLayerWithFixes(embedding_layer)
321
+ >>> embedding_layer_wrapper.add_embeddings(new_embedding)
322
+ >>>
323
+ >>> 3. Forward tokenizer and embedding layer!
324
+ >>> input_text = ['hello, ngapi!', 'hello my friend, ngapi?']
325
+ >>> input_ids = tokenizer(
326
+ >>> input_text, padding='max_length', truncation=True,
327
+ >>> return_tensors='pt')['input_ids']
328
+ >>> out_feat = embedding_layer_wrapper(input_ids)
329
+ >>>
330
+ >>> 4. Let's validate the result!
331
+ >>> assert (out_feat[0, 3: 7] == 2.3).all()
332
+ >>> assert (out_feat[2, 5: 9] == 2.3).all()
333
+
334
+ Args:
335
+ embeddings (Union[dict, list[dict]]): The external embeddings to
336
+ be added. Each dict must contain the following 4 fields: 'name'
337
+ (the name of this embedding), 'embedding' (the embedding
338
+ tensor), 'start' (the start token id of this embedding), 'end'
339
+ (the end token id of this embedding). For example:
340
+ `{name: NAME, start: START, end: END, embedding: torch.Tensor}`
341
+ """
342
+ if isinstance(embeddings, dict):
343
+ embeddings = [embeddings]
344
+
345
+ self.external_embeddings += embeddings
346
+ self.check_duplicate_names(self.external_embeddings)
347
+ self.check_ids_overlap(self.external_embeddings)
348
+
349
+ # set for trainable
350
+ added_trainable_emb_info = []
351
+ for embedding in embeddings:
352
+ trainable = embedding.get("trainable", False)
353
+ if trainable:
354
+ name = embedding["name"]
355
+ embedding["embedding"] = torch.nn.Parameter(embedding["embedding"])
356
+ self.trainable_embeddings[name] = embedding["embedding"]
357
+ added_trainable_emb_info.append(name)
358
+
359
+ added_emb_info = [emb["name"] for emb in embeddings]
360
+ added_emb_info = ", ".join(added_emb_info)
361
+ print(f"Successfully add external embeddings: {added_emb_info}.", "current")
362
+
363
+ if added_trainable_emb_info:
364
+ added_trainable_emb_info = ", ".join(added_trainable_emb_info)
365
+ print(
366
+ "Successfully add trainable external embeddings: "
367
+ f"{added_trainable_emb_info}",
368
+ "current",
369
+ )
370
+
371
+ def replace_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
372
+ """Replace external input ids to 0.
373
+
374
+ Args:
375
+ input_ids (torch.Tensor): The input ids to be replaced.
376
+
377
+ Returns:
378
+ torch.Tensor: The replaced input ids.
379
+ """
380
+ input_ids_fwd = input_ids.clone()
381
+ input_ids_fwd[input_ids_fwd >= self.num_embeddings] = 0
382
+ return input_ids_fwd
383
+
384
+ def replace_embeddings(
385
+ self, input_ids: torch.Tensor, embedding: torch.Tensor, external_embedding: dict
386
+ ) -> torch.Tensor:
387
+ """Replace external embedding to the embedding layer. Noted that, in
388
+ this function we use `torch.cat` to avoid inplace modification.
389
+
390
+ Args:
391
+ input_ids (torch.Tensor): The original token ids. Shape like
392
+ [LENGTH, ].
393
+ embedding (torch.Tensor): The embedding of token ids after
394
+ `replace_input_ids` function.
395
+ external_embedding (dict): The external embedding to be replaced.
396
+
397
+ Returns:
398
+ torch.Tensor: The replaced embedding.
399
+ """
400
+ new_embedding = []
401
+
402
+ name = external_embedding["name"]
403
+ start = external_embedding["start"]
404
+ end = external_embedding["end"]
405
+ target_ids_to_replace = [i for i in range(start, end)]
406
+ ext_emb = external_embedding["embedding"]
407
+
408
+ # do not need to replace
409
+ if not (input_ids == start).any():
410
+ return embedding
411
+
412
+ # start replace
413
+ s_idx, e_idx = 0, 0
414
+ while e_idx < len(input_ids):
415
+ if input_ids[e_idx] == start:
416
+ if e_idx != 0:
417
+ # add embedding do not need to replace
418
+ new_embedding.append(embedding[s_idx:e_idx])
419
+
420
+ # check if the next embedding need to replace is valid
421
+ actually_ids_to_replace = [
422
+ int(i) for i in input_ids[e_idx : e_idx + end - start]
423
+ ]
424
+ assert actually_ids_to_replace == target_ids_to_replace, (
425
+ f"Invalid 'input_ids' in position: {s_idx} to {e_idx}. "
426
+ f"Expect '{target_ids_to_replace}' for embedding "
427
+ f"'{name}' but found '{actually_ids_to_replace}'."
428
+ )
429
+
430
+ new_embedding.append(ext_emb)
431
+
432
+ s_idx = e_idx + end - start
433
+ e_idx = s_idx + 1
434
+ else:
435
+ e_idx += 1
436
+
437
+ if e_idx == len(input_ids):
438
+ new_embedding.append(embedding[s_idx:e_idx])
439
+
440
+ return torch.cat(new_embedding, dim=0)
441
+
442
+ def forward(
443
+ self, input_ids: torch.Tensor, external_embeddings: Optional[List[dict]] = None
444
+ ):
445
+ """The forward function.
446
+
447
+ Args:
448
+ input_ids (torch.Tensor): The token ids shape like [bz, LENGTH] or
449
+ [LENGTH, ].
450
+ external_embeddings (Optional[List[dict]]): The external
451
+ embeddings. If not passed, only `self.external_embeddings`
452
+ will be used. Defaults to None.
453
+
454
+ input_ids: shape like [bz, LENGTH] or [LENGTH].
455
+ """
456
+ assert input_ids.ndim in [1, 2]
457
+ if input_ids.ndim == 1:
458
+ input_ids = input_ids.unsqueeze(0)
459
+
460
+ if external_embeddings is None and not self.external_embeddings:
461
+ return self.wrapped(input_ids)
462
+
463
+ input_ids_fwd = self.replace_input_ids(input_ids)
464
+ inputs_embeds = self.wrapped(input_ids_fwd)
465
+
466
+ vecs = []
467
+
468
+ if external_embeddings is None:
469
+ external_embeddings = []
470
+ elif isinstance(external_embeddings, dict):
471
+ external_embeddings = [external_embeddings]
472
+ embeddings = self.external_embeddings + external_embeddings
473
+
474
+ for input_id, embedding in zip(input_ids, inputs_embeds):
475
+ new_embedding = embedding
476
+ for external_embedding in embeddings:
477
+ new_embedding = self.replace_embeddings(
478
+ input_id, new_embedding, external_embedding
479
+ )
480
+ vecs.append(new_embedding)
481
+
482
+ return torch.stack(vecs)
483
+
484
+
485
+ def add_tokens(
486
+ tokenizer,
487
+ text_encoder,
488
+ placeholder_tokens: list,
489
+ initialize_tokens: list = None,
490
+ num_vectors_per_token: int = 1,
491
+ ):
492
+ """Add token for training.
493
+
494
+ # TODO: support add tokens as dict, then we can load pretrained tokens.
495
+ """
496
+ if initialize_tokens is not None:
497
+ assert len(initialize_tokens) == len(
498
+ placeholder_tokens
499
+ ), "placeholder_token should be the same length as initialize_token"
500
+ for ii in range(len(placeholder_tokens)):
501
+ tokenizer.add_placeholder_token(
502
+ placeholder_tokens[ii], num_vec_per_token=num_vectors_per_token
503
+ )
504
+
505
+ # text_encoder.set_embedding_layer()
506
+ embedding_layer = text_encoder.text_model.embeddings.token_embedding
507
+ text_encoder.text_model.embeddings.token_embedding = EmbeddingLayerWithFixes(
508
+ embedding_layer
509
+ )
510
+ embedding_layer = text_encoder.text_model.embeddings.token_embedding
511
+
512
+ assert embedding_layer is not None, (
513
+ "Do not support get embedding layer for current text encoder. "
514
+ "Please check your configuration."
515
+ )
516
+ initialize_embedding = []
517
+ if initialize_tokens is not None:
518
+ for ii in range(len(placeholder_tokens)):
519
+ init_id = tokenizer(initialize_tokens[ii]).input_ids[1]
520
+ temp_embedding = embedding_layer.weight[init_id]
521
+ initialize_embedding.append(
522
+ temp_embedding[None, ...].repeat(num_vectors_per_token, 1)
523
+ )
524
+ else:
525
+ for ii in range(len(placeholder_tokens)):
526
+ init_id = tokenizer("a").input_ids[1]
527
+ temp_embedding = embedding_layer.weight[init_id]
528
+ len_emb = temp_embedding.shape[0]
529
+ init_weight = (torch.rand(num_vectors_per_token, len_emb) - 0.5) / 2.0
530
+ initialize_embedding.append(init_weight)
531
+
532
+ # initialize_embedding = torch.cat(initialize_embedding,dim=0)
533
+
534
+ token_info_all = []
535
+ for ii in range(len(placeholder_tokens)):
536
+ token_info = tokenizer.get_token_info(placeholder_tokens[ii])
537
+ token_info["embedding"] = initialize_embedding[ii]
538
+ token_info["trainable"] = True
539
+ token_info_all.append(token_info)
540
+ embedding_layer.add_embeddings(token_info_all)
iopaint/tests/test_adjust_mask.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ from iopaint.helper import adjust_mask
3
+ from iopaint.tests.utils import current_dir, save_dir
4
+
5
+ mask_p = current_dir / "overture-creations-5sI6fQgYIuo_mask.png"
6
+
7
+
8
+ def test_adjust_mask():
9
+ mask = cv2.imread(str(mask_p), cv2.IMREAD_GRAYSCALE)
10
+ res_mask = adjust_mask(mask, 0, "expand")
11
+ cv2.imwrite(str(save_dir / "adjust_mask_original.png"), res_mask)
12
+ res_mask = adjust_mask(mask, 40, "expand")
13
+ cv2.imwrite(str(save_dir / "adjust_mask_expand.png"), res_mask)
14
+ res_mask = adjust_mask(mask, 20, "shrink")
15
+ cv2.imwrite(str(save_dir / "adjust_mask_shrink.png"), res_mask)
16
+ res_mask = adjust_mask(mask, 20, "reverse")
17
+ cv2.imwrite(str(save_dir / "adjust_mask_reverse.png"), res_mask)
iopaint/tests/test_anytext.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ from iopaint.tests.utils import check_device, get_config, assert_equal
4
+
5
+ os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
6
+ from pathlib import Path
7
+
8
+ import pytest
9
+ import torch
10
+
11
+ from iopaint.model_manager import ModelManager
12
+ from iopaint.schema import HDStrategy
13
+
14
+ current_dir = Path(__file__).parent.absolute().resolve()
15
+ save_dir = current_dir / "result"
16
+ save_dir.mkdir(exist_ok=True, parents=True)
17
+
18
+
19
+ @pytest.mark.parametrize("device", ["cuda", "mps"])
20
+ def test_anytext(device):
21
+ sd_steps = check_device(device)
22
+ model = ModelManager(
23
+ name="Sanster/AnyText",
24
+ device=torch.device(device),
25
+ disable_nsfw=True,
26
+ sd_cpu_textencoder=False,
27
+ )
28
+
29
+ cfg = get_config(
30
+ strategy=HDStrategy.ORIGINAL,
31
+ prompt='Characters written in chalk on the blackboard that says "DADDY", best quality, extremely detailed,4k, HD, supper legible text, clear text edges, clear strokes, neat writing, no watermarks',
32
+ negative_prompt="low-res, bad anatomy, extra digit, fewer digits, cropped, worst quality, low quality, watermark, unreadable text, messy words, distorted text, disorganized writing, advertising picture",
33
+ sd_steps=sd_steps,
34
+ sd_guidance_scale=9.0,
35
+ sd_seed=66273235,
36
+ sd_match_histograms=True
37
+ )
38
+
39
+ assert_equal(
40
+ model,
41
+ cfg,
42
+ f"anytext.png",
43
+ img_p=current_dir / "anytext_ref.jpg",
44
+ mask_p=current_dir / "anytext_mask.jpg",
45
+ )
iopaint/tests/test_controlnet.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ from iopaint.const import SD_CONTROLNET_CHOICES
4
+ from iopaint.tests.utils import current_dir, check_device, get_config, assert_equal
5
+
6
+ os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
7
+ from pathlib import Path
8
+
9
+ import pytest
10
+ import torch
11
+
12
+ from iopaint.model_manager import ModelManager
13
+ from iopaint.schema import HDStrategy, SDSampler
14
+
15
+
16
+ model_name = "runwayml/stable-diffusion-inpainting"
17
+
18
+
19
+ def convert_controlnet_method_name(name):
20
+ return name.replace("/", "--")
21
+
22
+
23
+ @pytest.mark.parametrize("device", ["cuda", "mps", "cpu"])
24
+ @pytest.mark.parametrize("controlnet_method", [SD_CONTROLNET_CHOICES[0]])
25
+ def test_runway_sd_1_5(device, controlnet_method):
26
+ sd_steps = check_device(device)
27
+
28
+ model = ModelManager(
29
+ name=model_name,
30
+ device=torch.device(device),
31
+ disable_nsfw=True,
32
+ sd_cpu_textencoder=device == "cuda",
33
+ enable_controlnet=True,
34
+ controlnet_method=controlnet_method,
35
+ )
36
+
37
+ cfg = get_config(
38
+ prompt="a fox sitting on a bench",
39
+ sd_steps=sd_steps,
40
+ enable_controlnet=True,
41
+ controlnet_conditioning_scale=0.5,
42
+ controlnet_method=controlnet_method,
43
+ )
44
+ name = f"device_{device}"
45
+
46
+ assert_equal(
47
+ model,
48
+ cfg,
49
+ f"sd_controlnet_{convert_controlnet_method_name(controlnet_method)}_{name}.png",
50
+ img_p=current_dir / "overture-creations-5sI6fQgYIuo.png",
51
+ mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png",
52
+ )
53
+
54
+
55
+ @pytest.mark.parametrize("device", ["cuda", "mps", "cpu"])
56
+ def test_controlnet_switch(device):
57
+ sd_steps = check_device(device)
58
+ model = ModelManager(
59
+ name=model_name,
60
+ device=torch.device(device),
61
+ disable_nsfw=True,
62
+ sd_cpu_textencoder=False,
63
+ cpu_offload=True,
64
+ enable_controlnet=True,
65
+ controlnet_method="lllyasviel/control_v11p_sd15_canny",
66
+ )
67
+ cfg = get_config(
68
+ prompt="a fox sitting on a bench",
69
+ sd_steps=sd_steps,
70
+ enable_controlnet=True,
71
+ controlnet_method="lllyasviel/control_v11f1p_sd15_depth",
72
+ )
73
+
74
+ assert_equal(
75
+ model,
76
+ cfg,
77
+ f"controlnet_switch_canny_to_depth_device_{device}.png",
78
+ img_p=current_dir / "overture-creations-5sI6fQgYIuo.png",
79
+ mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png",
80
+ fx=1.2
81
+ )
82
+
83
+
84
+ @pytest.mark.parametrize("device", ["cuda", "mps", "cpu"])
85
+ @pytest.mark.parametrize(
86
+ "local_file", ["sd-v1-5-inpainting.ckpt", "v1-5-pruned-emaonly.safetensors"]
87
+ )
88
+ def test_local_file_path(device, local_file):
89
+ sd_steps = check_device(device)
90
+
91
+ controlnet_kwargs = dict(
92
+ enable_controlnet=True,
93
+ controlnet_method=SD_CONTROLNET_CHOICES[0],
94
+ )
95
+
96
+ model = ModelManager(
97
+ name=local_file,
98
+ device=torch.device(device),
99
+ disable_nsfw=True,
100
+ sd_cpu_textencoder=False,
101
+ cpu_offload=True,
102
+ **controlnet_kwargs,
103
+ )
104
+ cfg = get_config(
105
+ prompt="a fox sitting on a bench",
106
+ sd_steps=sd_steps,
107
+ **controlnet_kwargs,
108
+ )
109
+
110
+ name = f"device_{device}"
111
+
112
+ assert_equal(
113
+ model,
114
+ cfg,
115
+ f"{convert_controlnet_method_name(controlnet_kwargs['controlnet_method'])}_local_model_{name}.png",
116
+ img_p=current_dir / "overture-creations-5sI6fQgYIuo.png",
117
+ mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png",
118
+ )
iopaint/tests/test_instruct_pix2pix.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+
3
+ import pytest
4
+ import torch
5
+
6
+ from iopaint.model_manager import ModelManager
7
+ from iopaint.schema import HDStrategy
8
+ from iopaint.tests.utils import get_config, check_device, assert_equal, current_dir
9
+
10
+ model_name = "timbrooks/instruct-pix2pix"
11
+
12
+
13
+ @pytest.mark.parametrize("device", ["cuda", "mps", "cpu"])
14
+ @pytest.mark.parametrize("disable_nsfw", [True, False])
15
+ @pytest.mark.parametrize("cpu_offload", [False, True])
16
+ def test_instruct_pix2pix(device, disable_nsfw, cpu_offload):
17
+ sd_steps = check_device(device)
18
+ model = ModelManager(
19
+ name=model_name,
20
+ device=torch.device(device),
21
+ disable_nsfw=disable_nsfw,
22
+ sd_cpu_textencoder=False,
23
+ cpu_offload=cpu_offload,
24
+ )
25
+ cfg = get_config(
26
+ strategy=HDStrategy.ORIGINAL,
27
+ prompt="What if it were snowing?",
28
+ sd_steps=sd_steps
29
+ )
30
+
31
+ name = f"device_{device}_disnsfw_{disable_nsfw}_cpu_offload_{cpu_offload}"
32
+
33
+ assert_equal(
34
+ model,
35
+ cfg,
36
+ f"instruct_pix2pix_{name}.png",
37
+ img_p=current_dir / "overture-creations-5sI6fQgYIuo.png",
38
+ mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png",
39
+ fx=1.3,
40
+ )
iopaint/tests/test_load_img.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from iopaint.helper import load_img
2
+ from iopaint.tests.utils import current_dir
3
+
4
+ png_img_p = current_dir / "image.png"
5
+ jpg_img_p = current_dir / "bunny.jpeg"
6
+
7
+
8
+ def test_load_png_image():
9
+ with open(png_img_p, "rb") as f:
10
+ np_img, alpha_channel = load_img(f.read())
11
+ assert np_img.shape == (256, 256, 3)
12
+ assert alpha_channel.shape == (256, 256)
13
+
14
+
15
+ def test_load_jpg_image():
16
+ with open(jpg_img_p, "rb") as f:
17
+ np_img, alpha_channel = load_img(f.read())
18
+ assert np_img.shape == (394, 448, 3)
19
+ assert alpha_channel is None
iopaint/tests/test_low_mem.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ from loguru import logger
4
+
5
+ from iopaint.tests.utils import check_device, get_config, assert_equal, current_dir
6
+
7
+ os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
8
+
9
+ import pytest
10
+ import torch
11
+
12
+ from iopaint.model_manager import ModelManager
13
+ from iopaint.schema import HDStrategy, SDSampler, FREEUConfig
14
+
15
+
16
+ @pytest.mark.parametrize("device", ["cuda", "mps"])
17
+ def test_runway_sd_1_5_low_mem(device):
18
+ sd_steps = check_device(device)
19
+ model = ModelManager(
20
+ name="runwayml/stable-diffusion-inpainting",
21
+ device=torch.device(device),
22
+ disable_nsfw=True,
23
+ sd_cpu_textencoder=False,
24
+ low_mem=True,
25
+ )
26
+
27
+ all_samplers = [member.value for member in SDSampler.__members__.values()]
28
+ print(all_samplers)
29
+ cfg = get_config(
30
+ strategy=HDStrategy.ORIGINAL,
31
+ prompt="a fox sitting on a bench",
32
+ sd_steps=sd_steps,
33
+ sd_sampler=SDSampler.ddim,
34
+ )
35
+
36
+ name = f"device_{device}"
37
+
38
+ assert_equal(
39
+ model,
40
+ cfg,
41
+ f"runway_sd_{name}_low_mem.png",
42
+ img_p=current_dir / "overture-creations-5sI6fQgYIuo.png",
43
+ mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png",
44
+ )
45
+
46
+
47
+ @pytest.mark.parametrize("device", ["cuda", "mps", "cpu"])
48
+ @pytest.mark.parametrize("sampler", [SDSampler.lcm])
49
+ def test_runway_sd_lcm_lora_low_mem(device, sampler):
50
+ check_device(device)
51
+
52
+ sd_steps = 5
53
+ model = ModelManager(
54
+ name="runwayml/stable-diffusion-inpainting",
55
+ device=torch.device(device),
56
+ disable_nsfw=True,
57
+ sd_cpu_textencoder=False,
58
+ low_mem=True,
59
+ )
60
+ cfg = get_config(
61
+ strategy=HDStrategy.ORIGINAL,
62
+ prompt="face of a fox, sitting on a bench",
63
+ sd_steps=sd_steps,
64
+ sd_guidance_scale=2,
65
+ sd_lcm_lora=True,
66
+ )
67
+ cfg.sd_sampler = sampler
68
+
69
+ assert_equal(
70
+ model,
71
+ cfg,
72
+ f"runway_sd_1_5_lcm_lora_device_{device}_low_mem.png",
73
+ img_p=current_dir / "overture-creations-5sI6fQgYIuo.png",
74
+ mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png",
75
+ )
76
+
77
+
78
+ @pytest.mark.parametrize("device", ["cuda", "mps", "cpu"])
79
+ @pytest.mark.parametrize("sampler", [SDSampler.ddim])
80
+ def test_runway_sd_freeu(device, sampler):
81
+ sd_steps = check_device(device)
82
+ model = ModelManager(
83
+ name="runwayml/stable-diffusion-inpainting",
84
+ device=torch.device(device),
85
+ disable_nsfw=True,
86
+ sd_cpu_textencoder=False,
87
+ low_mem=True,
88
+ )
89
+ cfg = get_config(
90
+ strategy=HDStrategy.ORIGINAL,
91
+ prompt="face of a fox, sitting on a bench",
92
+ sd_steps=sd_steps,
93
+ sd_guidance_scale=7.5,
94
+ sd_freeu=True,
95
+ sd_freeu_config=FREEUConfig(),
96
+ )
97
+ cfg.sd_sampler = sampler
98
+
99
+ assert_equal(
100
+ model,
101
+ cfg,
102
+ f"runway_sd_1_5_freeu_device_{device}_low_mem.png",
103
+ img_p=current_dir / "overture-creations-5sI6fQgYIuo.png",
104
+ mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png",
105
+ )
106
+
107
+
108
+ @pytest.mark.parametrize("device", ["cuda", "mps", "cpu"])
109
+ @pytest.mark.parametrize("strategy", [HDStrategy.ORIGINAL])
110
+ @pytest.mark.parametrize("sampler", [SDSampler.ddim])
111
+ def test_runway_norm_sd_model(device, strategy, sampler):
112
+ sd_steps = check_device(device)
113
+ model = ModelManager(
114
+ name="runwayml/stable-diffusion-v1-5",
115
+ device=torch.device(device),
116
+ disable_nsfw=True,
117
+ sd_cpu_textencoder=False,
118
+ low_mem=True,
119
+ )
120
+ cfg = get_config(
121
+ strategy=strategy, prompt="face of a fox, sitting on a bench", sd_steps=sd_steps
122
+ )
123
+ cfg.sd_sampler = sampler
124
+
125
+ assert_equal(
126
+ model,
127
+ cfg,
128
+ f"runway_{device}_norm_sd_model_device_{device}_low_mem.png",
129
+ img_p=current_dir / "overture-creations-5sI6fQgYIuo.png",
130
+ mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png",
131
+ )
iopaint/tests/test_match_histograms.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import torch
3
+
4
+ from iopaint.model_manager import ModelManager
5
+ from iopaint.schema import SDSampler, HDStrategy
6
+ from iopaint.tests.utils import check_device, get_config, assert_equal, current_dir
7
+
8
+
9
+ @pytest.mark.parametrize("device", ["cuda", "mps"])
10
+ @pytest.mark.parametrize("sampler", [SDSampler.ddim])
11
+ def test_sd_match_histograms(device, sampler):
12
+ sd_steps = check_device(device)
13
+
14
+ model = ModelManager(
15
+ name="runwayml/stable-diffusion-inpainting",
16
+ device=torch.device(device),
17
+ disable_nsfw=True,
18
+ sd_cpu_textencoder=False,
19
+ )
20
+ cfg = get_config(
21
+ strategy=HDStrategy.ORIGINAL,
22
+ prompt="face of a fox, sitting on a bench",
23
+ sd_steps=sd_steps,
24
+ sd_guidance_scale=7.5,
25
+ sd_lcm_lora=False,
26
+ sd_match_histograms=True,
27
+ sd_sampler=sampler
28
+ )
29
+
30
+ assert_equal(
31
+ model,
32
+ cfg,
33
+ f"runway_sd_1_5_device_{device}_match_histograms.png",
34
+ img_p=current_dir / "overture-creations-5sI6fQgYIuo.png",
35
+ mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png",
36
+ )
iopaint/tests/test_model.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import torch
3
+
4
+ from iopaint.model_manager import ModelManager
5
+ from iopaint.schema import HDStrategy, LDMSampler
6
+ from iopaint.tests.utils import assert_equal, get_config, current_dir, check_device
7
+
8
+
9
+ @pytest.mark.parametrize("device", ["cuda", "mps", "cpu"])
10
+ @pytest.mark.parametrize(
11
+ "strategy", [HDStrategy.ORIGINAL, HDStrategy.RESIZE, HDStrategy.CROP]
12
+ )
13
+ def test_lama(device, strategy):
14
+ check_device(device)
15
+ model = ModelManager(name="lama", device=device)
16
+ assert_equal(
17
+ model,
18
+ get_config(strategy=strategy),
19
+ f"lama_{strategy[0].upper() + strategy[1:]}_result.png",
20
+ )
21
+
22
+ fx = 1.3
23
+ assert_equal(
24
+ model,
25
+ get_config(strategy=strategy),
26
+ f"lama_{strategy[0].upper() + strategy[1:]}_fx_{fx}_result.png",
27
+ fx=1.3,
28
+ )
29
+
30
+
31
+ @pytest.mark.parametrize("device", ["cuda", "cpu"])
32
+ @pytest.mark.parametrize(
33
+ "strategy", [HDStrategy.ORIGINAL, HDStrategy.RESIZE, HDStrategy.CROP]
34
+ )
35
+ @pytest.mark.parametrize("ldm_sampler", [LDMSampler.ddim, LDMSampler.plms])
36
+ def test_ldm(device, strategy, ldm_sampler):
37
+ check_device(device)
38
+ model = ModelManager(name="ldm", device=device)
39
+ cfg = get_config(strategy=strategy, ldm_sampler=ldm_sampler)
40
+ assert_equal(
41
+ model, cfg, f"ldm_{strategy[0].upper() + strategy[1:]}_{ldm_sampler}_result.png"
42
+ )
43
+
44
+ fx = 1.3
45
+ assert_equal(
46
+ model,
47
+ cfg,
48
+ f"ldm_{strategy[0].upper() + strategy[1:]}_{ldm_sampler}_fx_{fx}_result.png",
49
+ fx=fx,
50
+ )
51
+
52
+
53
+ @pytest.mark.parametrize("device", ["cuda", "cpu"])
54
+ @pytest.mark.parametrize(
55
+ "strategy", [HDStrategy.ORIGINAL, HDStrategy.RESIZE, HDStrategy.CROP]
56
+ )
57
+ @pytest.mark.parametrize("zits_wireframe", [False, True])
58
+ def test_zits(device, strategy, zits_wireframe):
59
+ check_device(device)
60
+ model = ModelManager(name="zits", device=device)
61
+ cfg = get_config(strategy=strategy, zits_wireframe=zits_wireframe)
62
+ assert_equal(
63
+ model,
64
+ cfg,
65
+ f"zits_{strategy[0].upper() + strategy[1:]}_wireframe_{zits_wireframe}_result.png",
66
+ )
67
+
68
+ fx = 1.3
69
+ assert_equal(
70
+ model,
71
+ cfg,
72
+ f"zits_{strategy.capitalize()}_wireframe_{zits_wireframe}_fx_{fx}_result.png",
73
+ fx=fx,
74
+ )
75
+
76
+
77
+ @pytest.mark.parametrize("device", ["cuda", "cpu"])
78
+ @pytest.mark.parametrize("strategy", [HDStrategy.ORIGINAL])
79
+ @pytest.mark.parametrize("no_half", [True, False])
80
+ def test_mat(device, strategy, no_half):
81
+ check_device(device)
82
+ model = ModelManager(name="mat", device=device, no_half=no_half)
83
+ cfg = get_config(strategy=strategy)
84
+
85
+ assert_equal(
86
+ model,
87
+ cfg,
88
+ f"mat_{strategy.capitalize()}_result.png",
89
+ )
90
+
91
+
92
+ @pytest.mark.parametrize("device", ["cuda", "cpu"])
93
+ @pytest.mark.parametrize("strategy", [HDStrategy.ORIGINAL])
94
+ def test_fcf(device, strategy):
95
+ check_device(device)
96
+ model = ModelManager(name="fcf", device=device)
97
+ cfg = get_config(strategy=strategy)
98
+
99
+ assert_equal(model, cfg, f"fcf_{strategy.capitalize()}_result.png", fx=2, fy=2)
100
+ assert_equal(model, cfg, f"fcf_{strategy.capitalize()}_result.png", fx=3.8, fy=2)
101
+
102
+
103
+ @pytest.mark.parametrize(
104
+ "strategy", [HDStrategy.ORIGINAL, HDStrategy.RESIZE, HDStrategy.CROP]
105
+ )
106
+ @pytest.mark.parametrize("cv2_flag", ["INPAINT_NS", "INPAINT_TELEA"])
107
+ @pytest.mark.parametrize("cv2_radius", [3, 15])
108
+ def test_cv2(strategy, cv2_flag, cv2_radius):
109
+ model = ModelManager(
110
+ name="cv2",
111
+ device=torch.device("cpu"),
112
+ )
113
+ cfg = get_config(strategy=strategy, cv2_flag=cv2_flag, cv2_radius=cv2_radius)
114
+ assert_equal(
115
+ model,
116
+ cfg,
117
+ f"cv2_{strategy.capitalize()}_{cv2_flag}_{cv2_radius}.png",
118
+ img_p=current_dir / "overture-creations-5sI6fQgYIuo.png",
119
+ mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png",
120
+ )
121
+
122
+
123
+ @pytest.mark.parametrize("device", ["cuda", "cpu"])
124
+ @pytest.mark.parametrize(
125
+ "strategy", [HDStrategy.ORIGINAL, HDStrategy.RESIZE, HDStrategy.CROP]
126
+ )
127
+ def test_manga(device, strategy):
128
+ check_device(device)
129
+ model = ModelManager(
130
+ name="manga",
131
+ device=torch.device(device),
132
+ )
133
+ cfg = get_config(strategy=strategy)
134
+ assert_equal(
135
+ model,
136
+ cfg,
137
+ f"manga_{strategy.capitalize()}.png",
138
+ img_p=current_dir / "overture-creations-5sI6fQgYIuo.png",
139
+ mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png",
140
+ )
141
+
142
+
143
+ @pytest.mark.parametrize("device", ["cuda", "mps", "cpu"])
144
+ @pytest.mark.parametrize("strategy", [HDStrategy.ORIGINAL])
145
+ def test_mi_gan(device, strategy):
146
+ check_device(device)
147
+ model = ModelManager(
148
+ name="migan",
149
+ device=torch.device(device),
150
+ )
151
+ cfg = get_config(strategy=strategy)
152
+ assert_equal(
153
+ model,
154
+ cfg,
155
+ f"migan_device_{device}.png",
156
+ img_p=current_dir / "overture-creations-5sI6fQgYIuo.png",
157
+ mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png",
158
+ fx=1.5,
159
+ fy=1.7
160
+ )
iopaint/tests/test_model_md5.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def test_load_model():
2
+ from iopaint.plugins import InteractiveSeg
3
+ from iopaint.model_manager import ModelManager
4
+
5
+ interactive_seg_model = InteractiveSeg("vit_l", "cpu")
6
+
7
+ models = ["lama", "ldm", "zits", "mat", "fcf", "manga", "migan"]
8
+ for m in models:
9
+ ModelManager(
10
+ name=m,
11
+ device="cpu",
12
+ no_half=False,
13
+ disable_nsfw=False,
14
+ sd_cpu_textencoder=True,
15
+ cpu_offload=True,
16
+ )
iopaint/tests/test_model_switch.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ from iopaint.schema import InpaintRequest
4
+
5
+ os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
6
+
7
+ import torch
8
+
9
+ from iopaint.model_manager import ModelManager
10
+
11
+
12
+ def test_model_switch():
13
+ model = ModelManager(
14
+ name="runwayml/stable-diffusion-inpainting",
15
+ enable_controlnet=True,
16
+ controlnet_method="lllyasviel/control_v11p_sd15_canny",
17
+ device=torch.device("mps"),
18
+ disable_nsfw=True,
19
+ sd_cpu_textencoder=True,
20
+ cpu_offload=False,
21
+ )
22
+
23
+ model.switch("lama")
24
+
25
+
26
+ def test_controlnet_switch_onoff(caplog):
27
+ name = "runwayml/stable-diffusion-inpainting"
28
+ model = ModelManager(
29
+ name=name,
30
+ enable_controlnet=True,
31
+ controlnet_method="lllyasviel/control_v11p_sd15_canny",
32
+ device=torch.device("mps"),
33
+ disable_nsfw=True,
34
+ sd_cpu_textencoder=True,
35
+ cpu_offload=False,
36
+ )
37
+
38
+ model.switch_controlnet_method(
39
+ InpaintRequest(
40
+ name=name,
41
+ enable_controlnet=False,
42
+ )
43
+ )
44
+
45
+ assert "Disable controlnet" in caplog.text
46
+
47
+
48
+ def test_switch_controlnet_method(caplog):
49
+ name = "runwayml/stable-diffusion-inpainting"
50
+ old_method = "lllyasviel/control_v11p_sd15_canny"
51
+ new_method = "lllyasviel/control_v11p_sd15_openpose"
52
+ model = ModelManager(
53
+ name=name,
54
+ enable_controlnet=True,
55
+ controlnet_method=old_method,
56
+ device=torch.device("mps"),
57
+ disable_nsfw=True,
58
+ sd_cpu_textencoder=True,
59
+ cpu_offload=False,
60
+ )
61
+
62
+ model.switch_controlnet_method(
63
+ InpaintRequest(
64
+ name=name,
65
+ enable_controlnet=True,
66
+ controlnet_method=new_method,
67
+ )
68
+ )
69
+
70
+ assert f"Switch Controlnet method from {old_method} to {new_method}" in caplog.text
iopaint/tests/test_outpainting.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ from iopaint.tests.utils import current_dir, check_device
4
+
5
+ os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
6
+ from pathlib import Path
7
+
8
+ import pytest
9
+ import torch
10
+
11
+ from iopaint.model_manager import ModelManager
12
+ from iopaint.schema import HDStrategy, SDSampler
13
+ from iopaint.tests.test_model import get_config, assert_equal
14
+
15
+
16
+ @pytest.mark.parametrize("name", ["runwayml/stable-diffusion-inpainting"])
17
+ @pytest.mark.parametrize("device", ["cuda", "mps", "cpu"])
18
+ @pytest.mark.parametrize(
19
+ "rect",
20
+ [
21
+ [0, -100, 512, 512 - 128 + 100],
22
+ [0, 128, 512, 512 - 128 + 100],
23
+ [128, 0, 512 - 128 + 100, 512],
24
+ [-100, 0, 512 - 128 + 100, 512],
25
+ [0, 0, 512, 512 + 200],
26
+ [0, 0, 512 + 200, 512],
27
+ [-100, -100, 512 + 200, 512 + 200],
28
+ ],
29
+ )
30
+ def test_outpainting(name, device, rect):
31
+ sd_steps = check_device(device)
32
+
33
+ model = ModelManager(
34
+ name=name,
35
+ device=torch.device(device),
36
+ disable_nsfw=True,
37
+ sd_cpu_textencoder=False,
38
+ )
39
+ cfg = get_config(
40
+ prompt="a dog sitting on a bench in the park",
41
+ sd_steps=sd_steps,
42
+ use_extender=True,
43
+ extender_x=rect[0],
44
+ extender_y=rect[1],
45
+ extender_width=rect[2],
46
+ extender_height=rect[3],
47
+ sd_guidance_scale=8.0,
48
+ sd_sampler=SDSampler.dpm_plus_plus_2m,
49
+ )
50
+
51
+ assert_equal(
52
+ model,
53
+ cfg,
54
+ f"{name.replace('/', '--')}_outpainting_{'_'.join(map(str, rect))}_device_{device}.png",
55
+ img_p=current_dir / "overture-creations-5sI6fQgYIuo.png",
56
+ mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png",
57
+ )
58
+
59
+
60
+ @pytest.mark.parametrize("name", ["kandinsky-community/kandinsky-2-2-decoder-inpaint"])
61
+ @pytest.mark.parametrize("device", ["cuda", "mps", "cpu"])
62
+ @pytest.mark.parametrize(
63
+ "rect",
64
+ [
65
+ [-128, -128, 768, 768],
66
+ ],
67
+ )
68
+ def test_kandinsky_outpainting(name, device, rect):
69
+ sd_steps = check_device(device)
70
+
71
+ model = ModelManager(
72
+ name=name,
73
+ device=torch.device(device),
74
+ disable_nsfw=True,
75
+ sd_cpu_textencoder=False,
76
+ )
77
+ cfg = get_config(
78
+ prompt="a cat",
79
+ negative_prompt="lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature",
80
+ sd_steps=sd_steps,
81
+ use_extender=True,
82
+ extender_x=rect[0],
83
+ extender_y=rect[1],
84
+ extender_width=rect[2],
85
+ extender_height=rect[3],
86
+ sd_guidance_scale=7,
87
+ sd_sampler=SDSampler.dpm_plus_plus_2m,
88
+ )
89
+
90
+ assert_equal(
91
+ model,
92
+ cfg,
93
+ f"{name.replace('/', '--')}_outpainting_{'_'.join(map(str, rect))}_device_{device}.png",
94
+ img_p=current_dir / "cat.png",
95
+ mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png",
96
+ fx=1,
97
+ fy=1,
98
+ )
99
+
100
+
101
+ @pytest.mark.parametrize("name", ["Sanster/PowerPaint-V1-stable-diffusion-inpainting"])
102
+ @pytest.mark.parametrize("device", ["cuda", "mps", "cpu"])
103
+ @pytest.mark.parametrize(
104
+ "rect",
105
+ [
106
+ [-100, -100, 512 + 200, 512 + 200],
107
+ ],
108
+ )
109
+ def test_powerpaint_outpainting(name, device, rect):
110
+ sd_steps = check_device(device)
111
+
112
+ model = ModelManager(
113
+ name=name,
114
+ device=torch.device(device),
115
+ disable_nsfw=True,
116
+ sd_cpu_textencoder=False,
117
+ low_mem=True
118
+ )
119
+ cfg = get_config(
120
+ prompt="a dog sitting on a bench in the park",
121
+ sd_steps=sd_steps,
122
+ use_extender=True,
123
+ extender_x=rect[0],
124
+ extender_y=rect[1],
125
+ extender_width=rect[2],
126
+ extender_height=rect[3],
127
+ sd_guidance_scale=8.0,
128
+ sd_sampler=SDSampler.dpm_plus_plus_2m,
129
+ powerpaint_task="outpainting",
130
+ )
131
+
132
+ assert_equal(
133
+ model,
134
+ cfg,
135
+ f"{name.replace('/', '--')}_outpainting_{'_'.join(map(str, rect))}_device_{device}.png",
136
+ img_p=current_dir / "overture-creations-5sI6fQgYIuo.png",
137
+ mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png",
138
+ )
iopaint/tests/test_paint_by_example.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import pytest
3
+ from PIL import Image
4
+
5
+ from iopaint.model_manager import ModelManager
6
+ from iopaint.schema import HDStrategy
7
+ from iopaint.tests.utils import (
8
+ current_dir,
9
+ get_config,
10
+ get_data,
11
+ save_dir,
12
+ check_device,
13
+ )
14
+
15
+ model_name = "Fantasy-Studio/Paint-by-Example"
16
+
17
+
18
+ def assert_equal(
19
+ model,
20
+ config,
21
+ save_name: str,
22
+ fx: float = 1,
23
+ fy: float = 1,
24
+ img_p=current_dir / "overture-creations-5sI6fQgYIuo.png",
25
+ mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png",
26
+ example_p=current_dir / "bunny.jpeg",
27
+ ):
28
+ img, mask = get_data(fx=fx, fy=fy, img_p=img_p, mask_p=mask_p)
29
+
30
+ example_image = cv2.imread(str(example_p))
31
+ example_image = cv2.cvtColor(example_image, cv2.COLOR_BGRA2RGB)
32
+ example_image = cv2.resize(
33
+ example_image, None, fx=fx, fy=fy, interpolation=cv2.INTER_AREA
34
+ )
35
+
36
+ print(f"Input image shape: {img.shape}, example_image: {example_image.shape}")
37
+ config.paint_by_example_example_image = Image.fromarray(example_image)
38
+ res = model(img, mask, config)
39
+ cv2.imwrite(str(save_dir / save_name), res)
40
+
41
+
42
+ @pytest.mark.parametrize("device", ["cuda", "mps", "cpu"])
43
+ def test_paint_by_example(device):
44
+ sd_steps = check_device(device)
45
+ model = ModelManager(name=model_name, device=device, disable_nsfw=True)
46
+ cfg = get_config(strategy=HDStrategy.ORIGINAL, sd_steps=sd_steps)
47
+ assert_equal(
48
+ model,
49
+ cfg,
50
+ f"paint_by_example_device_{device}.png",
51
+ img_p=current_dir / "overture-creations-5sI6fQgYIuo.png",
52
+ mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png",
53
+ fy=0.9,
54
+ fx=1.3,
55
+ )
iopaint/tests/test_plugins.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ import os
3
+ import time
4
+ from PIL import Image
5
+
6
+ from iopaint.helper import encode_pil_to_base64, gen_frontend_mask
7
+ from iopaint.plugins.anime_seg import AnimeSeg
8
+ from iopaint.schema import RunPluginRequest, RemoveBGModel
9
+ from iopaint.tests.utils import check_device, current_dir, save_dir
10
+
11
+ os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
12
+
13
+ import cv2
14
+ import pytest
15
+
16
+ from iopaint.plugins import (
17
+ RemoveBG,
18
+ RealESRGANUpscaler,
19
+ GFPGANPlugin,
20
+ RestoreFormerPlugin,
21
+ InteractiveSeg,
22
+ )
23
+
24
+ img_p = current_dir / "bunny.jpeg"
25
+ img_bytes = open(img_p, "rb").read()
26
+ bgr_img = cv2.imread(str(img_p))
27
+ rgb_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2RGB)
28
+ rgb_img_base64 = encode_pil_to_base64(Image.fromarray(rgb_img), 100, {})
29
+ bgr_img_base64 = encode_pil_to_base64(Image.fromarray(bgr_img), 100, {})
30
+
31
+
32
+ def _save(img, name):
33
+ cv2.imwrite(str(save_dir / name), img)
34
+
35
+
36
+ def test_remove_bg():
37
+ model = RemoveBG(RemoveBGModel.briaai_rmbg_1_4)
38
+ rgba_np_img = model.gen_image(
39
+ rgb_img, RunPluginRequest(name=RemoveBG.name, image=rgb_img_base64)
40
+ )
41
+ res = cv2.cvtColor(rgba_np_img, cv2.COLOR_RGBA2BGRA)
42
+ _save(res, "test_remove_bg.png")
43
+
44
+ bgr_np_img = model.gen_mask(
45
+ rgb_img, RunPluginRequest(name=RemoveBG.name, image=rgb_img_base64)
46
+ )
47
+
48
+ res_mask = gen_frontend_mask(bgr_np_img)
49
+ _save(res_mask, "test_remove_bg_frontend_mask.png")
50
+
51
+ assert len(bgr_np_img.shape) == 2
52
+ _save(bgr_np_img, "test_remove_bg_mask.jpeg")
53
+
54
+
55
+ def test_anime_seg():
56
+ model = AnimeSeg()
57
+ img = cv2.imread(str(current_dir / "anime_test.png"))
58
+ img_base64 = encode_pil_to_base64(Image.fromarray(img), 100, {})
59
+ res = model.gen_image(img, RunPluginRequest(name=AnimeSeg.name, image=img_base64))
60
+ assert len(res.shape) == 3
61
+ assert res.shape[-1] == 4
62
+ _save(res, "test_anime_seg.png")
63
+
64
+ res = model.gen_mask(img, RunPluginRequest(name=AnimeSeg.name, image=img_base64))
65
+ assert len(res.shape) == 2
66
+ _save(res, "test_anime_seg_mask.png")
67
+
68
+
69
+ @pytest.mark.parametrize("device", ["cuda", "cpu", "mps"])
70
+ def test_upscale(device):
71
+ check_device(device)
72
+ model = RealESRGANUpscaler("realesr-general-x4v3", device)
73
+ res = model.gen_image(
74
+ rgb_img,
75
+ RunPluginRequest(name=RealESRGANUpscaler.name, image=rgb_img_base64, scale=2),
76
+ )
77
+ _save(res, f"test_upscale_x2_{device}.png")
78
+
79
+ res = model.gen_image(
80
+ rgb_img,
81
+ RunPluginRequest(name=RealESRGANUpscaler.name, image=rgb_img_base64, scale=4),
82
+ )
83
+ _save(res, f"test_upscale_x4_{device}.png")
84
+
85
+
86
+ @pytest.mark.parametrize("device", ["cuda", "cpu", "mps"])
87
+ def test_gfpgan(device):
88
+ check_device(device)
89
+ model = GFPGANPlugin(device)
90
+ res = model.gen_image(
91
+ rgb_img, RunPluginRequest(name=GFPGANPlugin.name, image=rgb_img_base64)
92
+ )
93
+ _save(res, f"test_gfpgan_{device}.png")
94
+
95
+
96
+ @pytest.mark.parametrize("device", ["cuda", "cpu", "mps"])
97
+ def test_restoreformer(device):
98
+ check_device(device)
99
+ model = RestoreFormerPlugin(device)
100
+ res = model.gen_image(
101
+ rgb_img, RunPluginRequest(name=RestoreFormerPlugin.name, image=rgb_img_base64)
102
+ )
103
+ _save(res, f"test_restoreformer_{device}.png")
104
+
105
+
106
+ @pytest.mark.parametrize("device", ["cuda", "cpu", "mps"])
107
+ def test_segment_anything(device):
108
+ check_device(device)
109
+ model = InteractiveSeg("vit_l", device)
110
+ new_mask = model.gen_mask(
111
+ rgb_img,
112
+ RunPluginRequest(
113
+ name=InteractiveSeg.name,
114
+ image=rgb_img_base64,
115
+ clicks=([[448 // 2, 394 // 2, 1]]),
116
+ ),
117
+ )
118
+
119
+ save_name = f"test_segment_anything_{device}.png"
120
+ _save(new_mask, save_name)
iopaint/tests/test_save_exif.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import tempfile
3
+ from pathlib import Path
4
+ from typing import List
5
+
6
+ from PIL import Image
7
+
8
+ from iopaint.helper import pil_to_bytes, load_img
9
+
10
+ current_dir = Path(__file__).parent.absolute().resolve()
11
+
12
+
13
+ def print_exif(exif):
14
+ for k, v in exif.items():
15
+ print(f"{k}: {v}")
16
+
17
+
18
+ def extra_info(img_p: Path):
19
+ ext = img_p.suffix.strip(".")
20
+ img_bytes = img_p.read_bytes()
21
+ np_img, _, infos = load_img(img_bytes, False, True)
22
+ res_pil_bytes = pil_to_bytes(Image.fromarray(np_img), ext=ext, infos=infos)
23
+ res_img = Image.open(io.BytesIO(res_pil_bytes))
24
+ return infos, res_img.info, res_pil_bytes
25
+
26
+
27
+ def assert_keys(keys: List[str], infos, res_infos):
28
+ for k in keys:
29
+ assert k in infos
30
+ assert k in res_infos
31
+ assert infos[k] == res_infos[k]
32
+
33
+
34
+ def run_test(file_path, keys):
35
+ infos, res_infos, res_pil_bytes = extra_info(file_path)
36
+ assert_keys(keys, infos, res_infos)
37
+ with tempfile.NamedTemporaryFile("wb", suffix=file_path.suffix) as temp_file:
38
+ temp_file.write(res_pil_bytes)
39
+ temp_file.flush()
40
+ infos, res_infos, res_pil_bytes = extra_info(Path(temp_file.name))
41
+ assert_keys(keys, infos, res_infos)
42
+
43
+
44
+ def test_png_icc_profile_png():
45
+ run_test(current_dir / "icc_profile_test.png", ["icc_profile", "exif"])
46
+
47
+
48
+ def test_png_icc_profile_jpeg():
49
+ run_test(current_dir / "icc_profile_test.jpg", ["icc_profile", "exif"])
50
+
51
+
52
+ def test_jpeg():
53
+ jpg_img_p = current_dir / "bunny.jpeg"
54
+ run_test(jpg_img_p, ["dpi", "exif"])
55
+
56
+
57
+ def test_png_parameter():
58
+ jpg_img_p = current_dir / "png_parameter_test.png"
59
+ run_test(jpg_img_p, ["parameters"])
iopaint/tests/test_sd_model.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ from loguru import logger
4
+
5
+ from iopaint.tests.utils import check_device, get_config, assert_equal
6
+
7
+ os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
8
+ from pathlib import Path
9
+
10
+ import pytest
11
+ import torch
12
+
13
+ from iopaint.model_manager import ModelManager
14
+ from iopaint.schema import HDStrategy, SDSampler, FREEUConfig
15
+
16
+ current_dir = Path(__file__).parent.absolute().resolve()
17
+ save_dir = current_dir / "result"
18
+ save_dir.mkdir(exist_ok=True, parents=True)
19
+
20
+
21
+ @pytest.mark.parametrize("device", ["cuda", "mps"])
22
+ def test_runway_sd_1_5_all_samplers(device):
23
+ sd_steps = check_device(device)
24
+ model = ModelManager(
25
+ name="runwayml/stable-diffusion-inpainting",
26
+ device=torch.device(device),
27
+ disable_nsfw=True,
28
+ sd_cpu_textencoder=False,
29
+ )
30
+
31
+ all_samplers = [member.value for member in SDSampler.__members__.values()]
32
+ print(all_samplers)
33
+ for sampler in all_samplers:
34
+ print(f"Testing sampler {sampler}")
35
+ if (
36
+ sampler
37
+ in [SDSampler.dpm2_karras, SDSampler.dpm2_a_karras, SDSampler.lms_karras]
38
+ and device == "mps"
39
+ ):
40
+ # diffusers 0.25.0 still has bug on these sampler on mps, wait main branch released to fix it
41
+ logger.warning(
42
+ "skip dpm2_karras on mps, diffusers does not support it on mps. TypeError: Cannot convert a MPS Tensor to float64 dtype as the MPS framework doesn't support float64. Please use float32 instead."
43
+ )
44
+ continue
45
+ cfg = get_config(
46
+ strategy=HDStrategy.ORIGINAL,
47
+ prompt="a fox sitting on a bench",
48
+ sd_steps=sd_steps,
49
+ sd_sampler=sampler,
50
+ )
51
+
52
+ name = f"device_{device}_{sampler}"
53
+
54
+ assert_equal(
55
+ model,
56
+ cfg,
57
+ f"runway_sd_{name}.png",
58
+ img_p=current_dir / "overture-creations-5sI6fQgYIuo.png",
59
+ mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png",
60
+ )
61
+
62
+
63
+ @pytest.mark.parametrize("device", ["cuda", "mps", "cpu"])
64
+ @pytest.mark.parametrize("sampler", [SDSampler.lcm])
65
+ def test_runway_sd_lcm_lora(device, sampler):
66
+ check_device(device)
67
+
68
+ sd_steps = 5
69
+ model = ModelManager(
70
+ name="runwayml/stable-diffusion-inpainting",
71
+ device=torch.device(device),
72
+ disable_nsfw=True,
73
+ sd_cpu_textencoder=False,
74
+ )
75
+ cfg = get_config(
76
+ strategy=HDStrategy.ORIGINAL,
77
+ prompt="face of a fox, sitting on a bench",
78
+ sd_steps=sd_steps,
79
+ sd_guidance_scale=2,
80
+ sd_lcm_lora=True,
81
+ )
82
+ cfg.sd_sampler = sampler
83
+
84
+ assert_equal(
85
+ model,
86
+ cfg,
87
+ f"runway_sd_1_5_lcm_lora_device_{device}.png",
88
+ img_p=current_dir / "overture-creations-5sI6fQgYIuo.png",
89
+ mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png",
90
+ )
91
+
92
+
93
+ @pytest.mark.parametrize("device", ["cuda", "mps", "cpu"])
94
+ @pytest.mark.parametrize("sampler", [SDSampler.ddim])
95
+ def test_runway_sd_freeu(device, sampler):
96
+ sd_steps = check_device(device)
97
+ model = ModelManager(
98
+ name="runwayml/stable-diffusion-inpainting",
99
+ device=torch.device(device),
100
+ disable_nsfw=True,
101
+ sd_cpu_textencoder=False,
102
+ )
103
+ cfg = get_config(
104
+ strategy=HDStrategy.ORIGINAL,
105
+ prompt="face of a fox, sitting on a bench",
106
+ sd_steps=sd_steps,
107
+ sd_guidance_scale=7.5,
108
+ sd_freeu=True,
109
+ sd_freeu_config=FREEUConfig(),
110
+ )
111
+ cfg.sd_sampler = sampler
112
+
113
+ assert_equal(
114
+ model,
115
+ cfg,
116
+ f"runway_sd_1_5_freeu_device_{device}.png",
117
+ img_p=current_dir / "overture-creations-5sI6fQgYIuo.png",
118
+ mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png",
119
+ )
120
+
121
+
122
+ @pytest.mark.parametrize("device", ["cuda", "mps"])
123
+ @pytest.mark.parametrize("strategy", [HDStrategy.ORIGINAL])
124
+ @pytest.mark.parametrize("sampler", [SDSampler.ddim])
125
+ def test_runway_sd_sd_strength(device, strategy, sampler):
126
+ sd_steps = check_device(device)
127
+ model = ModelManager(
128
+ name="runwayml/stable-diffusion-inpainting",
129
+ device=torch.device(device),
130
+ disable_nsfw=True,
131
+ sd_cpu_textencoder=False,
132
+ )
133
+ cfg = get_config(
134
+ strategy=strategy,
135
+ prompt="a fox sitting on a bench",
136
+ sd_steps=sd_steps,
137
+ sd_strength=0.8,
138
+ )
139
+ cfg.sd_sampler = sampler
140
+
141
+ assert_equal(
142
+ model,
143
+ cfg,
144
+ f"runway_sd_strength_0.8_device_{device}.png",
145
+ img_p=current_dir / "overture-creations-5sI6fQgYIuo.png",
146
+ mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png",
147
+ )
148
+
149
+
150
+ @pytest.mark.parametrize("device", ["cuda", "cpu"])
151
+ @pytest.mark.parametrize("strategy", [HDStrategy.ORIGINAL])
152
+ @pytest.mark.parametrize("sampler", [SDSampler.ddim])
153
+ def test_runway_sd_cpu_textencoder(device, strategy, sampler):
154
+ sd_steps = check_device(device)
155
+ model = ModelManager(
156
+ name="runwayml/stable-diffusion-inpainting",
157
+ device=torch.device(device),
158
+ disable_nsfw=True,
159
+ sd_cpu_textencoder=True,
160
+ )
161
+ cfg = get_config(
162
+ strategy=strategy,
163
+ prompt="a fox sitting on a bench",
164
+ sd_steps=sd_steps,
165
+ sd_sampler=sampler,
166
+ )
167
+
168
+ assert_equal(
169
+ model,
170
+ cfg,
171
+ f"runway_sd_device_{device}_cpu_textencoder.png",
172
+ img_p=current_dir / "overture-creations-5sI6fQgYIuo.png",
173
+ mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png",
174
+ )
175
+
176
+
177
+ @pytest.mark.parametrize("device", ["cuda", "mps", "cpu"])
178
+ @pytest.mark.parametrize("strategy", [HDStrategy.ORIGINAL])
179
+ @pytest.mark.parametrize("sampler", [SDSampler.ddim])
180
+ def test_runway_norm_sd_model(device, strategy, sampler):
181
+ sd_steps = check_device(device)
182
+ model = ModelManager(
183
+ name="runwayml/stable-diffusion-v1-5",
184
+ device=torch.device(device),
185
+ disable_nsfw=True,
186
+ sd_cpu_textencoder=False,
187
+ )
188
+ cfg = get_config(
189
+ strategy=strategy, prompt="face of a fox, sitting on a bench", sd_steps=sd_steps
190
+ )
191
+ cfg.sd_sampler = sampler
192
+
193
+ assert_equal(
194
+ model,
195
+ cfg,
196
+ f"runway_{device}_norm_sd_model_device_{device}.png",
197
+ img_p=current_dir / "overture-creations-5sI6fQgYIuo.png",
198
+ mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png",
199
+ )
200
+
201
+
202
+ @pytest.mark.parametrize("device", ["cuda"])
203
+ @pytest.mark.parametrize("strategy", [HDStrategy.ORIGINAL])
204
+ @pytest.mark.parametrize("sampler", [SDSampler.dpm_plus_plus_2m])
205
+ def test_runway_sd_1_5_cpu_offload(device, strategy, sampler):
206
+ sd_steps = check_device(device)
207
+ model = ModelManager(
208
+ name="runwayml/stable-diffusion-inpainting",
209
+ device=torch.device(device),
210
+ disable_nsfw=True,
211
+ sd_cpu_textencoder=False,
212
+ cpu_offload=True,
213
+ )
214
+ cfg = get_config(
215
+ strategy=strategy, prompt="a fox sitting on a bench", sd_steps=sd_steps
216
+ )
217
+ cfg.sd_sampler = sampler
218
+
219
+ name = f"device_{device}_{sampler}"
220
+
221
+ assert_equal(
222
+ model,
223
+ cfg,
224
+ f"runway_sd_{strategy.capitalize()}_{name}_cpu_offload.png",
225
+ img_p=current_dir / "overture-creations-5sI6fQgYIuo.png",
226
+ mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png",
227
+ )
228
+
229
+
230
+ @pytest.mark.parametrize("device", ["cuda", "mps", "cpu"])
231
+ @pytest.mark.parametrize("sampler", [SDSampler.ddim])
232
+ @pytest.mark.parametrize(
233
+ "name",
234
+ [
235
+ "sd-v1-5-inpainting.safetensors",
236
+ "v1-5-pruned-emaonly.safetensors",
237
+ "sd_xl_base_1.0.safetensors",
238
+ "sd_xl_base_1.0_inpainting_0.1.safetensors",
239
+ ],
240
+ )
241
+ def test_local_file_path(device, sampler, name):
242
+ sd_steps = check_device(device)
243
+ model = ModelManager(
244
+ name=name,
245
+ device=torch.device(device),
246
+ disable_nsfw=True,
247
+ sd_cpu_textencoder=False,
248
+ cpu_offload=False,
249
+ )
250
+ cfg = get_config(
251
+ strategy=HDStrategy.ORIGINAL,
252
+ prompt="a fox sitting on a bench",
253
+ sd_steps=sd_steps,
254
+ )
255
+ cfg.sd_sampler = sampler
256
+
257
+ name = f"device_{device}_{sampler}_{name}"
258
+
259
+ is_sdxl = "sd_xl" in name
260
+
261
+ assert_equal(
262
+ model,
263
+ cfg,
264
+ f"sd_local_model_{name}.png",
265
+ img_p=current_dir / "overture-creations-5sI6fQgYIuo.png",
266
+ mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png",
267
+ fx=1.5 if is_sdxl else 1,
268
+ fy=1.5 if is_sdxl else 1,
269
+ )