Spaces:
Build error
Build error
AI-Journey2
commited on
Commit
•
ab70f27
1
Parent(s):
d702758
Update app.py
Browse files
app.py
CHANGED
@@ -1,327 +1,28 @@
|
|
1 |
-
import gradio as gr
|
2 |
import requests
|
3 |
-
import
|
4 |
-
import
|
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)
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
|
6 |
+
url = "https://stablediffusionapi.com/api/v3/text2img"
|
7 |
+
title = """<h2><center>Text to Image Generation with Stable Diffusion API</center></h2>"""
|
8 |
+
description = """#### Get the API key by signing up here [Stable Diffusion API](https://stablediffusionapi.com)."""
|
9 |
+
|
10 |
+
def get_image(key, prompt, inference_steps, filter):
|
11 |
+
payload = {
|
12 |
+
"key": key,
|
13 |
+
"prompt": prompt,
|
14 |
+
"negative_prompt": "((out of frame)), ((extra fingers)), mutated hands, ((poorly drawn hands)), ((poorly drawn face)), (((mutation))), (((deformed))), (((tiling))), ((naked)), ((tile)), ((fleshpile)), ((ugly)), (((abstract))), blurry, ((bad anatomy)), ((bad proportions)), ((extra limbs)), cloned face, (((skinny))), glitchy, ((extra breasts)), ((double torso)), ((extra arms)), ((extra hands)), ((mangled fingers)), ((missing breasts)), (missing lips), ((ugly face)), ((fat)), ((extra legs)), anime",
|
15 |
+
"width": "512",
|
16 |
+
"height": "512",
|
17 |
+
"samples": "1",
|
18 |
+
"num_inference_steps": inference_steps,"safety_checker": filter,"enhance_prompt": "yes","guidance_scale": 7.5}
|
19 |
+
headers = {}
|
20 |
+
response = requests.request("POST", url, headers=headers, data=payload)
|
21 |
+
url1 = str(json.loads(response.text)['output'][0])
|
22 |
+
r = requests.get(url1)
|
23 |
+
i = Image.open(BytesIO(r.content))
|
24 |
+
return i
|
25 |
+
|
26 |
+
demo = gr.Interface(fn=get_image,
|
27 |
+
inputs = [gr.Textbox(label="Enter API key"), gr.Textbox(label="Enter the Prompt"), gr.Number(label="Enter number of steps"),gr.Checkbox(label="Safety filter")],
|
28 |
+
outputs = gr.Image(type='pil'), title = title, description = description).launch(debug='True')
|