import numpy as np
import gradio as gr
import requests
import time
import json
import base64
import os
from PIL import Image
from io import BytesIO
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}/sdxl/generate", 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}/sdxl/models")
return response.json()
def list_samplers(self):
response = self._get(f"{self.base}/sdxl/samplers")
return response.json()
def generate_v2(self, config):
response = self._post("https://inference.prodia.com/v2/job", {"type": "v2.job.sdxl.txt2img", "config": config}, v2=True)
return Image.open(BytesIO(response.content)).convert("RGBA")
def _post(self, url, params, v2=False):
headers = {
**self.headers,
"Content-Type": "application/json"
}
if v2:
headers['Authorization'] = f"Bearer {os.getenv('API_KEY')}"
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_path):
# Open the image with PIL
with Image.open(image_path) as 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
prodia_client = Prodia(api_key=os.getenv("PRODIA_API_KEY"))
def flip_text(prompt, negative_prompt, model, steps, sampler, cfg_scale, width, height, seed):
config_without_model_and_sampler = {
"prompt": prompt,
"negative_prompt": negative_prompt,
"steps": steps,
"cfg_scale": cfg_scale,
"width": width,
"height": height,
"seed": seed
}
if model == "sd_xl_base_1.0.safetensors [be9edd61]":
return prodia_client.generate_v2(config_without_model_and_sampler)
result = prodia_client.generate({
**config_without_model_and_sampler,
"model": model,
"sampler": sampler
})
job = prodia_client.wait(result)
return job["imageUrl"]
css = """
#generate {
height: 100%;
}
"""
with gr.Blocks(css=css, theme=gr.themes.Default(spacing_size="sm", radius_size="lg")) as demo:
with gr.Row():
with gr.Column(scale=3, variant='panel'):
model = gr.Dropdown(label="Stable Diffusion Checkpoint", value="sd_xl_base_1.0.safetensors [be9edd61]", choices=prodia_client.list_models())
with gr.Column(scale=1, variant='panel'):
gr.Markdown(elem_id="powered-by-prodia", value="AUTOMATIC1111 Stable Diffusion Web UI for SDXL V1.0.
Powered by [Prodia](https://prodia.com).")
with gr.Row():
with gr.Column(scale=3, variant='panel'):
prompt = gr.Textbox(value="space warrior, beautiful, female, ultrarealistic, soft lighting, 8k", placeholder="Prompt", show_label=False, lines=3, max_lines=5)
negative_prompt = gr.Textbox(value="3d, cartoon, anime, (deformed eyes, nose, ears, nose), bad anatomy, ugly", placeholder="Negative Prompt", show_label=False, lines=3, max_lines=5)
with gr.Column(scale=1, variant='panel'):
text_button = gr.Button("Generate", variant='primary', elem_id="generate")
with gr.Row(equal_height=False):
with gr.Column(scale=3, variant='panel'):
with gr.Row():
sampler = gr.Dropdown(label="Sampling Method", value="DPM++ 2M Karras", choices=prodia_client.list_samplers())
steps = gr.Slider(label="Sampling Steps", minimum=1, maximum=100, value=20, step=1)
with gr.Column():
width = gr.Slider(label="Width", minimum=512, maximum=1536, value=1024, step=8)
height = gr.Slider(label="Height", minimum=512, maximum=1536, value=1024, step=8)
gr.HTML("