File size: 8,150 Bytes
0f8ec45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f1a540
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f8ec45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f1a540
 
 
 
 
 
 
 
0f8ec45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations
import uuid
import os
import math
import random
import spaces
import gradio as gr
import torch
from PIL import Image, ImageOps
from diffusers import StableDiffusionInstructPix2PixPipeline
from huggingface_hub import InferenceClient

help_text = """
To optimize image editing results:
- Adjust the **Image CFG weight** if the image isn't changing enough or is changing too much. Lower it to allow bigger changes, or raise it to preserve original details.
- Modify the **Text CFG weight** to influence how closely the edit follows text instructions. Increase it to adhere more to the text, or decrease it for subtler changes.
- Experiment with different **random seeds** and **CFG values** for varied outcomes.
- **Rephrase your instructions** for potentially better results.
- **Increase the number of steps** for enhanced edits.
- For better facial details, especially if they're small, **crop the image** to enlarge the face's presence.
"""

model_id = "timbrooks/instruct-pix2pix"

from diffusers import StableDiffusionXLPipeline, EulerAncestralDiscreteScheduler

if not torch.cuda.is_available():
    DESCRIPTION += "\n<p>Running on CPU 🥶 This demo may not work on CPU.</p>"
    
MAX_IMAGE_SIZE = int(os.getenv("MAX_IMAGE_SIZE", "4096"))

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

if torch.cuda.is_available():
    pipe = StableDiffusionXLPipeline.from_pretrained(
        "sd-community/sdxl-flash",
        torch_dtype=torch.float16,
        use_safetensors=True,
        add_watermarker=False
    )
    pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)

def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
    if randomize_seed:
        seed = random.randint(0, 999999)
    return seed

def resize_image(image, output_size=(512, 512)):
    # Calculate aspect ratios
    target_aspect = output_size[0] / output_size[1]  # Aspect ratio of the desired size
    image_aspect = image.width / image.height  # Aspect ratio of the original image

    # Resize then crop if the original image is larger
    if image_aspect > target_aspect:
        new_height = output_size[1]
        new_width = int(new_height * image_aspect)
        resized_image = image.resize((new_width, new_height), Image.LANCZOS)
        left = (new_width - output_size[0]) / 2
        top = 0
        right = (new_width + output_size[0]) / 2
        bottom = output_size[1]
    else:
        new_width = output_size[0]
        new_height = int(new_width / image_aspect)
        resized_image = image.resize((new_width, new_height), Image.LANCZOS)
        left = 0
        top = (new_height - output_size[1]) / 2
        right = output_size[0]
        bottom = (new_height + output_size[1]) / 2
    cropped_image = resized_image.crop((left, top, right, bottom))
    return cropped_image

pipe2 = StableDiffusionInstructPix2PixPipeline.from_pretrained(model_id, torch_dtype=torch.float16, safety_checker=None).to("cuda")

@spaces.GPU(duration=30, queue=False)
def king(type = "Image Editing",
        input_image = None,
        instruction: str = "Eiffel tower",
        steps: int = 8,
        randomize_seed: bool = False,
        seed: int = 24,
        text_cfg_scale: float = 7.3,
        image_cfg_scale: float = 1.7,
        width: int = 1024,
        height: int = 1024,
        guidance_scale: float = 3,
        use_resolution_binning: bool = True,
        progress=gr.Progress(track_tqdm=True),
    ):
    if type=="Image Generation" :
        pipe.to(device)
        seed = int(randomize_seed_fn(seed, randomize_seed))
        generator = torch.Generator().manual_seed(seed)   
        
        options = {
            "prompt":instruction,
            "width":width,
            "height":height,
            "guidance_scale":guidance_scale,
            "num_inference_steps":steps,
            "generator":generator,
            "use_resolution_binning":use_resolution_binning,
            "output_type":"pil",
        }
        
        output_image = pipe(**options).images[0]
        return seed, output_image
    else:
        seed = int(randomize_seed_fn(seed, randomize_seed))
        text_cfg_scale = text_cfg_scale
        image_cfg_scale = image_cfg_scale
        input_image = input_image

        steps=steps*6
        generator = torch.manual_seed(seed)
        output_image = pipe2(
            instruction, image=input_image,
            guidance_scale=text_cfg_scale, image_guidance_scale=image_cfg_scale,
            num_inference_steps=steps, generator=generator).images[0]
        return seed, output_image
    
def response(instruction, input_image=None):
    client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
        
    generate_kwargs = dict(
            max_new_tokens=5,
        )

    system="[SYSTEM] You will be provided with text, and your task is to classify task is image generation or image editing answer with only task do not say anything else and stop as soon as possible. [TEXT]"
        
    formatted_prompt = system + instruction + "[TASK]"
    stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False)
    output = ""
    for response in stream:        
        if not response.token.text == "</s>":
            output += response.token.text

    if input_image is None:
        output="Image Generation"
        
    if "editing" in output:
        output = "Image Editing"
    else:
        output = "Image Generation"
    return output

css = '''
.gradio-container{max-width: 600px !important}
h1{text-align:center}
footer {
    visibility: hidden
}
'''

def get_example():
    case = [
        [
            "Image Generation",
            None,
            "A Super Car",
        ],
        [
            "Image Editing",
            "./supercar.png",
            "make it red",
        ],
        [
            "Image Editing",
            "./red_car.png",
            "add some snow",
        ],
        [
            "Image Generation",
            None,
            "Ironman flying in front of Ststue of liberty",
        ],
        [
            "Image Generation",
            None,
            "Beautiful Eiffel Tower at Night",
        ],
    ]
    return case

with gr.Blocks(css=css) as demo:
    gr.Markdown("# Image Generator Pro")
    with gr.Row():
        with gr.Column(scale=4):
            instruction = gr.Textbox(lines=1, label="Instruction", interactive=True)
        with gr.Column(scale=1):
            generate_button = gr.Button("Generate")
        with gr.Column(scale=1):
            type = gr.Dropdown(["Image Generation","Image Editing"], label="Task", value="Image Generation",interactive=True, visible=False)

    with gr.Row():
        input_image = gr.Image(label="Image", type="pil", interactive=True)

    with gr.Row():
        text_cfg_scale = gr.Number(value=7.3, step=0.1, label="Text CFG", interactive=True)
        image_cfg_scale = gr.Number(value=1.7, step=0.1,label="Image CFG", interactive=True)
        steps = gr.Number(value=8, precision=0, label="Steps", interactive=True)
        randomize_seed = gr.Radio(
                ["Fix Seed", "Randomize Seed"],
                value="Randomize Seed",
                type="index",
                show_label=False,
                interactive=True,
            )
        seed = gr.Number(value=1371, precision=0, label="Seed", interactive=True)

    gr.Examples(
        examples=get_example(),
        inputs=[type,input_image, instruction],
        fn=king,
        outputs=[input_image],
        cache_examples=True,
    )

    gr.Markdown(help_text)

    instruction.change(fn=response, inputs=[instruction,input_image], outputs=type, queue=False)
        
    generate_button.click(
            fn=king,
            inputs=[type,
                input_image,
                instruction,
                steps,
                randomize_seed,
                seed,
                text_cfg_scale,
                image_cfg_scale,
            ],
            outputs=[seed, input_image],
        )

demo.queue(max_size=99999).launch()