Spaces:
Runtime error
Runtime error
Update app.py
Browse files5 unmodified lines6789101112131415161 unmodified line1819202122232425262728293031323334353638 unmodified lines7576777879808182838485863 unmodified lines9091929394951 unmodified line9798991001011021031041051061079 unmodified lines11711811912012112212312412512612712812913013113213313413513613713813913 unmodified lines1531541551561571581592 unmodified lines1621631641651661671681693 unmodified lines1731741751761771781791801811821833 unmodified lines1871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672681 unmodified line2702712722732742752762772782792802812822832842852862872882892902912922932945 unmodified linesimport base64import osfrom io import BytesIOimport PILfrom PIL.ExifTags import TAGSimport htmlimport reclass Prodia:def __init__(self, api_key, base=None):1 unmodified lineself.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()38 unmodified lines# Convert the image to bytesbuffered = BytesIO()image.save(buffered, format="PNG") # You can change format to PNG if needed# Encode the bytes to base64img_str = base64.b64encode(buffered.getvalue())return img_str.decode('utf-8') # Convert bytes to stringdef remove_id_and_ext(text):text = re.sub(r'\[.*\]$', '', text)extension = text[-12:].strip()3 unmodified linestext = text[:-4]return textdef get_data(text):results = {}patterns = {1 unmodified line'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:9 unmodified linesresults['h'] = Nonereturn resultsdef 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 result13 unmodified linesreturn resultprodia_client = Prodia(api_key=os.getenv("PRODIA_API_KEY"))model_list = prodia_client.list_models()model_names = {}2 unmodified linesname_without_ext = remove_id_and_ext(model_name)model_names[name_without_ext] = model_namedef flip_text(prompt, negative_prompt, model, steps, sampler, cfg_scale, width, height, seed):result = prodia_client.generate({"prompt": prompt,"negative_prompt": negative_prompt,"model": model,3 unmodified lines"width": width,"height": height,"seed": seed})job = prodia_client.wait(result)return job["imageUrl"]css = """3 unmodified lines"""with gr.Blocks(css=css) as demo:with gr.Row():with gr.Column(scale=6):model = gr.Dropdown(interactive=True,value="absolutereality_v181.safetensors [3d9d4d2b]", show_label=True, label="Stable Diffusion Checkpoint", choices=prodia_client.list_models())with gr.Column(scale=1):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 gen times check out our [API Docs](https://docs.prodia.com/reference/getting-started-guide)")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("space warrior, beautiful, female, ultrarealistic, soft lighting, 8k", placeholder="Prompt", show_label=False, lines=3)negative_prompt = gr.Textbox(placeholder="Negative Prompt", show_label=False, lines=3, value="3d, cartoon, anime, (deformed eyes, nose, ears, nose), bad anatomy, ugly")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(value="Euler a", show_label=True, label="Sampling Method", choices=["Euler","Euler a","LMS","Heun","DPM2","DPM2 a","DPM++ 2S a","DPM++ 2M","DPM++ SDE","DPM fast","DPM adaptive","LMS Karras","DPM2 Karras","DPM2 a Karras","DPM++ 2S a Karras","DPM++ 2M Karras","DPM++ SDE Karras","DDIM","PLMS",])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://images.prodia.xyz/8ede1a7c-c0ee-4ded-987d-6ffed35fc477.png")text_button.click(flip_text, inputs=[prompt, negative_prompt, model, steps, sampler, cfg_scale, width, height, seed], outputs=image_output)with gr.Tab("PNG Info"):def plaintext_to_html(text, classname=None):content = "<br>\n".join(html.escape(x) for x in text.split('\n'))return f"<p class='{classname}'>{content}</p>" if classname else f"<p>{content}</p>"def get_exif_data(image):items = image.infoinfo = ''for key, text in items.items():info += f"""1 unmodified line<p><b>{plaintext_to_html(str(key))}</b></p><p>{plaintext_to_html(str(text))}</p></div>""".strip()+"\n"if len(info) == 0:message = "Nothing found in the image."info = f"<div><p>{message}<p></div>"return infowith gr.Row():with gr.Column():image_input = gr.Image(type="pil")with gr.Column():exif_output = gr.HTML(label="EXIF Data")send_to_txt2img_btn = gr.Button("Send to txt2img")image_input.upload(get_exif_data, inputs=[image_input], outputs=exif_output)send_to_txt2img_btn.click(send_to_txt2img, inputs=[image_input], outputs=[tabs, prompt, negative_prompt, steps, seed,model, sampler, width, height, cfg_scale])demo.queue(concurrency_count=32)demo.launch()5 unmodified lines67891011121314151617181920211 unmodified line2324252627282930313233343536373839404138 unmodified lines808182838485868788899091923 unmodified lines969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321 unmodified line1341351361371381391401411421431449 unmodified lines15415515615715815916016116216316416516616716816917017117217317417517617713 unmodified lines1911921931941951962 unmodified lines1992002012022032042052062072082092103 unmodified lines2142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592603 unmodified lines2642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443451 unmodified line3473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773785 unmodified linesimport base64import osfrom io import BytesIOimport mathimport PILfrom PIL import Imagefrom PIL.ExifTags import TAGSimport htmlimport refrom threading import Threadfrom dotenv import load_dotenvload_dotenv()class Prodia:def __init__(self, api_key, base=None):1 unmodified lineself.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()38 unmodified lines# Convert the image to bytesbuffered = BytesIO()image.save(buffered, format="PNG") # You can change format to PNG if needed# Encode the bytes to base64img_str = base64.b64encode(buffered.getvalue())return img_str.decode('utf-8') # Convert bytes to stringdef remove_id_and_ext(text):text = re.sub(r'\[.*\]$', '', text)extension = text[-12:].strip()3 unmodified linestext = text[:-4]return textdef create_grid(image_urls):# Download first image to get sizeresponse = requests.get(image_urls[0])img_data = response.contentimg = Image.open(BytesIO(img_data))w, h = img.size# Calculate rows and colsnum_images = len(image_urls)num_cols = min(num_images, 3)num_rows = math.ceil(num_images / num_cols)# Create new rgba imagegrid_w = num_cols * wgrid_h = num_rows * hgrid = Image.new('RGBA', (grid_w, grid_h), (0, 0, 0, 0))# Download images and paste into gridfor index, img_url in enumerate(image_urls):response = requests.get(img_url)img_data = response.contentimg = Image.open(BytesIO(img_data))row = index // num_colscol = index % num_colsgrid.paste(img, (col * w, row * h))# Save imagereturn griddef get_data(text):results = {}patterns = {1 unmodified line'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:9 unmodified linesresults['h'] = Nonereturn resultsdef 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 data['model'] in model_names:result[model] = gr.update(value=model_names[data['model']])else:result[model] = gr.update()return result13 unmodified linesreturn resultprodia_client = Prodia(api_key=os.getenv("PRODIA_API_KEY"))model_list = prodia_client.list_models()model_names = {}2 unmodified linesname_without_ext = remove_id_and_ext(model_name)model_names[name_without_ext] = model_namedef flip_text(prompt, negative_prompt, model, steps, sampler, cfg_scale, width, height, seed, batch_size, batch_count, gallery):data = {"prompt": prompt,"negative_prompt": negative_prompt,"model": model,3 unmodified lines"width": width,"height": height,"seed": seed}total_images = []count_threads = []def generate_one_grid():grid_images = []size_threads = []def generate_one_image():result = prodia_client.generate(data)job = prodia_client.wait(result)grid_images.append(job['imageUrl'])for y in range(batch_size):t = Thread(target=generate_one_image)size_threads.append(t)t.start()for t in size_threads:t.join()total_images.append(create_grid(grid_images))for x in range(batch_count):t = Thread(target=generate_one_grid)count_threads.append(t)t.start()for t in count_threads:t.join()new_images_list = [img['name'] for img in gallery]for image in total_images:new_images_list.insert(0, image)return {image_output: total_images, gallery_obj: new_images_list}css = """3 unmodified lines"""with gr.Blocks(css=css) as demo:with gr.Row():with gr.Column(scale=6):model = gr.Dropdown(interactive=True, value="absolutereality_v181.safetensors [3d9d4d2b]", show_label=True,label="Stable Diffusion Checkpoint", choices=prodia_client.list_models())with gr.Column(scale=1):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 gen times check out our [API Docs](https://docs.prodia.com/reference/getting-started-guide)")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("space warrior, beautiful, female, ultrarealistic, soft lighting, 8k",placeholder="Prompt", show_label=False, lines=3)negative_prompt = gr.Textbox(placeholder="Negative Prompt", show_label=False, lines=3,value="3d, cartoon, anime, (deformed eyes, nose, ears, nose), bad anatomy, ugly")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(value="Euler a", show_label=True, label="Sampling Method",choices=["Euler","Euler a","LMS","Heun","DPM2","DPM2 a","DPM++ 2S a","DPM++ 2M","DPM++ SDE","DPM fast","DPM adaptive","LMS Karras","DPM2 Karras","DPM2 a Karras","DPM++ 2S a Karras","DPM++ 2M Karras","DPM++ SDE Karras","DDIM","PLMS",])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", minimum=1, maximum=9, value=1, step=1)batch_count = gr.Slider(label="Batch Count", minimum=1, maximum=100, value=1, step=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.Gallery(value=["https://images.prodia.xyz/8ede1a7c-c0ee-4ded-987d-6ffed35fc477.png"], preview=True)with gr.Tab("PNG Info"):def plaintext_to_html(text, classname=None):content = "<br>\n".join(html.escape(x) for x in text.split('\n'))return f"<p class='{classname}'>{content}</p>" if classname else f"<p>{content}</p>"def get_exif_data(image):items = image.infoinfo = ''for key, text in items.items():info += f"""1 unmodified line<p><b>{plaintext_to_html(str(key))}</b></p><p>{plaintext_to_html(str(text))}</p></div>""".strip() + "\n"if len(info) == 0:message = "Nothing found in the image."info = f"<div><p>{message}<p></div>"return infowith gr.Row():with gr.Column():image_input = gr.Image(type="pil")with gr.Column():exif_output = gr.HTML(label="EXIF Data")send_to_txt2img_btn = gr.Button("Send to txt2img")with gr.Tab("Gallery"):gallery_obj = gr.Gallery(height=1000, columns=5)text_button.click(flip_text,inputs=[prompt, negative_prompt, model, steps, sampler, cfg_scale, width, height, seed, batch_size, batch_count,gallery_obj], outputs=[image_output, gallery_obj])image_input.upload(get_exif_data, inputs=[image_input], outputs=exif_output)send_to_txt2img_btn.click(send_to_txt2img, inputs=[image_input],outputs=[tabs, prompt, negative_prompt, steps, seed,model, sampler, width, height, cfg_scale])demo.queue(concurrency_count=32)demo.launch()
app.py+156-72