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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
import math
|
3 |
+
import random
|
4 |
+
import spaces
|
5 |
+
import gradio as gr
|
6 |
+
import numpy as np
|
7 |
+
import torch
|
8 |
+
from PIL import Image
|
9 |
+
from diffusers import StableDiffusionXLPipeline, EDMEulerScheduler, StableDiffusionXLInstructPix2PixPipeline, AutoencoderKL
|
10 |
+
from custom_pipeline import CosStableDiffusionXLInstructPix2PixPipeline
|
11 |
+
from huggingface_hub import hf_hub_download
|
12 |
+
from huggingface_hub import InferenceClient
|
13 |
+
|
14 |
+
|
15 |
+
help_text = """
|
16 |
+
To optimize image results:
|
17 |
+
- 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.
|
18 |
+
- 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.
|
19 |
+
- Experiment with different **random seeds** and **CFG values** for varied outcomes.
|
20 |
+
- **Rephrase your instructions** for potentially better results.
|
21 |
+
- **Increase the number of steps** for enhanced edits.
|
22 |
+
"""
|
23 |
+
|
24 |
+
def set_timesteps_patched(self, num_inference_steps: int, device = None):
|
25 |
+
self.num_inference_steps = num_inference_steps
|
26 |
+
|
27 |
+
ramp = np.linspace(0, 1, self.num_inference_steps)
|
28 |
+
sigmas = torch.linspace(math.log(self.config.sigma_min), math.log(self.config.sigma_max), len(ramp)).exp().flip(0)
|
29 |
+
|
30 |
+
sigmas = (sigmas).to(dtype=torch.float32, device=device)
|
31 |
+
self.timesteps = self.precondition_noise(sigmas)
|
32 |
+
|
33 |
+
self.sigmas = torch.cat([sigmas, torch.zeros(1, device=sigmas.device)])
|
34 |
+
self._step_index = None
|
35 |
+
self._begin_index = None
|
36 |
+
self.sigmas = self.sigmas.to("cpu")
|
37 |
+
|
38 |
+
# Image Editor
|
39 |
+
edit_file = hf_hub_download(repo_id="stabilityai/cosxl", filename="cosxl_edit.safetensors")
|
40 |
+
normal_file = hf_hub_download(repo_id="stabilityai/cosxl", filename="cosxl.safetensors")
|
41 |
+
|
42 |
+
EDMEulerScheduler.set_timesteps = set_timesteps_patched
|
43 |
+
|
44 |
+
vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
|
45 |
+
|
46 |
+
pipe_edit = StableDiffusionXLInstructPix2PixPipeline.from_single_file(
|
47 |
+
edit_file, num_in_channels=8, is_cosxl_edit=True, vae=vae, torch_dtype=torch.float16,
|
48 |
+
)
|
49 |
+
pipe_edit.scheduler = EDMEulerScheduler(sigma_min=0.002, sigma_max=120.0, sigma_data=1.0, prediction_type="v_prediction")
|
50 |
+
pipe_edit.to("cuda")
|
51 |
+
|
52 |
+
from diffusers import StableDiffusionXLPipeline, EulerAncestralDiscreteScheduler
|
53 |
+
|
54 |
+
if not torch.cuda.is_available():
|
55 |
+
DESCRIPTION += "\n<p>Running on CPU 🥶 This demo may not work on CPU.</p>"
|
56 |
+
|
57 |
+
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
58 |
+
|
59 |
+
|
60 |
+
# Image Generator
|
61 |
+
if torch.cuda.is_available():
|
62 |
+
pipe = StableDiffusionXLPipeline.from_pretrained(
|
63 |
+
"fluently/Fluently-XL-v4",
|
64 |
+
torch_dtype=torch.float16,
|
65 |
+
use_safetensors=True,
|
66 |
+
)
|
67 |
+
pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
|
68 |
+
pipe.load_lora_weights("ehristoforu/dalle-3-xl-v2", weight_name="dalle-3-xl-lora-v2.safetensors", adapter_name="dalle")
|
69 |
+
pipe.set_adapters("dalle")
|
70 |
+
|
71 |
+
def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
|
72 |
+
if randomize_seed:
|
73 |
+
seed = random.randint(0, 999999)
|
74 |
+
return seed
|
75 |
+
|
76 |
+
# Generator
|
77 |
+
@spaces.GPU(duration=30, queue=False)
|
78 |
+
def king(type = "Image Generation",
|
79 |
+
input_image = None,
|
80 |
+
instruction: str = "Eiffel tower",
|
81 |
+
steps: int = 8,
|
82 |
+
randomize_seed: bool = False,
|
83 |
+
seed: int = 25,
|
84 |
+
text_cfg_scale: float = 7.3,
|
85 |
+
image_cfg_scale: float = 1.7,
|
86 |
+
width: int = 1024,
|
87 |
+
height: int = 1024,
|
88 |
+
guidance_scale: float = 6.2,
|
89 |
+
use_resolution_binning: bool = True,
|
90 |
+
progress=gr.Progress(track_tqdm=True),
|
91 |
+
):
|
92 |
+
if type=="Image Editing" :
|
93 |
+
seed = int(randomize_seed_fn(seed, randomize_seed))
|
94 |
+
text_cfg_scale = text_cfg_scale
|
95 |
+
image_cfg_scale = image_cfg_scale
|
96 |
+
input_image = input_image
|
97 |
+
|
98 |
+
steps=steps
|
99 |
+
generator = torch.manual_seed(seed)
|
100 |
+
output_image = pipe_edit(
|
101 |
+
instruction, image=input_image,
|
102 |
+
guidance_scale=text_cfg_scale, image_guidance_scale=image_cfg_scale,
|
103 |
+
num_inference_steps=steps, generator=generator).images[0]
|
104 |
+
return seed, output_image
|
105 |
+
else :
|
106 |
+
pipe.to(device)
|
107 |
+
seed = int(randomize_seed_fn(seed, randomize_seed))
|
108 |
+
generator = torch.Generator().manual_seed(seed)
|
109 |
+
|
110 |
+
options = {
|
111 |
+
"prompt":instruction,
|
112 |
+
"width":width,
|
113 |
+
"height":height,
|
114 |
+
"guidance_scale":guidance_scale,
|
115 |
+
"num_inference_steps":steps,
|
116 |
+
"generator":generator,
|
117 |
+
"use_resolution_binning":use_resolution_binning,
|
118 |
+
"output_type":"pil",
|
119 |
+
}
|
120 |
+
|
121 |
+
output_image = pipe(**options).images[0]
|
122 |
+
return seed, output_image
|
123 |
+
|
124 |
+
# Prompt classifier
|
125 |
+
def response(instruction, input_image=None):
|
126 |
+
if input_image is None:
|
127 |
+
output="Image Generation"
|
128 |
+
yield output
|
129 |
+
else:
|
130 |
+
client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
|
131 |
+
|
132 |
+
generate_kwargs = dict(
|
133 |
+
max_new_tokens=5,
|
134 |
+
)
|
135 |
+
|
136 |
+
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]"
|
137 |
+
|
138 |
+
formatted_prompt = system + instruction + "[TASK]"
|
139 |
+
stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False)
|
140 |
+
output = ""
|
141 |
+
for response in stream:
|
142 |
+
if not response.token.text == "</s>":
|
143 |
+
output += response.token.text
|
144 |
+
if "editing" in output:
|
145 |
+
output = "Image Editing"
|
146 |
+
else:
|
147 |
+
output = "Image Generation"
|
148 |
+
yield output
|
149 |
+
return output
|
150 |
+
|
151 |
+
css = '''
|
152 |
+
.gradio-container{max-width: 600px !important}
|
153 |
+
h1{text-align:center}
|
154 |
+
footer {
|
155 |
+
visibility: hidden
|
156 |
+
}
|
157 |
+
'''
|
158 |
+
|
159 |
+
examples=[
|
160 |
+
[
|
161 |
+
"Image Generation",
|
162 |
+
None,
|
163 |
+
"A Super Car",
|
164 |
+
|
165 |
+
],
|
166 |
+
[
|
167 |
+
"Image Editing",
|
168 |
+
"./supercar.png",
|
169 |
+
"make it red",
|
170 |
+
|
171 |
+
],
|
172 |
+
[
|
173 |
+
"Image Editing",
|
174 |
+
"./red_car.png",
|
175 |
+
"add some snow",
|
176 |
+
|
177 |
+
],
|
178 |
+
[
|
179 |
+
"Image Generation",
|
180 |
+
None,
|
181 |
+
"Kids going o school, Anime style",
|
182 |
+
|
183 |
+
],
|
184 |
+
[
|
185 |
+
"Image Generation",
|
186 |
+
None,
|
187 |
+
"Beautiful Eiffel Tower at Night",
|
188 |
+
|
189 |
+
],
|
190 |
+
]
|
191 |
+
|
192 |
+
with gr.Blocks(css=css) as demo:
|
193 |
+
gr.Markdown("# Image Generator Pro")
|
194 |
+
with gr.Row():
|
195 |
+
with gr.Column(scale=4):
|
196 |
+
instruction = gr.Textbox(lines=1, label="Instruction", interactive=True)
|
197 |
+
with gr.Column(scale=1):
|
198 |
+
type = gr.Dropdown(["Image Generation","Image Editing"], label="Task", value="Image Generation",interactive=True, info="AI will select option based on your query, but if it selects wrong, please choose correct one.")
|
199 |
+
with gr.Column(scale=1):
|
200 |
+
generate_button = gr.Button("Generate")
|
201 |
+
|
202 |
+
with gr.Row():
|
203 |
+
input_image = gr.Image(label="Image", type="pil", interactive=True)
|
204 |
+
|
205 |
+
with gr.Row():
|
206 |
+
text_cfg_scale = gr.Number(value=7.3, step=0.1, label="Text CFG", interactive=True)
|
207 |
+
image_cfg_scale = gr.Number(value=1.7, step=0.1,label="Image CFG", interactive=True)
|
208 |
+
steps = gr.Number(value=25, precision=0, label="Steps", interactive=True)
|
209 |
+
randomize_seed = gr.Radio(
|
210 |
+
["Fix Seed", "Randomize Seed"],
|
211 |
+
value="Randomize Seed",
|
212 |
+
type="index",
|
213 |
+
show_label=False,
|
214 |
+
interactive=True,
|
215 |
+
)
|
216 |
+
seed = gr.Number(value=1371, precision=0, label="Seed", interactive=True)
|
217 |
+
|
218 |
+
gr.Examples(
|
219 |
+
examples=examples,
|
220 |
+
inputs=[type,input_image, instruction],
|
221 |
+
fn=king,
|
222 |
+
outputs=[input_image],
|
223 |
+
cache_examples=False,
|
224 |
+
)
|
225 |
+
|
226 |
+
gr.Markdown(help_text)
|
227 |
+
|
228 |
+
instruction.change(fn=response, inputs=[instruction,input_image], outputs=type, queue=False)
|
229 |
+
|
230 |
+
input_image.upload(fn=response, inputs=[instruction,input_image], outputs=type, queue=False)
|
231 |
+
|
232 |
+
gr.on(triggers=[
|
233 |
+
generate_button.click,
|
234 |
+
instruction.submit
|
235 |
+
],
|
236 |
+
fn=king,
|
237 |
+
inputs=[type,
|
238 |
+
input_image,
|
239 |
+
instruction,
|
240 |
+
steps,
|
241 |
+
randomize_seed,
|
242 |
+
seed,
|
243 |
+
text_cfg_scale,
|
244 |
+
image_cfg_scale,
|
245 |
+
],
|
246 |
+
outputs=[seed, input_image],
|
247 |
+
)
|
248 |
+
|
249 |
+
demo.queue(max_size=99999).launch()
|