Burman-AI/Printing-Press
1
1import gradio as gr2from random import randint3from all_models import models4 5from externalmod import gr_Interface_load6 7import asyncio8import os9from threading import RLock10lock = RLock()11HF_TOKEN = os.environ.get("HF_TOKEN") if os.environ.get("HF_TOKEN") else None # If private or gated models aren't used, ENV setting is unnecessary.12 13 14def load_fn(models):15 global models_load16 models_load = {}17 18 for model in models:19 if model not in models_load.keys():20 try:21 m = gr_Interface_load(f'models/{model}', hf_token=HF_TOKEN)22 except Exception as error:23 print(error)24 m = gr.Interface(lambda: None, ['text'], ['image'])25 models_load.update({model: m})26 27load_fn(models)28 29 30num_models = 131default_models = models[:num_models]32inference_timeout = 60033 34MAX_SEED=399999999935 36 37 38def extend_choices(choices):39 return choices + (num_models - len(choices)) * ['NA']40 41 42def update_imgbox(choices):43 choices_plus = extend_choices(choices)44 return [gr.Image(None, label = m, visible = (m != 'NA')) for m in choices_plus]45 46def gen_fn(model_str, prompt):47 if model_str == 'NA':48 return None49 noise = str('') #str(randint(0, 99999999999))50 return models_load[model_str](f'{prompt} {noise}')51 52 53 54 55 56 57 58 59 60async def infer(model_str, prompt, seed=1, timeout=inference_timeout):61 from pathlib import Path62 kwargs = {}63 noise = ""64 kwargs["seed"] = seed65 task = asyncio.create_task(asyncio.to_thread(models_load[model_str].fn,66 prompt=f'{prompt} {noise}', **kwargs, token=HF_TOKEN))67 await asyncio.sleep(0)68 try:69 result = await asyncio.wait_for(task, timeout=timeout)70 except (Exception, asyncio.TimeoutError) as e:71 print(e)72 print(f"Task timed out: {model_str}")73 if not task.done(): task.cancel()74 result = None75 if task.done() and result is not None:76 with lock:77 png_path = "image.png"78 result.save(png_path)79 image = str(Path(png_path).resolve())80 return image81 return None82 83def gen_fnseed(model_str, prompt, seed=1):84 if model_str == 'NA':85 return None86 try:87 loop = asyncio.new_event_loop()88 result = loop.run_until_complete(infer(model_str, prompt, seed, inference_timeout))89 except (Exception, asyncio.CancelledError) as e:90 print(e)91 print(f"Task aborted: {model_str}")92 result = None93 with lock:94 image = "https://huggingface.co/spaces/Yntec/ToyWorld/resolve/main/error.png"95 result = image96 finally:97 loop.close()98 return result99 100def gen_fnsix(model_str, prompt):101 if model_str == 'NA':102 return None103 noisesix = str(randint(1941, 2023)) #str(randint(0, 99999999999))104 return models_load[model_str](f'{prompt} {noisesix}')105with gr.Blocks() as demo:106 gr.HTML(107 """108 <div>109 <p> <center><img src="https://huggingface.co/Yntec/OpenGenDiffusers/resolve/main/pp.png" style="height:128px; width:482px; margin-top: -22px; margin-bottom: -44px;" span title="Free ai art image generator Printing Press"></center>110 </p>111 """112)113 gr.HTML(114 """115 <div>116 <p> <center>For negative prompts, Width and Height, and other features visit John6666's <a href="https://huggingface.co/spaces/John6666/PrintingPress4">Printing Press 4</a>!</center>117 </p></div>118 """119) 120 with gr.Tab('One Image'):121 model_choice = gr.Dropdown(models, label = f'Choose a model from the {len(models)} available! Try clearing the box and typing on it to filter them!', value = models[0], filterable = True)122 txt_input = gr.Textbox(label = 'Your prompt:')123 124 max_imagesone = 1125 num_imagesone = gr.Slider(1, max_imagesone, value = max_imagesone, step = 1, label = 'Nobody gets to see this label so I can put here whatever I want!', visible = False)126 127 gen_button = gr.Button('Generate')128 #stop_button = gr.Button('Stop', variant = 'secondary', interactive = False)129 gen_button.click(lambda s: gr.update(interactive = True), None)130 131 with gr.Row():132 output = [gr.Image(label = '') for _ in range(max_imagesone)]133 134 for i, o in enumerate(output):135 img_in = gr.Number(i, visible = False)136 num_imagesone.change(lambda i, n: gr.update(visible = (i < n)), [img_in, num_imagesone], o, show_progress = False)137 gen_event = gen_button.click(lambda i, n, m, t: gen_fn(m, t) if (i < n) else None, [img_in, num_imagesone, model_choice, txt_input], o, concurrency_limit=None, queue=False)138 #stop_button.click(lambda s: gr.update(interactive = False), None, stop_button, cancels = [gen_event])139 with gr.Row():140 gr.HTML(141 """142 <div class="footer">143 <p> Based on the <a href="https://huggingface.co/spaces/derwahnsinn/TestGen">TestGen</a> Space by derwahnsinn, the <a href="https://huggingface.co/spaces/RdnUser77/SpacIO_v1">SpacIO</a> Space by RdnUser77, Omnibus's Maximum Multiplier, and <a href="https://huggingface.co/spaces/Yntec/ToyWorld">Toy World</a>!144 </p>145 """146)147 with gr.Tab('Seed it!'):148 model_choiceseed = gr.Dropdown(models, label = f'Choose a model from the {len(models)} available! Try clearing the box and typing on it to filter them!', value = models[0], filterable = True)149 txt_inputseed = gr.Textbox(label = 'Your prompt:')150 seed = gr.Slider(label="Use a seed to replicate the same image later", info="Max 3999999999", minimum=0, maximum=MAX_SEED, step=1, value=1)151 152 max_imagesseed = 1153 num_imagesseed = gr.Slider(1, max_imagesone, value = max_imagesone, step = 1, label = 'One, because more would make it produce identical images with the seed', visible = False)154 155 gen_buttonseed = gr.Button('Generate an image using the seed')156 #stop_button = gr.Button('Stop', variant = 'secondary', interactive = False)157 gen_button.click(lambda s: gr.update(interactive = True), None)158 159 with gr.Row():160 outputseed = [gr.Image(label = '') for _ in range(max_imagesseed)]161 162 for i, o in enumerate(outputseed):163 img_is = gr.Number(i, visible = False)164 num_imagesseed.change(lambda i, n: gr.update(visible = (i < n)), [img_is, num_imagesseed], o, show_progress = False)165 #gen_eventseed = gen_buttonseed.click(lambda i, n, m, t, n1: gen_fnseed(m, t, n1) if (i < n) else None, [img_is, num_imagesseed, model_choiceseed, txt_inputseed, useseed], o, concurrency_limit=None, queue=False)166 167 gen_eventseed = gr.on(triggers=[gen_buttonseed.click, txt_inputseed.submit],168 fn=lambda i, n, m, t, n1: gen_fnseed(m, t, n1) if (i < n) else None,169 inputs=[img_is, num_imagesseed, model_choiceseed, txt_inputseed, seed], outputs=[o],170 concurrency_limit=None, queue=False) # Be sure to delete ", queue=False" when activating the stop button171 172 #stop_button.click(lambda s: gr.update(interactive = False), None, stop_button, cancels = [gen_event])173 with gr.Row():174 gr.HTML(175 """176 <div class="footer">177 <p> Based on the <a href="https://huggingface.co/spaces/derwahnsinn/TestGen">TestGen</a> Space by derwahnsinn, the <a href="https://huggingface.co/spaces/RdnUser77/SpacIO_v1">SpacIO</a> Space by RdnUser77, Omnibus's Maximum Multiplier, and <a href="https://huggingface.co/spaces/Yntec/ToyWorld">Toy World</a>!178 </p>179 """180)181 with gr.Tab('Up To Six'):182 model_choice2 = gr.Dropdown(models, label = f'Choose a model from the {len(models)} available! Try clearing the box and typing on it to filter them!', value = models[0], filterable = True)183 txt_input2 = gr.Textbox(label = 'Your prompt:')184 185 max_images = 6186 num_images = gr.Slider(1, max_images, value = max_images, step = 1, label = 'Number of images (if you want less than 6 decrease them slowly until they match the boxes below)')187 188 gen_button2 = gr.Button('Generate up to 6 images in up to 3 minutes total')189 #stop_button2 = gr.Button('Stop', variant = 'secondary', interactive = False)190 gen_button2.click(lambda s: gr.update(interactive = True), None)191 gr.HTML(192 """193 <div style="text-align: center; max-width: 1200px; margin: 0 auto;">194 <div>195 <body>196 <div class="center"><p style="margin-bottom: 10px; color: #000000;">Scroll down to see more images (they generate in a random order).</p>197 </div>198 </body>199 </div>200 </div>201 """202 )203 with gr.Column():204 output2 = [gr.Image(label = '') for _ in range(max_images)]205 206 for i, o in enumerate(output2):207 img_i = gr.Number(i, visible = False)208 num_images.change(lambda i, n: gr.update(visible = (i < n)), [img_i, num_images], o, show_progress = False)209 gen_event2 = gen_button2.click(lambda i, n, m, t: gen_fnsix(m, t) if (i < n) else None, [img_i, num_images, model_choice2, txt_input2], o, concurrency_limit=None, queue=False)210 #stop_button2.click(lambda s: gr.update(interactive = False), None, stop_button2, cancels = [gen_event2])211 with gr.Row():212 gr.HTML(213 """214 <div class="footer">215 <p> Based on the <a href="https://huggingface.co/spaces/derwahnsinn/TestGen">TestGen</a> Space by derwahnsinn, the <a href="https://huggingface.co/spaces/RdnUser77/SpacIO_v1">SpacIO</a> Space by RdnUser77, Omnibus's Maximum Multiplier and <a href="https://huggingface.co/spaces/Yntec/ToyWorld">Toy World</a>!216 </p>217 """218)219 220demo.queue(default_concurrency_limit=200, max_size=200)221demo.launch(show_api=False, max_threads=400)