Spaces:
Build error
Build error
AI-Journey2
commited on
Commit
•
d702758
1
Parent(s):
95b0926
Update app.py
Browse files
app.py
CHANGED
@@ -1,146 +1,327 @@
|
|
1 |
import gradio as gr
|
2 |
-
import
|
3 |
-
import
|
4 |
-
|
5 |
-
import
|
|
|
|
|
|
|
|
|
6 |
|
7 |
-
device = "cuda" if torch.cuda.is_available() else "cpu"
|
8 |
|
9 |
-
if torch.cuda.is_available():
|
10 |
-
torch.cuda.max_memory_allocated(device=device)
|
11 |
-
pipe = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo", torch_dtype=torch.float16, variant="fp16", use_safetensors=True)
|
12 |
-
pipe.enable_xformers_memory_efficient_attention()
|
13 |
-
pipe = pipe.to(device)
|
14 |
-
else:
|
15 |
-
pipe = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo", use_safetensors=True)
|
16 |
-
pipe = pipe.to(device)
|
17 |
|
18 |
-
|
19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
20 |
|
21 |
-
def
|
|
|
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 |
-
if torch.cuda.is_available():
|
54 |
-
power_device = "GPU"
|
55 |
-
else:
|
56 |
-
power_device = "CPU"
|
57 |
-
|
58 |
with gr.Blocks(css=css) as demo:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
59 |
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
|
78 |
-
|
79 |
-
|
80 |
-
with gr.Accordion("Advanced Settings", open=False):
|
81 |
-
|
82 |
-
negative_prompt = gr.Text(
|
83 |
-
label="Negative prompt",
|
84 |
-
max_lines=1,
|
85 |
-
placeholder="Enter a negative prompt",
|
86 |
-
visible=False,
|
87 |
-
)
|
88 |
-
|
89 |
-
seed = gr.Slider(
|
90 |
-
label="Seed",
|
91 |
-
minimum=0,
|
92 |
-
maximum=MAX_SEED,
|
93 |
-
step=1,
|
94 |
-
value=0,
|
95 |
-
)
|
96 |
-
|
97 |
-
randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
|
98 |
-
|
99 |
with gr.Row():
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
value=512,
|
107 |
-
)
|
108 |
-
|
109 |
-
height = gr.Slider(
|
110 |
-
label="Height",
|
111 |
-
minimum=256,
|
112 |
-
maximum=MAX_IMAGE_SIZE,
|
113 |
-
step=32,
|
114 |
-
value=512,
|
115 |
-
)
|
116 |
-
|
117 |
with gr.Row():
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
134 |
|
135 |
-
gr.
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
+
import requests
|
3 |
+
import time
|
4 |
+
import json
|
5 |
+
import base64
|
6 |
+
import os
|
7 |
+
from io import BytesIO
|
8 |
+
import html
|
9 |
+
import re
|
10 |
|
|
|
11 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
|
13 |
+
class Prodia:
|
14 |
+
def __init__(self, api_key, base=None):
|
15 |
+
self.base = base or "https://api.prodia.com/v1"
|
16 |
+
self.headers = {
|
17 |
+
"X-Prodia-Key": api_key
|
18 |
+
}
|
19 |
+
|
20 |
+
def generate(self, params):
|
21 |
+
response = self._post(f"{self.base}/sd/generate", params)
|
22 |
+
return response.json()
|
23 |
+
|
24 |
+
def transform(self, params):
|
25 |
+
response = self._post(f"{self.base}/sd/transform", params)
|
26 |
+
return response.json()
|
27 |
+
|
28 |
+
def controlnet(self, params):
|
29 |
+
response = self._post(f"{self.base}/sd/controlnet", params)
|
30 |
+
return response.json()
|
31 |
+
|
32 |
+
def get_job(self, job_id):
|
33 |
+
response = self._get(f"{self.base}/job/{job_id}")
|
34 |
+
return response.json()
|
35 |
|
36 |
+
def wait(self, job):
|
37 |
+
job_result = job
|
38 |
|
39 |
+
while job_result['status'] not in ['succeeded', 'failed']:
|
40 |
+
time.sleep(0.25)
|
41 |
+
job_result = self.get_job(job['job'])
|
42 |
+
|
43 |
+
return job_result
|
44 |
+
|
45 |
+
def list_models(self):
|
46 |
+
response = self._get(f"{self.base}/sd/models")
|
47 |
+
return response.json()
|
48 |
+
|
49 |
+
def list_samplers(self):
|
50 |
+
response = self._get(f"{self.base}/sd/samplers")
|
51 |
+
return response.json()
|
52 |
+
|
53 |
+
def _post(self, url, params):
|
54 |
+
headers = {
|
55 |
+
**self.headers,
|
56 |
+
"Content-Type": "application/json"
|
57 |
+
}
|
58 |
+
response = requests.post(url, headers=headers, data=json.dumps(params))
|
59 |
+
|
60 |
+
if response.status_code != 200:
|
61 |
+
raise Exception(f"Bad Prodia Response: {response.status_code}")
|
62 |
+
|
63 |
+
return response
|
64 |
+
|
65 |
+
def _get(self, url):
|
66 |
+
response = requests.get(url, headers=self.headers)
|
67 |
+
|
68 |
+
if response.status_code != 200:
|
69 |
+
raise Exception(f"Bad Prodia Response: {response.status_code}")
|
70 |
+
|
71 |
+
return response
|
72 |
+
|
73 |
+
|
74 |
+
def image_to_base64(image):
|
75 |
+
# Convert the image to bytes
|
76 |
+
buffered = BytesIO()
|
77 |
+
image.save(buffered, format="PNG") # You can change format to PNG if needed
|
78 |
+
|
79 |
+
# Encode the bytes to base64
|
80 |
+
img_str = base64.b64encode(buffered.getvalue())
|
81 |
+
|
82 |
+
return img_str.decode('utf-8') # Convert bytes to string
|
83 |
+
|
84 |
+
|
85 |
+
def remove_id_and_ext(text):
|
86 |
+
text = re.sub(r'\[.*\]$', '', text)
|
87 |
+
extension = text[-12:].strip()
|
88 |
+
if extension == "safetensors":
|
89 |
+
text = text[:-13]
|
90 |
+
elif extension == "ckpt":
|
91 |
+
text = text[:-4]
|
92 |
+
return text
|
93 |
+
|
94 |
+
|
95 |
+
def get_data(text):
|
96 |
+
results = {}
|
97 |
+
patterns = {
|
98 |
+
'prompt': r'(.*)',
|
99 |
+
'negative_prompt': r'Negative prompt: (.*)',
|
100 |
+
'steps': r'Steps: (\d+),',
|
101 |
+
'seed': r'Seed: (\d+),',
|
102 |
+
'sampler': r'Sampler:\s*([^\s,]+(?:\s+[^\s,]+)*)',
|
103 |
+
'model': r'Model:\s*([^\s,]+)',
|
104 |
+
'cfg_scale': r'CFG scale:\s*([\d\.]+)',
|
105 |
+
'size': r'Size:\s*([0-9]+x[0-9]+)'
|
106 |
+
}
|
107 |
+
for key in ['prompt', 'negative_prompt', 'steps', 'seed', 'sampler', 'model', 'cfg_scale', 'size']:
|
108 |
+
match = re.search(patterns[key], text)
|
109 |
+
if match:
|
110 |
+
results[key] = match.group(1)
|
111 |
+
else:
|
112 |
+
results[key] = None
|
113 |
+
if results['size'] is not None:
|
114 |
+
w, h = results['size'].split("x")
|
115 |
+
results['w'] = w
|
116 |
+
results['h'] = h
|
117 |
+
else:
|
118 |
+
results['w'] = None
|
119 |
+
results['h'] = None
|
120 |
+
return results
|
121 |
+
|
122 |
+
|
123 |
+
def send_to_txt2img(image):
|
124 |
+
|
125 |
+
result = {tabs: gr.update(selected="t2i")}
|
126 |
+
|
127 |
+
try:
|
128 |
+
text = image.info['parameters']
|
129 |
+
data = get_data(text)
|
130 |
+
result[prompt] = gr.update(value=data['prompt'])
|
131 |
+
result[negative_prompt] = gr.update(value=data['negative_prompt']) if data['negative_prompt'] is not None else gr.update()
|
132 |
+
result[steps] = gr.update(value=int(data['steps'])) if data['steps'] is not None else gr.update()
|
133 |
+
result[seed] = gr.update(value=int(data['seed'])) if data['seed'] is not None else gr.update()
|
134 |
+
result[cfg_scale] = gr.update(value=float(data['cfg_scale'])) if data['cfg_scale'] is not None else gr.update()
|
135 |
+
result[width] = gr.update(value=int(data['w'])) if data['w'] is not None else gr.update()
|
136 |
+
result[height] = gr.update(value=int(data['h'])) if data['h'] is not None else gr.update()
|
137 |
+
result[sampler] = gr.update(value=data['sampler']) if data['sampler'] is not None else gr.update()
|
138 |
+
if model in model_names:
|
139 |
+
result[model] = gr.update(value=model_names[model])
|
140 |
+
else:
|
141 |
+
result[model] = gr.update()
|
142 |
+
return result
|
143 |
+
|
144 |
+
except Exception as e:
|
145 |
+
print(e)
|
146 |
+
|
147 |
+
return result
|
148 |
+
|
149 |
+
|
150 |
+
prodia_client = Prodia(api_key=os.getenv("PRODIA_API_KEY"))
|
151 |
+
model_list = prodia_client.list_models()
|
152 |
+
model_names = {}
|
153 |
+
|
154 |
+
for model_name in model_list:
|
155 |
+
name_without_ext = remove_id_and_ext(model_name)
|
156 |
+
model_names[name_without_ext] = model_name
|
157 |
+
|
158 |
+
|
159 |
+
def txt2img(prompt, negative_prompt, model, steps, sampler, cfg_scale, width, height, seed):
|
160 |
+
result = prodia_client.generate({
|
161 |
+
"prompt": prompt,
|
162 |
+
"negative_prompt": negative_prompt,
|
163 |
+
"model": model,
|
164 |
+
"steps": steps,
|
165 |
+
"sampler": sampler,
|
166 |
+
"cfg_scale": cfg_scale,
|
167 |
+
"width": width,
|
168 |
+
"height": height,
|
169 |
+
"seed": seed
|
170 |
+
})
|
171 |
+
|
172 |
+
job = prodia_client.wait(result)
|
173 |
+
|
174 |
+
return job["imageUrl"]
|
175 |
+
|
176 |
+
|
177 |
+
def img2img(input_image, denoising, prompt, negative_prompt, model, steps, sampler, cfg_scale, width, height, seed):
|
178 |
+
result = prodia_client.transform({
|
179 |
+
"imageData": image_to_base64(input_image),
|
180 |
+
"denoising_strength": denoising,
|
181 |
+
"prompt": prompt,
|
182 |
+
"negative_prompt": negative_prompt,
|
183 |
+
"model": model,
|
184 |
+
"steps": steps,
|
185 |
+
"sampler": sampler,
|
186 |
+
"cfg_scale": cfg_scale,
|
187 |
+
"width": width,
|
188 |
+
"height": height,
|
189 |
+
"seed": seed
|
190 |
+
})
|
191 |
+
|
192 |
+
job = prodia_client.wait(result)
|
193 |
+
|
194 |
+
return job["imageUrl"]
|
195 |
+
|
196 |
+
|
197 |
+
css = """
|
198 |
+
#generate {
|
199 |
+
height: 100%;
|
200 |
}
|
201 |
"""
|
202 |
|
|
|
|
|
|
|
|
|
|
|
203 |
with gr.Blocks(css=css) as demo:
|
204 |
+
with gr.Row():
|
205 |
+
with gr.Column(scale=6):
|
206 |
+
model = gr.Dropdown(interactive=True,value="absolutereality_v181.safetensors [3d9d4d2b]", show_label=True, label="Stable Diffusion Checkpoint", choices=prodia_client.list_models())
|
207 |
+
|
208 |
+
with gr.Column(scale=1):
|
209 |
+
gr.Markdown(elem_id="powered-by-prodia", value="AUTOMATIC1111 Stable Diffusion Web UI.<br>Powered by [Prodia](https://prodia.com).<br>For more features and faster generation times check out our [API Docs](https://docs.prodia.com/reference/getting-started-guide).")
|
210 |
+
|
211 |
+
with gr.Tabs() as tabs:
|
212 |
+
with gr.Tab("txt2img", id='t2i'):
|
213 |
+
with gr.Row():
|
214 |
+
with gr.Column(scale=6, min_width=600):
|
215 |
+
prompt = gr.Textbox("space warrior, beautiful, female, ultrarealistic, soft lighting, 8k", placeholder="Prompt", show_label=False, lines=3)
|
216 |
+
negative_prompt = gr.Textbox(placeholder="Negative Prompt", show_label=False, lines=3, value="3d, cartoon, anime, (deformed eyes, nose, ears, nose), bad anatomy, ugly")
|
217 |
+
with gr.Column():
|
218 |
+
text_button = gr.Button("Generate", variant='primary', elem_id="generate")
|
219 |
+
|
220 |
+
with gr.Row():
|
221 |
+
with gr.Column(scale=3):
|
222 |
+
with gr.Tab("Generation"):
|
223 |
+
with gr.Row():
|
224 |
+
with gr.Column(scale=1):
|
225 |
+
sampler = gr.Dropdown(value="DPM++ 2M Karras", show_label=True, label="Sampling Method", choices=prodia_client.list_samplers())
|
226 |
+
|
227 |
+
with gr.Column(scale=1):
|
228 |
+
steps = gr.Slider(label="Sampling Steps", minimum=1, maximum=25, value=20, step=1)
|
229 |
|
230 |
+
with gr.Row():
|
231 |
+
with gr.Column(scale=1):
|
232 |
+
width = gr.Slider(label="Width", maximum=1024, value=512, step=8)
|
233 |
+
height = gr.Slider(label="Height", maximum=1024, value=512, step=8)
|
234 |
+
|
235 |
+
with gr.Column(scale=1):
|
236 |
+
batch_size = gr.Slider(label="Batch Size", maximum=1, value=1)
|
237 |
+
batch_count = gr.Slider(label="Batch Count", maximum=1, value=1)
|
238 |
+
|
239 |
+
cfg_scale = gr.Slider(label="CFG Scale", minimum=1, maximum=20, value=7, step=1)
|
240 |
+
seed = gr.Number(label="Seed", value=-1)
|
241 |
+
|
242 |
+
with gr.Column(scale=2):
|
243 |
+
image_output = gr.Image(value="https://images.prodia.xyz/8ede1a7c-c0ee-4ded-987d-6ffed35fc477.png")
|
244 |
+
|
245 |
+
text_button.click(txt2img, inputs=[prompt, negative_prompt, model, steps, sampler, cfg_scale, width, height,
|
246 |
+
seed], outputs=image_output, concurrency_limit=64)
|
247 |
|
248 |
+
with gr.Tab("img2img", id='i2i'):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
249 |
with gr.Row():
|
250 |
+
with gr.Column(scale=6, min_width=600):
|
251 |
+
i2i_prompt = gr.Textbox("space warrior, beautiful, female, ultrarealistic, soft lighting, 8k", placeholder="Prompt", show_label=False, lines=3)
|
252 |
+
i2i_negative_prompt = gr.Textbox(placeholder="Negative Prompt", show_label=False, lines=3, value="3d, cartoon, anime, (deformed eyes, nose, ears, nose), bad anatomy, ugly")
|
253 |
+
with gr.Column():
|
254 |
+
i2i_text_button = gr.Button("Generate", variant='primary', elem_id="generate")
|
255 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
256 |
with gr.Row():
|
257 |
+
with gr.Column(scale=3):
|
258 |
+
with gr.Tab("Generation"):
|
259 |
+
i2i_image_input = gr.Image(type="pil")
|
260 |
+
|
261 |
+
with gr.Row():
|
262 |
+
with gr.Column(scale=1):
|
263 |
+
i2i_sampler = gr.Dropdown(value="Euler a", show_label=True, label="Sampling Method", choices=prodia_client.list_samplers())
|
264 |
+
|
265 |
+
with gr.Column(scale=1):
|
266 |
+
i2i_steps = gr.Slider(label="Sampling Steps", minimum=1, maximum=25, value=20, step=1)
|
267 |
+
|
268 |
+
with gr.Row():
|
269 |
+
with gr.Column(scale=1):
|
270 |
+
i2i_width = gr.Slider(label="Width", maximum=1024, value=512, step=8)
|
271 |
+
i2i_height = gr.Slider(label="Height", maximum=1024, value=512, step=8)
|
272 |
+
|
273 |
+
with gr.Column(scale=1):
|
274 |
+
i2i_batch_size = gr.Slider(label="Batch Size", maximum=1, value=1)
|
275 |
+
i2i_batch_count = gr.Slider(label="Batch Count", maximum=1, value=1)
|
276 |
+
|
277 |
+
i2i_cfg_scale = gr.Slider(label="CFG Scale", minimum=1, maximum=20, value=7, step=1)
|
278 |
+
i2i_denoising = gr.Slider(label="Denoising Strength", minimum=0, maximum=1, value=0.7, step=0.1)
|
279 |
+
i2i_seed = gr.Number(label="Seed", value=-1)
|
280 |
+
|
281 |
+
with gr.Column(scale=2):
|
282 |
+
i2i_image_output = gr.Image(value="https://images.prodia.xyz/8ede1a7c-c0ee-4ded-987d-6ffed35fc477.png")
|
283 |
+
|
284 |
+
i2i_text_button.click(img2img, inputs=[i2i_image_input, i2i_denoising, i2i_prompt, i2i_negative_prompt,
|
285 |
+
model, i2i_steps, i2i_sampler, i2i_cfg_scale, i2i_width, i2i_height,
|
286 |
+
i2i_seed], outputs=i2i_image_output, concurrency_limit=64)
|
287 |
|
288 |
+
with gr.Tab("PNG Info"):
|
289 |
+
def plaintext_to_html(text, classname=None):
|
290 |
+
content = "<br>\n".join(html.escape(x) for x in text.split('\n'))
|
291 |
+
|
292 |
+
return f"<p class='{classname}'>{content}</p>" if classname else f"<p>{content}</p>"
|
293 |
+
|
294 |
+
|
295 |
+
def get_exif_data(image):
|
296 |
+
items = image.info
|
297 |
+
|
298 |
+
info = ''
|
299 |
+
for key, text in items.items():
|
300 |
+
info += f"""
|
301 |
+
<div>
|
302 |
+
<p><b>{plaintext_to_html(str(key))}</b></p>
|
303 |
+
<p>{plaintext_to_html(str(text))}</p>
|
304 |
+
</div>
|
305 |
+
""".strip()+"\n"
|
306 |
+
|
307 |
+
if len(info) == 0:
|
308 |
+
message = "Nothing found in the image."
|
309 |
+
info = f"<div><p>{message}<p></div>"
|
310 |
+
|
311 |
+
return info
|
312 |
+
|
313 |
+
with gr.Row():
|
314 |
+
with gr.Column():
|
315 |
+
image_input = gr.Image(type="pil")
|
316 |
+
|
317 |
+
with gr.Column():
|
318 |
+
exif_output = gr.HTML(label="EXIF Data")
|
319 |
+
send_to_txt2img_btn = gr.Button("Send to txt2img")
|
320 |
+
|
321 |
+
image_input.upload(get_exif_data, inputs=[image_input], outputs=exif_output)
|
322 |
+
send_to_txt2img_btn.click(send_to_txt2img, inputs=[image_input], outputs=[tabs, prompt, negative_prompt,
|
323 |
+
steps, seed, model, sampler,
|
324 |
+
width, height, cfg_scale],
|
325 |
+
concurrency_limit=64)
|
326 |
+
|
327 |
+
demo.queue(max_size=80, api_open=False).launch(max_threads=256, show_api=False)
|