File size: 8,771 Bytes
ada0ab1
 
 
 
 
 
 
 
6402ae2
d4011b4
ada0ab1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02c021a
 
ada0ab1
ef99825
ada0ab1
 
 
 
62fabfd
ada0ab1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df64a69
ada0ab1
 
 
 
 
7fae782
ada0ab1
 
 
 
 
 
c391ec5
ada0ab1
 
bff87b0
ada0ab1
 
 
 
 
df64a69
 
ada0ab1
 
 
 
7fae782
ada0ab1
 
 
05cbb25
ada0ab1
 
 
 
 
 
 
 
 
 
 
 
ebbd4e8
ada0ab1
bff87b0
ada0ab1
 
 
 
 
 
 
 
 
 
 
ef99825
ada0ab1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73270ee
62fabfd
73270ee
ada0ab1
 
 
 
 
 
62fabfd
ada0ab1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bcad7c8
 
ada0ab1
 
 
 
 
 
 
 
 
 
11cde33
ada0ab1
 
11cde33
ada0ab1
 
 
 
 
6402ae2
ada0ab1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11cde33
ada0ab1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11cde33
ada0ab1
11cde33
 
 
 
 
ada0ab1
 
 
 
 
 
 
 
 
 
 
 
11cde33
 
 
 
 
 
ada0ab1
 
 
 
 
 
 
 
 
 
 
 
 
 
11cde33
 
 
ada0ab1
11cde33
 
ada0ab1
11cde33
 
ada0ab1
 
6402ae2
 
 
ada0ab1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
import numpy as np
import torch
import cv2 as cv
import random
import os
import spaces
import gradio as gr

from rembg import remove
from PIL import Image
from transformers import pipeline
from controlnet_aux import MLSDdetector, HEDdetector, NormalBaeDetector, LineartDetector
from peft import PeftModel, LoraConfig
from diffusers import (
    DiffusionPipeline,
    StableDiffusionPipeline,
    StableDiffusionControlNetPipeline,
    StableDiffusionControlNetImg2ImgPipeline,
    DPMSolverMultistepScheduler,
    PNDMScheduler,
    ControlNetModel
)
from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import rescale_noise_cfg, retrieve_timesteps
from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
from diffusers.utils.torch_utils import randn_tensor
from diffusers.utils import load_image, make_image_grid

device = "cuda" if torch.cuda.is_available() else "cpu"

if torch.cuda.is_available():
    torch_dtype = torch.float16
else:
    torch_dtype = torch.float32

MAX_SEED = np.iinfo(np.int32).max

default_model = 'CompVis/stable-diffusion-v1-4'
LoRA_path = 'new_model'

CONTROLNET_MODE = {
    "Canny Edge Detection" : "lllyasviel/control_v11p_sd15_canny",
    "Pixel to Pixel": "lllyasviel/control_v11e_sd15_ip2p",
    "HED edge detection (soft edge)" : "lllyasviel/control_v11p_sd15_softedge",
    "Midas depth estimation" : "lllyasviel/control_v11f1p_sd15_depth",
    "Surface Normal Estimation" : "lllyasviel/control_v11p_sd15_normalbae",
    "Scribble-Based Generation" : "lllyasviel/control_v11p_sd15_scribble",
    "Line Art Generation": "lllyasviel/control_v11p_sd15_lineart",
}

def get_pipe(
    model_id,
    use_controlnet,
    controlnet_mode,
    use_ip_adapter
):

    if use_controlnet and use_ip_adapter:
        
        print('Pipe with ControlNet and IPAdapter')

        controlnet = ControlNetModel.from_pretrained(
            CONTROLNET_MODE[controlnet_mode],
            cache_dir="./models_cache"
        )

        pipe = StableDiffusionControlNetPipeline.from_pretrained(
            model_id if model_id!='Maria_Lashina_LoRA' else default_model, 
            torch_dtype=torch_dtype, 
            controlnet=controlnet,
            safety_checker=None,
        ).to(device)

        pipe.load_ip_adapter(
            "h94/IP-Adapter",
            subfolder="models",
            weight_name="ip-adapter-plus_sd15.bin",
        )

    elif use_controlnet and not use_ip_adapter:

        print('Pipe with ControlNet')

        controlnet = ControlNetModel.from_pretrained(
            CONTROLNET_MODE[controlnet_mode],
            cache_dir="./models_cache"
            )
            
        pipe = StableDiffusionControlNetPipeline.from_pretrained(
            model_id if model_id!='Maria_Lashina_LoRA' else default_model, 
            torch_dtype=torch_dtype, 
            controlnet=controlnet,
            safety_checker=None,
        ).to(device)

    elif use_ip_adapter and not use_controlnet:

        print('Pipe with IpAdapter')

        pipe = StableDiffusionPipeline.from_pretrained(
            model_id if model_id!='Maria_Lashina_LoRA' else default_model, 
            torch_dtype=torch_dtype,
            safety_checker=None,
        ).to(device)
        
        pipe.load_ip_adapter(
            "h94/IP-Adapter",
            subfolder="models",
            weight_name="ip-adapter-plus_sd15.bin")

    elif not use_controlnet and not use_ip_adapter:

        print('Pipe with only SD')

        pipe = StableDiffusionPipeline.from_pretrained(
            model_id if model_id!='Maria_Lashina_LoRA' else default_model, 
            torch_dtype=torch_dtype,
            safety_checker=None,
        ).to(device)


    if model_id == 'Maria_Lashina_LoRA':
        adapter_name = 'cartoonish mouse'
        unet_sub_dir = os.path.join(LoRA_path, "unet")
        text_encoder_sub_dir = os.path.join(LoRA_path, "text_encoder")
        
        pipe.unet = PeftModel.from_pretrained(pipe.unet, unet_sub_dir, adapter_name=adapter_name)

        pipe.text_encoder = PeftModel.from_pretrained(pipe.text_encoder, text_encoder_sub_dir, adapter_name=adapter_name)
    
    return pipe

def prepare_controlnet_image(controlnet_image, mode):
    if mode == "Canny Edge Detection":
        image = cv.Canny(controlnet_image, 80, 160)
        image = np.repeat(image[:, :, None], 3, axis=2)
        image = Image.fromarray(image)

    elif mode == "Pixel to Pixel":
        image = Image.fromarray(controlnet_image).convert('RGB')

    elif mode == "HED edge detection (soft edge)":
        processor = HEDdetector.from_pretrained('lllyasviel/Annotators')
        image = processor(controlnet_image)

    elif mode == "Midas depth estimation":
        depth_estimator = pipeline('depth-estimation')
        image = depth_estimator(Image.fromarray(controlnet_image))['depth']
        image = np.array(image)
        image = image[:, :, None]
        image = np.concatenate([image, image, image], axis=2)
        image = Image.fromarray(image)

    elif mode == "Surface Normal Estimation":
        processor = NormalBaeDetector.from_pretrained("lllyasviel/Annotators")
        image = processor(controlnet_image)

    elif mode == "Scribble-Based Generation":
        processor = HEDdetector.from_pretrained('lllyasviel/Annotators')
        image = processor(controlnet_image, scribble=True)

    elif mode == "Line Art Generation":
        processor = LineartDetector.from_pretrained("lllyasviel/Annotators")
        image = processor(controlnet_image)

    else:
        image = controlnet_image

    return image

# @spaces.GPU #[uncomment to use ZeroGPU]
def infer(
    model_id,
    prompt,
    negative_prompt,
    seed,
    randomize_seed,
    width,
    height,
    guidance_scale,
    lora_scale,
    num_inference_steps,
    use_controlnet,
    control_strength,
    controlnet_mode,
    controlnet_image,
    use_ip_adapter,
    ip_adapter_scale,
    ip_adapter_image,
    delete_background,
    progress=gr.Progress(track_tqdm=True),
):
    if randomize_seed:
        seed = random.randint(0, MAX_SEED)

    generator = torch.Generator().manual_seed(seed)

    if not use_controlnet and not use_ip_adapter:

        pipe = get_pipe(model_id, use_controlnet, controlnet_mode, use_ip_adapter)

        image = pipe(
            prompt=prompt,
            negative_prompt=negative_prompt,
            guidance_scale=guidance_scale,
            cross_attention_kwargs={"scale": lora_scale},
            num_inference_steps=num_inference_steps,
            width=width,
            height=height,
            generator=generator
        ).images[0]

    elif use_controlnet and not use_ip_adapter:
        
        cn_image = prepare_controlnet_image(controlnet_image, controlnet_mode)

        pipe = get_pipe(model_id, use_controlnet, controlnet_mode, use_ip_adapter)
        
        image = pipe(
            prompt,
            cn_image,
            controlnet_conditioning_scale=control_strength,
            negative_prompt=negative_prompt,
            guidance_scale=guidance_scale,
            cross_attention_kwargs={"scale": lora_scale},
            num_inference_steps=num_inference_steps,
            width=width,
            height=height,
            generator=generator
        ).images[0]

    elif not use_controlnet and use_ip_adapter:

        pipe = get_pipe(model_id, use_controlnet, controlnet_mode, use_ip_adapter)

        pipe.set_ip_adapter_scale(ip_adapter_scale)

        image = pipe(
            prompt,
            ip_adapter_image=ip_adapter_image,
            negative_prompt=negative_prompt,
            guidance_scale=guidance_scale,
            cross_attention_kwargs={"scale": lora_scale},
            num_inference_steps=num_inference_steps,
            width=width,
            height=height,
            generator=generator
        ).images[0]

    elif use_controlnet and use_ip_adapter:

        cn_image = prepare_controlnet_image(controlnet_image, controlnet_mode)

        pipe = get_pipe(model_id, use_controlnet, controlnet_mode, use_ip_adapter)
        
        pipe.set_ip_adapter_scale(ip_adapter_scale)

        image = pipe(
            prompt,
            cn_image,
            controlnet_conditioning_scale=control_strength,
            ip_adapter_image=ip_adapter_image,
            negative_prompt=negative_prompt,
            guidance_scale=guidance_scale,
            cross_attention_kwargs={"scale": lora_scale},
            num_inference_steps=num_inference_steps,
            width=width,
            height=height,
            generator=generator
        ).images[0]

    if delete_background:
        image = remove(image)

    return image, seed