import gradio as gr from all_models import models from externalmod import gr_Interface_load, save_image, randomize_seed import asyncio import os from threading import RLock lock = RLock() HF_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. def load_fn(models): global models_load models_load = {} for model in models: if model not in models_load.keys(): try: m = gr_Interface_load(f'models/{model}', hf_token=HF_TOKEN) except Exception as error: print(error) m = gr.Interface(lambda: None, ['text'], ['image']) models_load.update({model: m}) load_fn(models) num_models = 6 timeout = 600 default_models = models[:num_models] MAX_SEED = 3999999999 def extend_choices(choices): return choices[:num_models] + (num_models - len(choices[:num_models])) * ['NA'] def update_imgbox(choices): choices_plus = extend_choices(choices[:num_models]) return [gr.Image(None, label=m, visible=(m!='NA')) for m in choices_plus] def random_choices(): import random random.seed() return random.choices(models, k=561) # https://huggingface.co/docs/api-inference/detailed_parameters # https://huggingface.co/docs/huggingface_hub/package_reference/inference_client async def infer(model_str, prompt, nprompt="", height=0, width=0, cfg=0, seed=-1, timeout=inference_timeout): kwargs = {} if height > 0: kwargs["height"] = height if width > 0: kwargs["width"] = width if cfg > 0: cfg = kwargs["guidance_scale"] = cfg if seed == -1: kwargs["seed"] = randomize_seed() else: kwargs["seed"] = seed task = asyncio.create_task(asyncio.to_thread(models_load[model_str].fn, prompt=prompt, negative_prompt=nprompt, **kwargs, token=HF_TOKEN)) await asyncio.sleep(0) try: result = await asyncio.wait_for(task, timeout=timeout) except asyncio.TimeoutError as e: print(e) print(f"Task timed out: {model_str}") if not task.done(): task.cancel() result = None raise Exception(f"Task timed out: {model_str}") from e except Exception as e: print(e) if not task.done(): task.cancel() result = None raise Exception() from e if task.done() and result is not None and not isinstance(result, tuple): with lock: png_path = "image.png" image = save_image(result, png_path, model_str, prompt, nprompt, height, width, steps, cfg, seed) return image return None def gen_fn(model_str, prompt, nprompt="", height=0, width=0, steps=0, cfg=0, seed=-1): try: loop = asyncio.new_event_loop() result = loop.run_until_complete(infer(model_str, prompt, nprompt, height, width, steps, cfg, seed, inference_timeout)) except (Exception, asyncio.CancelledError) as e: print(e) print(f"Task aborted: {model_str}") result = None raise gr.Error(f"Task aborted: {model_str}, Error: {e}") finally: loop.close() return result def add_gallery(image, model_str, gallery): if gallery is None: gallery = [] with lock: if image is not None: gallery.insert(0, (image, model_str)) return gallery CSS=""" .gradio-container { max-width: 1200px; margin: 0 auto; !important; } .output { width=112px; height=112px; max_width=112px; max_height=112px; !important; } .gallery { min_width=512px; min_height=512px; max_height=1024px; !important; } .guide { text-align: center; !important; } """ with gr.Blocks(theme='Nymbo/Nymbo_Theme', fill_width=True, css=CSS) as demo: gr.HTML( """