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