File size: 8,514 Bytes
2afcb7e
 
 
dd9e7d8
2afcb7e
 
 
 
bd9110a
0b34766
2afcb7e
 
 
 
 
bd9110a
2afcb7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd9110a
2afcb7e
0b34766
5708a7c
 
 
 
 
 
39f6ea0
5708a7c
 
 
 
 
39f6ea0
 
 
 
 
5708a7c
 
 
 
 
 
 
 
 
ff35174
39f6ea0
5708a7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39f6ea0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5708a7c
 
 
f3b9b59
5708a7c
 
dd9e7d8
39f6ea0
dd9e7d8
 
5708a7c
 
 
 
868bbe7
 
 
 
 
0b34766
5708a7c
 
 
 
 
 
 
 
 
4353573
5708a7c
 
c21a3e5
 
5708a7c
 
4353573
5708a7c
 
 
 
 
0b34766
4353573
5708a7c
 
 
 
 
2afcb7e
4353573
 
5708a7c
dd9e7d8
 
 
 
418a4e2
dd9e7d8
 
 
 
 
 
 
5708a7c
2afcb7e
5708a7c
 
 
 
 
 
 
 
 
 
 
44f95cd
5708a7c
16d15ba
 
f3b9b59
 
 
 
 
 
 
 
 
 
16d15ba
 
 
 
 
d8b3099
 
 
 
 
 
 
 
39f6ea0
 
 
 
 
 
 
 
 
 
 
 
5708a7c
 
 
 
 
 
 
 
 
39f6ea0
44f95cd
5708a7c
2afcb7e
 
5708a7c
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
from __future__ import annotations

import math
import os
import random

import gradio as gr
import torch
from diffusers import StableDiffusionInstructPix2PixPipeline
from PIL import Image, ImageOps

help_text = """
If you're not getting what you want, there may be a few reasons:
1. Is the image not changing enough? Your Image CFG weight may be too high. This value dictates how similar the output should be to the input. It's possible your edit requires larger changes from the original image, and your Image CFG weight isn't allowing that. Alternatively, your Text CFG weight may be too low. This value dictates how much to listen to the text instruction. The default Image CFG of 1.5 and Text CFG of 7.5 are a good starting point, but aren't necessarily optimal for each edit. Try:
    * Decreasing the Image CFG weight, or
    * Increasing the Text CFG weight, or
2. Conversely, is the image changing too much, such that the details in the original image aren't preserved? Try:
    * Increasing the Image CFG weight, or
    * Decreasing the Text CFG weight
3. Try generating results with different random seeds by setting "Randomize Seed" and running generation multiple times. You can also try setting "Randomize CFG" to sample new Text CFG and Image CFG values each time.
4. Rephrasing the instruction sometimes improves results (e.g., "turn him into a dog" vs. "make him a dog" vs. "as a dog").
5. Increasing the number of steps sometimes improves results.
6. Do faces look weird? The Stable Diffusion autoencoder has a hard time with faces that are small in the image. Try:
    * Cropping the image so the face takes up a larger portion of the frame.
"""


example_instructions = [
    "Make it a picasso painting",
    "as if it were by modigliani",
    "convert to a bronze statue",
    "Turn it into an anime.",
    "have it look like a graphic novel",
    "make him gain weight",
    "what would he look like bald?",
    "Have him smile",
    "Put him in a cocktail party.",
    "move him at the beach.",
    "add dramatic lighting",
    "Convert to black and white",
    "What if it were snowing?",
    "Give him a leather jacket",
    "Turn him into a cyborg!",
    "make him wear a beanie",
]

model_id = "timbrooks/instruct-pix2pix"


pipe = StableDiffusionInstructPix2PixPipeline.from_pretrained(
    model_id, torch_dtype=torch.float16, safety_checker=None
).to("cuda")
example_image = Image.open("imgs/example.jpg").convert("RGB")


def randomize(
    randomize_seed: bool,
    seed: int,
    randomize_cfg: bool,
    text_cfg_scale: float,
    image_cfg_scale: float,
) -> tuple[int, float, float]:
    seed = random.randint(0, 100000) if randomize_seed else seed
    text_cfg_scale = round(random.uniform(6.0, 9.0), ndigits=2) if randomize_cfg else text_cfg_scale
    image_cfg_scale = round(random.uniform(1.2, 1.8), ndigits=2) if randomize_cfg else image_cfg_scale
    return seed, text_cfg_scale, image_cfg_scale


def generate(
    input_image: Image.Image,
    instruction: str,
    steps: int,
    seed: int,
    text_cfg_scale: float,
    image_cfg_scale: float,
    progress=gr.Progress(track_tqdm=True),
) -> Image.Image:
    width, height = input_image.size
    factor = 512 / max(width, height)
    factor = math.ceil(min(width, height) * factor / 64) * 64 / min(width, height)
    width = int((width * factor) // 64) * 64
    height = int((height * factor) // 64) * 64
    input_image = ImageOps.fit(input_image, (width, height), method=Image.Resampling.LANCZOS)

    if instruction == "":
        return [input_image, seed]

    generator = torch.manual_seed(seed)
    edited_image = pipe(
        instruction,
        image=input_image,
        guidance_scale=text_cfg_scale,
        image_guidance_scale=image_cfg_scale,
        num_inference_steps=steps,
        generator=generator,
    ).images[0]
    return edited_image


def load_example(
    steps: int,
    randomize_seed: bool,
    seed: int,
    randomize_cfg: bool,
    text_cfg_scale: float,
    image_cfg_scale: float,
    progress=gr.Progress(track_tqdm=True),
):
    example_instruction = random.choice(example_instructions)
    seed, text_cfg_scale, image_cfg_scale = randomize(
        randomize_seed, seed, randomize_cfg, text_cfg_scale, image_cfg_scale
    )
    return [
        example_image,
        example_instruction,
        seed,
        text_cfg_scale,
        image_cfg_scale,
        generate(
            example_image,
            example_instruction,
            steps,
            seed,
            text_cfg_scale,
            image_cfg_scale,
        ),
    ]


def reset():
    return [None, 50, "Randomize Seed", 1371, "Fix CFG", 7.5, 1.5, None]


def process_example(input_image: Image.Image, instruction: str, seed: int) -> Image.Image:
    return generate(input_image, instruction, 50, seed, 7.5, 1.5)


with gr.Blocks() as demo:
    gr.HTML(
        """<h1 style="font-weight: 900; margin-bottom: 7px;">
InstructPix2Pix: Learning to Follow Image Editing Instructions
</h1>
<p>For faster inference without waiting in queue, you may duplicate the space and upgrade to GPU in settings.
<br/>
<a href="https://huggingface.co/spaces/timbrooks/instruct-pix2pix?duplicate=true">
<img style="margin-top: 0em; margin-bottom: 0em" src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>
<p/>"""
    )
    with gr.Row():
        with gr.Column(scale=1, min_width=100):
            generate_button = gr.Button("Generate")
        with gr.Column(scale=1, min_width=100):
            load_button = gr.Button("Load Example")
        with gr.Column(scale=1, min_width=100):
            reset_button = gr.Button("Reset")
        with gr.Column(scale=3):
            instruction = gr.Textbox(lines=1, label="Edit Instruction")

    with gr.Row():
        input_image = gr.Image(label="Input Image", type="pil", height=512, width=512)
        edited_image = gr.Image(label="Edited Image", type="pil", height=512, width=512)

    with gr.Row():
        steps = gr.Number(value=50, precision=0, label="Steps")
        randomize_seed = gr.Radio(
            ["Fix Seed", "Randomize Seed"],
            value="Randomize Seed",
            type="index",
            show_label=False,
        )
        seed = gr.Number(value=1371, precision=0, label="Seed")
        randomize_cfg = gr.Radio(
            ["Fix CFG", "Randomize CFG"],
            value="Fix CFG",
            type="index",
            show_label=False,
        )
        text_cfg_scale = gr.Number(value=7.5, label="Text CFG")
        image_cfg_scale = gr.Number(value=1.5, label="Image CFG")

    gr.Examples(
        examples=[
            ["imgs/example.jpg", "Turn him into a cyborg", 0],
            ["imgs/example.jpg", "Have him smile", 0],
            ["imgs/cats.jpg", "Turn kittens into baby lions", 0],
        ],
        inputs=[input_image, instruction, seed],
        outputs=edited_image,
        fn=process_example,
        cache_examples=os.getenv("CACHE_EXAMPLES") == "1",
    )

    gr.Markdown(help_text)

    load_button.click(
        fn=load_example,
        inputs=[
            steps,
            randomize_seed,
            seed,
            randomize_cfg,
            text_cfg_scale,
            image_cfg_scale,
        ],
        outputs=[input_image, instruction, seed, text_cfg_scale, image_cfg_scale, edited_image],
        api_name=False,
    )
    reset_button.click(
        fn=reset,
        outputs=[
            instruction,
            steps,
            randomize_seed,
            seed,
            randomize_cfg,
            text_cfg_scale,
            image_cfg_scale,
            edited_image,
        ],
        queue=False,
        api_name=False,
    )

    gr.on(
        triggers=[
            generate_button.click,
            instruction.submit,
            steps.submit,
            seed.submit,
            text_cfg_scale.submit,
            image_cfg_scale.submit,
        ],
        fn=randomize,
        inputs=[
            randomize_seed,
            seed,
            randomize_cfg,
            text_cfg_scale,
            image_cfg_scale,
        ],
        outputs=[seed, text_cfg_scale, image_cfg_scale],
        queue=False,
        api_name=False,
    ).then(
        fn=generate,
        inputs=[
            input_image,
            instruction,
            steps,
            seed,
            text_cfg_scale,
            image_cfg_scale,
        ],
        outputs=edited_image,
        api_name="run",
    )

if __name__ == "__main__":
    demo.queue(max_size=20).launch()