RonYin commited on
Commit
10c5105
β€’
1 Parent(s): 556bc55

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +265 -0
app.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 StableDiffusionXLImg2ImgPipeline, StableDiffusionXLPipeline, EDMEulerScheduler, StableDiffusionXLInstructPix2PixPipeline, AutoencoderKL, DPMSolverMultistepScheduler
10
+ from huggingface_hub import hf_hub_download, InferenceClient
11
+
12
+ vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
13
+ pipe = StableDiffusionXLPipeline.from_pretrained("SG161222/RealVisXL_V4.0", torch_dtype=torch.float16, vae=vae)
14
+ pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config, use_karras_sigmas=True, algorithm_type="sde-dpmsolver++")
15
+ pipe.to("cuda")
16
+
17
+ refiner = StableDiffusionXLImg2ImgPipeline.from_pretrained("stabilityai/stable-diffusion-xl-refiner-1.0", vae=vae, torch_dtype=torch.float16, use_safetensors=True, variant="fp16")
18
+ refiner.to("cuda")
19
+
20
+ pipe_fast = StableDiffusionXLPipeline.from_pretrained("SG161222/RealVisXL_V4.0_Lightning", torch_dtype=torch.float16, vae=vae, use_safetensors=True)
21
+ pipe_fast.to("cuda")
22
+
23
+ help_text = """
24
+ To optimize image results:
25
+ - 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.
26
+ - 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.
27
+ - Experiment with different **random seeds** and **CFG values** for varied outcomes.
28
+ - **Rephrase your instructions** for potentially better results.
29
+ - **Increase the number of steps** for enhanced edits.
30
+ """
31
+
32
+ def set_timesteps_patched(self, num_inference_steps: int, device = None):
33
+ self.num_inference_steps = num_inference_steps
34
+
35
+ ramp = np.linspace(0, 1, self.num_inference_steps)
36
+ sigmas = torch.linspace(math.log(self.config.sigma_min), math.log(self.config.sigma_max), len(ramp)).exp().flip(0)
37
+
38
+ sigmas = (sigmas).to(dtype=torch.float32, device=device)
39
+ self.timesteps = self.precondition_noise(sigmas)
40
+
41
+ self.sigmas = torch.cat([sigmas, torch.zeros(1, device=sigmas.device)])
42
+ self._step_index = None
43
+ self._begin_index = None
44
+ self.sigmas = self.sigmas.to("cpu")
45
+
46
+ # Image Editor
47
+ edit_file = hf_hub_download(repo_id="stabilityai/cosxl", filename="cosxl_edit.safetensors")
48
+ EDMEulerScheduler.set_timesteps = set_timesteps_patched
49
+ pipe_edit = StableDiffusionXLInstructPix2PixPipeline.from_single_file( edit_file, num_in_channels=8, is_cosxl_edit=True, vae=vae, torch_dtype=torch.float16 )
50
+ pipe_edit.scheduler = EDMEulerScheduler(sigma_min=0.002, sigma_max=120.0, sigma_data=1.0, prediction_type="v_prediction")
51
+ pipe_edit.to("cuda")
52
+
53
+ client1 = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
54
+ system_instructions1 = "<|system|>\nAct as Image Prompt Generation expert, Your task is to modify prompt by USER to more better prompt for Image Generation in Stable Diffusion XL. \n Modify the user's prompt to generate a high-quality image by incorporating essential keywords and styles according to prompt if none style is mentioned than assume realistic. The optimized prompt may include keywords according to prompt for resolution (4K, HD, 16:9 aspect ratio, , etc.), image quality (cute, masterpiece, high-quality, vivid colors, intricate details, etc.), and desired art styles (realistic, anime, 3D, logo, futuristic, fantasy, etc.). Ensure the prompt is concise, yet comprehensive and choose keywords wisely, to generate an exceptional image that meets the user's expectations. \n Your task is to reply with final optimized prompt only. If you get big prompt make it concise. and Apply all keyword at last of prompt. Reply with optimized prompt only.\n<|user|>\n"
55
+
56
+ def promptifier(prompt):
57
+ formatted_prompt = f"{system_instructions1}{prompt}\n<|assistant|>\n"
58
+ stream = client1.text_generation(formatted_prompt, max_new_tokens=100)
59
+ return stream
60
+
61
+ # Generator
62
+ @spaces.GPU(duration=60, queue=False)
63
+ def king(type ,
64
+ input_image ,
65
+ instruction: str ,
66
+ negative_prompt: str ="",
67
+ enhance_prompt: bool = True,
68
+ steps: int = 25,
69
+ randomize_seed: bool = True,
70
+ seed: int = 2404,
71
+ width: int = 1024,
72
+ height: int = 1024,
73
+ guidance_scale: float = 6,
74
+ fast=True,
75
+ progress=gr.Progress(track_tqdm=True)
76
+ ):
77
+ if type=="Image Editing" :
78
+ input_image = Image.open(input_image).convert('RGB')
79
+ if randomize_seed:
80
+ seed = random.randint(0, 999999)
81
+ generator = torch.manual_seed(seed)
82
+ output_image = pipe_edit(
83
+ instruction, negative_prompt=negative_prompt, image=input_image,
84
+ guidance_scale=guidance_scale, image_guidance_scale=1.5,
85
+ width = input_image.width, height = input_image.height,
86
+ num_inference_steps=steps, generator=generator, output_type="latent",
87
+ ).images
88
+ refine = refiner(
89
+ prompt=f"{instruction}, 4k, hd, high quality, masterpiece",
90
+ negative_prompt = negative_prompt,
91
+ guidance_scale=7.5,
92
+ num_inference_steps=steps,
93
+ image=output_image,
94
+ generator=generator,
95
+ ).images[0]
96
+ return seed, refine
97
+ else :
98
+ if randomize_seed:
99
+ seed = random.randint(0, 999999)
100
+ generator = torch.Generator().manual_seed(seed)
101
+ if enhance_prompt:
102
+ print(f"BEFORE: {instruction} ")
103
+ instruction = promptifier(instruction)
104
+ print(f"AFTER: {instruction} ")
105
+ guidance_scale2=(guidance_scale/2)
106
+ if fast:
107
+ refine = pipe_fast(prompt = instruction,
108
+ guidance_scale = guidance_scale2,
109
+ num_inference_steps = int(steps/2.5),
110
+ width = width, height = height,
111
+ generator = generator,
112
+ ).images[0]
113
+ else:
114
+ image = pipe_fast( prompt = instruction,
115
+ negative_prompt=negative_prompt,
116
+ guidance_scale = guidance_scale,
117
+ num_inference_steps = steps,
118
+ width = width, height = height,
119
+ generator = generator, output_type="latent",
120
+ ).images
121
+
122
+ refine = refiner( prompt=instruction,
123
+ negative_prompt = negative_prompt,
124
+ guidance_scale = 7.5,
125
+ num_inference_steps= steps,
126
+ image=image, generator=generator,
127
+ ).images[0]
128
+ return seed, refine
129
+
130
+ client = InferenceClient()
131
+ # Prompt classifier
132
+ def response(instruction, input_image=None ):
133
+ if input_image is None:
134
+ output="Image Generation"
135
+ else:
136
+ try:
137
+ text = instruction
138
+ labels = ["Image Editing", "Image Generation"]
139
+ classification = client.zero_shot_classification(text, labels, multi_label=True)
140
+ output = classification[0]
141
+ output = str(output)
142
+ if "Editing" in output:
143
+ output = "Image Editing"
144
+ else:
145
+ output = "Image Generation"
146
+ except:
147
+ if input_image is None:
148
+ output="Image Generation"
149
+ else:
150
+ output="Image Editing"
151
+ return output
152
+
153
+ css = '''
154
+ .gradio-container{max-width: 700px !important}
155
+ h1{text-align:center}
156
+ footer {
157
+ visibility: hidden
158
+ }
159
+ '''
160
+
161
+ examples=[
162
+ [
163
+ "Image Generation",
164
+ None,
165
+ "A luxurious supercar with a unique design. The car should have a pearl white finish, and gold accents. 4k, realistic.",
166
+
167
+ ],
168
+ [
169
+ "Image Editing",
170
+ "./supercar.png",
171
+ "make it red",
172
+
173
+ ],
174
+ [
175
+ "Image Editing",
176
+ "./red_car.png",
177
+ "add some snow",
178
+
179
+ ],
180
+ [
181
+ "Image Generation",
182
+ None,
183
+ "An alien grasping a sign board contain word 'ALIEN' with Neon Glow, neon, futuristic, neonpunk, neon lights",
184
+ ],
185
+ [
186
+ "Image Generation",
187
+ None,
188
+ "Beautiful Eiffel Tower at Night",
189
+ ],
190
+ [
191
+ "Image Generation",
192
+ None,
193
+ "Beautiful Eiffel Tower at Night",
194
+ ],
195
+ ]
196
+
197
+ with gr.Blocks(css=css) as demo:
198
+ gr.Markdown("# Image Generation , Image Editing \n ### Note: First image generation takes time")
199
+ with gr.Row():
200
+ instruction = gr.Textbox(lines=1, label="Instruction", interactive=True)
201
+ generate_button = gr.Button("Run", scale=0)
202
+ with gr.Row():
203
+ type = gr.Dropdown(["Image Generation","Image Editing"], label="Task", value="Image Generation",interactive=True)
204
+ enhance_prompt = gr.Checkbox(label="Enhance prompt", value=False, scale=0)
205
+ fast = gr.Checkbox(label="FAST Generation", value=True, scale=0)
206
+
207
+ with gr.Row():
208
+ input_image = gr.Image(label="Image", type='filepath', interactive=True)
209
+
210
+ with gr.Row():
211
+ guidance_scale = gr.Number(value=6.0, step=0.1, label="Guidance Scale", interactive=True)
212
+ steps = gr.Number(value=25, step=1, label="Steps", interactive=True)
213
+
214
+ with gr.Accordion("Advanced options", open=False):
215
+ with gr.Row():
216
+ negative_prompt = gr.Text(
217
+ label="Negative prompt",
218
+ max_lines=1,
219
+ value="(deformed, distorted, disfigured:1.3), poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, (mutated hands and fingers:1.4), disconnected limbs, ugly, disgusting, blurry, amputation,(face asymmetry, eyes asymmetry, deformed eyes, open mouth)",
220
+ visible=True)
221
+ with gr.Row():
222
+ width = gr.Slider( label="Width", minimum=256, maximum=2048, step=64, value=1024)
223
+ height = gr.Slider( label="Height", minimum=256, maximum=2048, step=64, value=1024)
224
+ with gr.Row():
225
+ randomize_seed = gr.Checkbox(label="Randomize Seed", value = True, interactive=True )
226
+ seed = gr.Number(value=2404, step=1, label="Seed", interactive=True)
227
+
228
+ gr.Examples(
229
+ examples=examples,
230
+ inputs=[type,input_image, instruction],
231
+ fn=king,
232
+ outputs=[input_image],
233
+ cache_examples=False,
234
+ )
235
+
236
+ # gr.Markdown(help_text)
237
+
238
+ instruction.change(fn=response, inputs=[instruction,input_image], outputs=type, queue=False)
239
+
240
+ input_image.upload(fn=response, inputs=[instruction,input_image], outputs=type, queue=False)
241
+
242
+ gr.on(triggers=[
243
+ generate_button.click,
244
+ instruction.submit
245
+ ],
246
+ fn=king,
247
+ inputs=[type,
248
+ input_image,
249
+ instruction,
250
+ negative_prompt,
251
+ enhance_prompt,
252
+ steps,
253
+ randomize_seed,
254
+ seed,
255
+ width,
256
+ height,
257
+ guidance_scale,
258
+ fast,
259
+ ],
260
+ outputs=[seed, input_image],
261
+ api_name = "image_gen_pro",
262
+ queue=False
263
+ )
264
+
265
+ demo.queue(max_size=500).launch()