ehristoforu's picture
Upload 3 files
7fb7561
raw
history blame
9.51 kB
import numpy as np
import gradio as gr
import requests
import time
import json
import base64
import os
from io import BytesIO
import PIL
from PIL.ExifTags import TAGS
import html
import re
batch_count = 1
batch_size = 1
i2i_batch_count = 1
i2i_batch_size = 1
class Prodia:
def __init__(self, api_key, base=None):
self.base = base or "https://api.prodia.com/v1"
self.headers = {
"X-Prodia-Key": api_key
}
def generate(self, params):
response = self._post(f"{self.base}/sd/generate", params)
return response.json()
def transform(self, params):
response = self._post(f"{self.base}/sd/transform", params)
return response.json()
def controlnet(self, params):
response = self._post(f"{self.base}/sd/controlnet", params)
return response.json()
def get_job(self, job_id):
response = self._get(f"{self.base}/job/{job_id}")
return response.json()
def wait(self, job):
job_result = job
while job_result['status'] not in ['succeeded', 'failed']:
time.sleep(0.25)
job_result = self.get_job(job['job'])
return job_result
def list_models(self):
response = self._get(f"{self.base}/sd/models")
return response.json()
def list_samplers(self):
response = self._get(f"{self.base}/sd/samplers")
return response.json()
def _post(self, url, params):
headers = {
**self.headers,
"Content-Type": "application/json"
}
response = requests.post(url, headers=headers, data=json.dumps(params))
if response.status_code != 200:
raise Exception(f"Bad Prodia Response: {response.status_code}")
return response
def _get(self, url):
response = requests.get(url, headers=self.headers)
if response.status_code != 200:
raise Exception(f"Bad Prodia Response: {response.status_code}")
return response
def image_to_base64(image):
# Convert the image to bytes
buffered = BytesIO()
image.save(buffered, format="PNG") # You can change format to PNG if needed
# Encode the bytes to base64
img_str = base64.b64encode(buffered.getvalue())
return img_str.decode('utf-8') # Convert bytes to string
def remove_id_and_ext(text):
text = re.sub(r'\[.*\]$', '', text)
extension = text[-12:].strip()
if extension == "safetensors":
text = text[:-13]
elif extension == "ckpt":
text = text[:-4]
return text
def get_data(text):
results = {}
patterns = {
'prompt': r'(.*)',
'negative_prompt': r'Negative prompt: (.*)',
'steps': r'Steps: (\d+),',
'seed': r'Seed: (\d+),',
'sampler': r'Sampler:\s*([^\s,]+(?:\s+[^\s,]+)*)',
'model': r'Model:\s*([^\s,]+)',
'cfg_scale': r'CFG scale:\s*([\d\.]+)',
'size': r'Size:\s*([0-9]+x[0-9]+)'
}
for key in ['prompt', 'negative_prompt', 'steps', 'seed', 'sampler', 'model', 'cfg_scale', 'size']:
match = re.search(patterns[key], text)
if match:
results[key] = match.group(1)
else:
results[key] = None
if results['size'] is not None:
w, h = results['size'].split("x")
results['w'] = w
results['h'] = h
else:
results['w'] = None
results['h'] = None
return results
def send_to_txt2img(image):
result = {tabs: gr.Tabs.update(selected="t2i")}
try:
text = image.info['parameters']
data = get_data(text)
result[prompt] = gr.update(value=data['prompt'])
result[negative_prompt] = gr.update(value=data['negative_prompt']) if data['negative_prompt'] is not None else gr.update()
result[steps] = gr.update(value=int(data['steps'])) if data['steps'] is not None else gr.update()
result[seed] = gr.update(value=int(data['seed'])) if data['seed'] is not None else gr.update()
result[cfg_scale] = gr.update(value=float(data['cfg_scale'])) if data['cfg_scale'] is not None else gr.update()
result[width] = gr.update(value=int(data['w'])) if data['w'] is not None else gr.update()
result[height] = gr.update(value=int(data['h'])) if data['h'] is not None else gr.update()
result[sampler] = gr.update(value=data['sampler']) if data['sampler'] is not None else gr.update()
if model in model_names:
result[model] = gr.update(value=model_names[model])
else:
result[model] = gr.update()
return result
except Exception as e:
print(e)
result[prompt] = gr.update()
result[negative_prompt] = gr.update()
result[steps] = gr.update()
result[seed] = gr.update()
result[cfg_scale] = gr.update()
result[width] = gr.update()
result[height] = gr.update()
result[sampler] = gr.update()
result[model] = gr.update()
return result
prodia_client = Prodia(api_key=os.getenv("super_api_key"))
model_list = prodia_client.list_models()
model_names = {}
for model_name in model_list:
name_without_ext = remove_id_and_ext(model_name)
model_names[name_without_ext] = model_name
def txt2img(prompt, negative_prompt, model, width, height):
result = prodia_client.generate({
"prompt": prompt,
"negative_prompt": negative_prompt,
"model": model,
"steps": 30,
"sampler": "DPM++ SDE",
"cfg_scale": 7,
"width": width,
"height": height,
"seed": -1
})
job = prodia_client.wait(result)
return job["imageUrl"]
def img2img(input_image, prompt, negative_prompt, model, width, height):
result = prodia_client.transform({
"imageData": image_to_base64(input_image),
"denoising_strength": 0.7,
"prompt": prompt,
"negative_prompt": negative_prompt,
"model": i2i_model,
"steps": 30,
"sampler": "DPM++ SDE",
"cfg_scale": 7,
"width": width,
"height": height,
"seed": -1
})
job = prodia_client.wait(result)
return job["imageUrl"]
css = """
#generate {
height: 100%;
}
"""
with gr.Blocks(css=css, theme="Base") as demo:
gr.HTML(value="<h1><center>🥏 DreamDrop</center></h1>")
with gr.Tabs() as tabs:
with gr.Tab("Text to Image", id='t2i'):
with gr.Row():
with gr.Column(scale=6, min_width=600):
prompt = gr.Textbox(label="Prompt", placeholder="a cute cat, 8k", lines=2)
negative_prompt = gr.Textbox(label="Negative Prompt", value="text, blurry, fuzziness", lines=1)
with gr.Column():
text_button = gr.Button("Generate", variant='primary', elem_id="generate")
with gr.Row():
with gr.Column(scale=2):
image_output = gr.Image(label="Result Image")
with gr.Row():
with gr.Accordion("⚙️ Settings", open=False):
with gr.Column(scale=1):
model = gr.Dropdown(interactive=True, value="absolutereality_v181.safetensors [3d9d4d2b]",
show_label=True, label="Model",
choices=prodia_client.list_models())
width = gr.Slider(label="↔️ Width", maximum=1024, value=768, step=8)
height = gr.Slider(label="↕️ Height", maximum=1024, value=768, step=8)
text_button.click(txt2img, inputs=[prompt, negative_prompt, model, width, height], outputs=image_output)
with gr.Tab("Image to Image", id='i2i'):
with gr.Row():
with gr.Column(scale=6, min_width=600):
i2i_prompt = gr.Textbox(label="Prompt", placeholder="a cute cat, 8k", lines=3)
i2i_negative_prompt = gr.Textbox(label="Negative Prompt", lines=2, value="text, blurry, fuzziness")
with gr.Column():
i2i_text_button = gr.Button("Generate", variant='primary', elem_id="generate")
with gr.Row():
with gr.Column(scale=3):
i2i_image_input = gr.Image(label="Input Image", type="pil")
with gr.Column(scale=2):
i2i_image_output = gr.Image(label="Result Image")
with gr.Row():
with gr.Accordion("⚙️ Settings", open=False):
with gr.Column(scale=1):
i2i_model = gr.Dropdown(interactive=True,
value="absolutereality_v181.safetensors [3d9d4d2b]",
show_label=True, label="Model",
choices=prodia_client.list_models())
with gr.Column(scale=1):
i2i_width = gr.Slider(label="↔️ Width", maximum=1024, value=768, step=8)
i2i_height = gr.Slider(label="↕️ Height", maximum=1024, value=768, step=8)
i2i_text_button.click(img2img, inputs=[i2i_image_input, i2i_prompt, i2i_negative_prompt, model, i2i_width, i2i_height], outputs=i2i_image_output)
demo.queue(concurrency_count=64, max_size=30, api_open=False).launch(max_threads=256, show_api=False)