File size: 7,345 Bytes
ce9d0da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
This Module contains funstions for loading the segmentation model and inpainting models, and editing top using a example image or text prompt.

"""

# Imports
from diffusers import DiffusionPipeline
from diffusers import StableDiffusionInpaintPipeline
from transformers import AutoFeatureExtractor, SegformerForSemanticSegmentation
from torchvision.transforms.functional import to_pil_image
from PIL import Image
import torch
import numpy as np
import urllib.request


# Functions
def load_seg(model_card: str = "mattmdjaga/segformer_b2_clothes"):
    """
    Load The Segmentation Extractor and Model.

    Parameters:
    model_card: HuggingFace Model Card. Default: mattmdjaga/segformer_b2_clothes

    Returns:
    extractor: Feature Extractor
    model: Segformer Model For Segmentation
    """
    extractor = AutoFeatureExtractor.from_pretrained(model_card)
    model = SegformerForSemanticSegmentation.from_pretrained(model_card)
    return extractor, model


def load_inpainting(using_prompt: bool = False, fast: bool = False):
    """
    Load Inpaining Model.

    Parameters:
    using_prompt: If using a prompt based inpainting model or image based inpainting model. Default: False

    Returns:
    pipe: Diffusion Pipeline mounted onto the device
    """
    device = "cuda" if torch.cuda.is_available() else "cpu"
    if using_prompt:
        if fast:
            pipe = StableDiffusionInpaintPipeline.from_pretrained(
                "runwayml/stable-diffusion-inpainting",
                revision="fp16",
                torch_dtype=torch.float16,
            )
        else:
            pipe = StableDiffusionInpaintPipeline.from_pretrained(
                "runwayml/stable-diffusion-inpainting",
                torch_dtype=torch.float32,
            )
    else:
        if fast:
            pipe = DiffusionPipeline.from_pretrained(
                "Fantasy-Studio/Paint-by-Example",
                torch_dtype=torch.float16,
            )
        else:
            pipe = DiffusionPipeline.from_pretrained(
                "Fantasy-Studio/Paint-by-Example",
                torch_dtype=torch.float32,
            )
    pipe = pipe.to(device)
    return pipe


def generate_mask(image_name: str, extractor, model):
    """
    Generate mask using Image Path and Segmentation Model.

    Parameters:
    image_name: Path to Input Image
    extractor: Feature Extractor
    model: Segmentation Model

    Returns:
    image: PIL Image of Input Image
    mask: PIL Image of Generated Mask
    """
    try:
        image = Image.open(image_name)
    except Exception as e:
        image = Image.open(urllib.request.urlopen(image_name))
    inputs = extractor(images=image, return_tensors="pt")

    outputs = model(**inputs)
    logits = outputs.logits.cpu()

    upsampled_logits = torch.nn.functional.interpolate(
        logits,
        size=image.size[::-1],
        mode="bilinear",
        align_corners=False,
    )

    pred_seg = upsampled_logits.argmax(dim=1)[0]
    pred_seg[pred_seg != 4] = 0
    pred_seg[pred_seg == 4] = 1
    pred_seg = pred_seg.to(dtype=torch.float32)
    # pred_seg = pred_seg.unsqueeze(dim = 0)
    mask = to_pil_image(pred_seg)
    return image, mask

def get_cloth(cloth_name, extractor, model):
    cloth_image, cloth_mask = generate_mask(cloth_name, extractor, model)
    cloth = np.array(cloth_image)
    cloth[np.array(cloth_mask) == 0] = 255
    return to_pil_image(cloth)

def generate_image(image, mask, pipe, example_name=None, prompt=None):
    """
    Generate Edited Image. Uses Example Image or Prompt.

    Parameters:
    image: PIL Image of The Image to Edit.
    mask: PIL Image of the Mask.
    pipe: DiffusionPipeline
    example_name: Path to Image of the cloth.
    prompt: Editing Prompt, if not using Example Image.

    Returns:
    image: PIL Image of Input Image
    mask: PIL Image of Generated Mask
    gen: PIL Image of Generated Preview
    """
    if example_name:
        try:
            example = Image.open(example_name)
        except Exception as e:
            example = Image.open(urllib.request.urlopen(example_name))
        gen = pipe(
            image=image.resize((512, 512)),
            mask_image=mask.resize((512, 512)),
            example_image=example.resize((512, 512)),
        ).images[0]
    elif prompt:
        gen = pipe(prompt=prompt, image=image, mask_image=mask).images[0]
    else:
        gen = None
        print("Neither Example Image nor Prompt provided.")
    return image, mask, gen

def generate_image_with_mask(image, mask, pipe, extractor, model, example_name=None, prompt=None):
    """
    Generate Edited Image. Uses Example Image or Prompt. Extracts the Cloth from the cloth image.

    Parameters:
    image: PIL Image of The Image to Edit.
    mask: PIL Image of the Mask.
    pipe: DiffusionPipeline
    example_name: Path to Image of the cloth.
    prompt: Editing Prompt, if not using Example Image.

    Returns:
    image: PIL Image of Input Image
    mask: PIL Image of Generated Mask
    gen: PIL Image of Generated Preview
    """
    if example_name:
        cloth = get_cloth(example_name, extractor, model)
        gen = pipe(
            image=image.resize((512, 512)),
            mask_image=mask.resize((512, 512)),
            example_image=cloth.resize((512, 512)),
        ).images[0]
    elif prompt:
        gen = pipe(prompt=prompt, image=image, mask_image=mask).images[0]
    else:
        gen = None
        print("Neither Example Image nor Prompt provided.")
    return image, mask, gen

def load(using_prompt=False):
    """
    Loads Segmentation and Inpainting Model.

    Parameters:
    using_prompt: If using a prompt based inpainting model or image based inpainting model. Default: False

    Returns:
    extractor: Feature Extractor
    model: Segformer Model For Segmentation
    pipe: Diffusion Pipeline loaded onto the device
    """
    extractor, model = load_seg()
    pipe = load_inpainting(using_prompt)
    return extractor, model, pipe


def generate(image_name, extractor, model, pipe, example_name=None, prompt=None):
    """
    Generate Preview.

    Parameters:
    image_name: Path to Input Image
    extractor: Feature Extractor
    model: Segmentation Model
    pipe: DiffusionPipeline
    example_name: Path to Image of the cloth.
    prompt: Editing Prompt, if not using Example Image.

    Returns:
    gen: PIL Image of Generated Preview
    """
    image, mask = generate_mask(image_name, extractor, model)
    res = int(mask.size[1] * 512 / mask.size[0])
    image, mask, gen = generate_image(image, mask, pipe, example_name, prompt)
    return gen.resize((512, res))

def generate_with_mask(image_name, extractor, model, pipe, example_name=None, prompt=None):
    """
    Generate Preview.

    Parameters:
    image_name: Path to Input Image
    extractor: Feature Extractor
    model: Segmentation Model
    pipe: DiffusionPipeline
    example_name: Path to Image of the cloth.
    prompt: Editing Prompt, if not using Example Image.

    Returns:
    gen: PIL Image of Generated Preview
    """
    image, mask = generate_mask(image_name, extractor, model)
    res = int(mask.size[1] * 512 / mask.size[0])
    image, mask, gen = generate_image_with_mask(image, mask, pipe, extractor, model, example_name, prompt)
    return gen.resize((512, res))