Spaces:
Runtime error
Runtime error
File size: 10,298 Bytes
9a46212 b8a8ac7 9a46212 b8a8ac7 9a46212 c015ba6 9a46212 491c2d3 9a46212 f627998 9a46212 20e4ac4 2127e48 20e4ac4 16dae2c 20e4ac4 9a46212 9586f99 f627998 c9430f9 9a46212 20e4ac4 f627998 c9430f9 20e4ac4 9a46212 20e4ac4 9a46212 3a4ba99 9a46212 20e4ac4 9a46212 3a4ba99 9a46212 ae5a60f 20e4ac4 9a46212 f9c5d2e 9a46212 c242249 9a46212 20e4ac4 9a46212 65952f3 9a46212 65952f3 20e4ac4 9a46212 7bdea22 7387a54 470f207 9a46212 369e5aa 7bdea22 aff6353 7bdea22 9a46212 0265de8 9a46212 bd3d125 9a46212 f627998 9a46212 bd3d125 9a46212 f627998 9a46212 2b7510a c731ab6 9a46212 73e7987 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 | 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
class RenderNet:
def __init__(self, api_key, base=None):
self.base = base or "https://app.rendernet.ai/api/"
self.headers = {
"rendernetapikey": api_key
}
def generate(self, params):
response = self._post(f"{self.base}/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(1)
job_result = self.get_job(job['job'])
print("Job Result:")
print(job_result)
return job_result
def list_models(self):
response =[
'dreamshaper',
'ghost_mix',
'proto_vision',
'meina_unreal',
'realistic_vision',
'animerge',
'oil_painting',
'absolute_reality',
'meinamix',
'rpg',
'western_animation',
'dynavision',
'Realvis_XL',
'abyss_orange_mix',
'anything_v5',
'dreamshaper_xl',
'epic_realism',
'comicbook_style',
'newdawnxl',
'nextphoto',
'nightvisionxl',
'juggernaut',
'cyber_realistic',
'real_cartoon',
'unstable_diffusers',
'cant_believe',
'majicmix_fantasy',
'analog_madness',
'blazing_drive',
'mysteriousxl',
'night_sky',
'never_ending',
'dark_sushi',
'meina_pastel',
'meina_alter',
'counterfeitxl_v10',
'plagion_v10',
'replicant_v3.0'
]
return response
def list_samplers(self):
response = [
'DPM++ SDE Karras',
'DPM++ 2M Karras'
'DPM++ 2S a Karras',
'Euler a',
'DPM++ 2M SDE Karras'
]
return response
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 RenderNet 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 RenderNet Response: {response.status_code}")
return response
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
rendernet_client = RenderNet(api_key=os.getenv("API_KEY"))
model_list = rendernet_client.list_models()
model_names = {}
for model_name in model_list:
name_without_ext = remove_id_and_ext(model_name)
print(name_without_ext)
model_names[name_without_ext] = model_name
print(model_names)
def txt2img(prompt, negative_prompt, model, steps, sampler, cfg_scale, width, height, seed):
result = rendernet_client.generate({
"prompt": prompt,
"negative_prompt": negative_prompt,
"model": model,
"steps": steps,
"sampler": sampler,
"cfg_scale": cfg_scale,
"width": width,
"height": height,
"seed": seed
})
print("Result Value:")
print("")
print(result)
print("Job Value:")
print("")
job = rendernet_client.wait(result)
return job["imageUrl"]
# Static Image URL
static_image_url = "https://baseavaar2.s3.amazonaws.com/banner.png"
static_image_link_url="https://rendernet.ai"
css = """
#generate {
height: 100%;
}
"""
with gr.Blocks(css=css) as demo:
# Add a Row for the Static Image
with gr.Row():
with gr.Column():
static_image_with_link = gr.HTML(f'<a href="{static_image_link_url}" target="_blank"><img src="{static_image_url}" /></a>')
with gr.Row():
with gr.Column(scale=6):
model = gr.Dropdown(interactive=True, value="dreamshaper", show_label=True, label="Stable Diffusion Checkpoint", choices=rendernet_client.list_models())
with gr.Column(scale=1):
gr.Markdown(elem_id="powered-by-rendernet", value="AUTOMATIC1111 Stable Diffusion Web UI.<br>Powered by [RenderNet](https://rendernet.ai).<br>For advanced features and faster generation times check out our API and Website(https://rendernet.ai/).")
with gr.Tabs() as tabs:
with gr.Tab("txt2img", id='t2i'):
with gr.Row():
with gr.Column(scale=6, min_width=600):
prompt = gr.Textbox("a master jedi cat in star wars with a lightsaber, wearing a jedi cloak hood in the kitchen (cat:1.3)", placeholder="Prompt", show_label=False, lines=3)
negative_prompt = gr.Textbox(placeholder="Negative Prompt", show_label=False, lines=3, value="(worst quality, low quality, normal quality:2)")
with gr.Column():
text_button = gr.Button("Generate", variant='primary', elem_id="generate")
with gr.Row():
with gr.Column(scale=3):
with gr.Tab("Generation"):
with gr.Row():
with gr.Column(scale=1):
sampler = gr.Dropdown(show_label=True, value="DPM++ SDE Karras", label="Sampling Method", choices=rendernet_client.list_samplers())
with gr.Column(scale=1):
steps = gr.Slider(label="Sampling Steps", minimum=1, maximum=30, value=25, step=1)
with gr.Row():
with gr.Column(scale=1):
width = gr.Slider(label="Width", maximum=1024, value=512, step=8)
height = gr.Slider(label="Height", maximum=1024, value=512, step=8)
with gr.Column(scale=1):
batch_size = gr.Slider(label="Batch Size", maximum=1, value=1)
batch_count = gr.Slider(label="Batch Count", maximum=1, value=1)
cfg_scale = gr.Slider(label="CFG Scale", minimum=1, maximum=20, value=7, step=1)
seed = gr.Number(label="Seed", value=-1)
with gr.Column(scale=2):
image_output = gr.Image(value="https://app.rendernet.ai/userfiles/1699956614571.5938.png")
text_button.click(txt2img, inputs=[prompt, negative_prompt, model, steps, sampler, cfg_scale, width, height, seed], outputs=image_output)
demo.queue(max_size=80, api_open=False).launch(max_threads=256)
|