Spaces:
Runtime error
Runtime error
Upload 2 files
Browse filesFiles changed (2)
- app.py+75-62
- externalmod.py+105-24
123456789101112131415161718194 unmodified lines24252627282930311 unmodified line3334353637383940414243444546474849505152535455565758596061626364656667686970717273747576776 unmodified lines848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351362 unmodified lines139140141142143144145146147148149150151152153154155156157158import gradio as grfrom random import randintfrom all_models import modelsfrom externalmod import gr_Interface_loadimport asynciofrom threading import RLocklock = RLock()def load_fn(models):global models_loadmodels_load = {}for model in models:if model not in models_load.keys():try:m = gr_Interface_load(f'models/{model}')except Exception as error:print(error)m = gr.Interface(lambda: None, ['text'], ['image'])4 unmodified linesnum_models = 6default_models = models[:num_models]timeout = 300def extend_choices(choices):return choices[:num_models] + (num_models - len(choices[:num_models])) * ['NA']1 unmodified linedef 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 update_imgbox_gallery(choices):choices_plus = extend_choices(choices[:num_models])return [gr.Gallery(None, label = m, visible = (m != 'NA')) for m in choices_plus]async def infer(model_str, prompt, timeout):from PIL import Imagenoise = ""rand = randint(1, 500)for i in range(rand):noise += " "task = asyncio.create_task(asyncio.to_thread(models_load[model_str], f'{prompt} {noise}'))await asyncio.sleep(0)try:result = await asyncio.wait_for(task, timeout=timeout)except (Exception, asyncio.TimeoutError) as e:print(e)print(f"Task timed out: {model_str}")if not task.done(): task.cancel()result = Noneif task.done() and result is not None:with lock:image = Image.open(result).convert('RGBA')return imagereturn Nonedef gen_fn(model_str, prompt):if model_str == 'NA':return Nonetry:loop = asyncio.new_event_loop()result = loop.run_until_complete(infer(model_str, prompt, timeout))except (Exception, asyncio.CancelledError) as e:print(e)print(f"Task aborted: {model_str}")result = Nonefinally:loop.close()return result6 unmodified linesreturn gallerydef gen_fn_gallery(model_str, prompt, gallery):if gallery is None: gallery = []if model_str == 'NA':yield gallerytry:loop = asyncio.new_event_loop()result = loop.run_until_complete(infer(model_str, prompt, timeout))with lock:if result: gallery.insert(0, result)except (Exception, asyncio.CancelledError) as e:print(e)print(f"Task aborted: {model_str}")finally:loop.close()yield galleryCSS="""#container { max-width: 1200px; margin: 0 auto; !important; }.output { width=112px; height=112px; !important; }.gallery { width=100%; min_height=768px; !important; }.guide { text-align: center; !important; }"""with gr.Blocks(theme='Nymbo/Nymbo_Theme', fill_width=True, css=CSS) as demo:gr.HTML("""<div><p> <center>For simultaneous generations without hidden queue check out <a href="https://huggingface.co/spaces/Yntec/ToyWorld">Toy World</a>! For more options like single model x6 check out <a href="https://huggingface.co/spaces/John6666/Diffusion80XX4sg">Diffusion80XX4sg</a> by John6666!</center></p></div>""")with gr.Tab('Huggingface Diffusion'):with gr.Column(scale=2):txt_input = gr.Textbox(label='Your prompt:', lines=4)with gr.Row():gen_button = gr.Button(f'Generate up to {int(num_models)} images from 1 to {int(num_models)*3} minutes total', scale=2)stop_button = gr.Button('Stop', variant='secondary', interactive=False, scale=1)gen_button.click(lambda: gr.update(interactive = True), None, stop_button)gr.Markdown("Scroll down to see more images and select models.", elem_classes="guide")with gr.Column(scale=1):with gr.Group():with gr.Row():output = [gr.Image(label=m, show_download_button=True, elem_classes="output", interactive=False, min_width=80, show_share_button=False, visible=True) for m in default_models]#output = [gr.Image(label=m, show_download_button=True, elem_classes="output", interactive=False, show_share_button=True) for m in default_models]#output = [gr.Gallery(label=m, show_download_button=True, elem_classes="output", interactive=False, show_share_button=True, container=True, format="png", object_fit="cover") for m in default_models]current_models = [gr.Textbox(m, visible=False) for m in default_models]with gr.Column(scale=2):2 unmodified linespreview=True, object_fit="cover", columns=2, rows=2)for m, o in zip(current_models, output):#gen_event = gen_button.click(gen_fn, [m, txt_input], o)#gen_event = gen_button.click(gen_fn_gallery, [m, txt_input, o], o)gen_event = gr.on(triggers=[gen_button.click, txt_input.submit], fn=gen_fn, inputs=[m, txt_input], outputs=[o])o.change(add_gallery, [o, m, gallery], [gallery])stop_button.click(lambda: gr.update(interactive = False), None, stop_button, cancels = [gen_event])with gr.Column(scale=4):with gr.Accordion('Model selection'):model_choice = gr.CheckboxGroup(models, label = f'Choose up to {int(num_models)} different models from the {len(models)} available!', value=default_models, interactive=True)model_choice.change(update_imgbox, model_choice, output)#model_choice.change(update_imgbox_gallery, model_choice, output)model_choice.change(extend_choices, model_choice, current_models)gr.Markdown("Based on the [TestGen](https://huggingface.co/spaces/derwahnsinn/TestGen) Space by derwahnsinn, the [SpacIO](https://huggingface.co/spaces/RdnUser77/SpacIO_v1) Space by RdnUser77 and Omnibus's Maximum Multiplier!")demo.queue()demo.launch()1234567891011121314151617181920214 unmodified lines262728293031323334351 unmodified line373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293946 unmodified lines1011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471482 unmodified lines151152153154155156157158159160161162163164165166167168169170171import gradio as grfrom all_models import modelsfrom externalmod import gr_Interface_load, save_image, randomize_seedimport asyncioimport osfrom threading import RLocklock = 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_loadmodels_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'])4 unmodified linesnum_models = 6timeout = 600default_models = models[:num_models]MAX_SEED = 3999999999def extend_choices(choices):return choices[:num_models] + (num_models - len(choices[:num_models])) * ['NA']1 unmodified linedef 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 randomrandom.seed()return random.choices(models, k=561)# https://huggingface.co/docs/api-inference/detailed_parameters# https://huggingface.co/docs/huggingface_hub/package_reference/inference_clientasync def infer(model_str, prompt, nprompt="", height=0, width=0, cfg=0, seed=-1, timeout=inference_timeout):kwargs = {}if height > 0: kwargs["height"] = heightif width > 0: kwargs["width"] = widthif cfg > 0: cfg = kwargs["guidance_scale"] = cfgif seed == -1: kwargs["seed"] = randomize_seed()else: kwargs["seed"] = seedtask = 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 = Noneraise Exception(f"Task timed out: {model_str}") from eexcept Exception as e:print(e)if not task.done(): task.cancel()result = Noneraise Exception() from eif 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 imagereturn Nonedef 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 = Noneraise gr.Error(f"Task aborted: {model_str}, Error: {e}")finally:loop.close()return result6 unmodified linesreturn galleryCSS=""".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("""<div><p> <center>For more options like single model x6 check out <a href="https://huggingface.co/spaces/John6666/Diffusion80XX4sg">Diffusion80XX4sg</a> by John6666!</center></p></div>""")with gr.Tab('Huggingface Diffusion'):with gr.Column(scale=2):with gr.Group():txt_input = gr.Textbox(label='Your prompt:', lines=4)neg_input = gr.Textbox(label='Negative prompt:', lines=1)with gr.Accordion("Advanced", open=False, visible=True):with gr.Row():width = gr.Slider(label="Width", info="If 0, the default value is used.", maximum=1216, step=32, value=0)height = gr.Slider(label="Height", info="If 0, the default value is used.", maximum=1216, step=32, value=0)with gr.Row():cfg = gr.Slider(label="Guidance scale", info="If 0, the default value is used.", maximum=30.0, step=0.1, value=0)seed = gr.Slider(label="Seed", info="Randomize Seed if -1.", minimum=-1, maximum=MAX_SEED, step=1, value=-1)seed_rand = gr.Button("Randomize Seed ??", size="sm", variant="secondary")seed_rand.click(randomize_seed, None, [seed], queue=False)with gr.Row():gen_button = gr.Button(f'Generate up to {int(num_models)} images from 10 seconds to 3 minutes total', variant='primary', scale=3)random_button = gr.Button(f'Random {int(num_models)} ??', variant='secondary', scale=1)#gen_button.click(lambda: gr.update(interactive = True), None, stop_button)gr.Markdown("Scroll down to see more images and select models.", elem_classes="guide")with gr.Column(scale=1):with gr.Group():with gr.Row():output = [gr.Image(label=m, show_download_button=True, elem_classes="output",interactive=False, min_width=80, show_share_button=False, format="png",visible=True) for m in default_models]current_models = [gr.Textbox(m, visible=False) for m in default_models]with gr.Column(scale=2):2 unmodified linespreview=True, object_fit="cover", columns=2, rows=2)for m, o in zip(current_models, output):gen_event = gr.on(triggers=[gen_button.click, txt_input.submit], fn=gen_fn,inputs=[m, txt_input, neg_input, height, width, cfg, seed], outputs=[o],concurrency_limit=None, queue=False) # Be sure to delete ", queue=False" when activating the stop buttono.change(add_gallery, [o, m, gallery], [gallery])#stop_button.click(lambda: gr.update(interactive = False), None, stop_button, cancels = [gen_event])with gr.Column(scale=4):with gr.Accordion('Model selection'):model_choice = gr.CheckboxGroup(models, label = f'Choose up to {int(num_models)} different models from the {len(models)} available!', value=default_models, interactive=True)model_choice.change(update_imgbox, model_choice, output)model_choice.change(extend_choices, model_choice, current_models)random_button.click(random_choices, None, model_choice)gr.Markdown("Based on the [TestGen](https://huggingface.co/spaces/derwahnsinn/TestGen) Space by derwahnsinn, the [SpacIO](https://huggingface.co/spaces/RdnUser77/SpacIO_v1) Space by RdnUser77 and Omnibus's Maximum Multiplier!")demo.queue(default_concurrency_limit=200, max_size=200)demo.launch(show_api=False, max_threads=400)# https://github.com/gradio-app/gradio/issues/6339
8 unmodified lines910111213141517 unmodified lines33343536373839404142434 unmodified lines4849505152535410 unmodified lines6566676869707117 unmodified lines899091929394954 unmodified lines1001011021031041051061071081091101113 unmodified lines115116117118119120121243 unmodified lines3653663673683693703713723733745 unmodified lines3803813823833843853864 unmodified lines39139239339439539639739839940040140240340440540640740840930 unmodified lines44044144244344444544644738 unmodified lines48648748848949049149233 unmodified lines5265275285295305318 unmodified linesimport tempfileimport warningsfrom pathlib import Pathfrom typing import TYPE_CHECKING, Callableimport httpximport huggingface_hub17 unmodified linesfrom gradio.interface import Interface@document()def load(name: str,src: str | None = None,hf_token: str | None = None,alias: str | None = None,**kwargs,) -> Blocks:4 unmodified linesParameters:name: the name of the model (e.g. "gpt2" or "facebook/bart-base") or space (e.g. "flax-community/spanish-gpt2"), can include the `src` as prefix (e.g. "models/facebook/bart-base")src: the source of the model: `models` or `spaces` (or leave empty if source is provided as a prefix in `name`)hf_token: optional access token for loading private Hugging Face Hub models or spaces. Find your token here: https://huggingface.co/settings/tokens. Warning: only provide this if you are loading a trusted private Space as it can be read by the Space you are loading.alias: optional string used as the name of the loaded model instead of the default name (only applies if loading a Space running Gradio 2.x)Returns:a Gradio Blocks object for the given model10 unmodified linesdef load_blocks_from_repo(name: str,src: str | None = None,hf_token: str | None = None,alias: str | None = None,**kwargs,) -> Blocks:17 unmodified linesif src.lower() not in factory_methods:raise ValueError(f"parameter: src must be one of {factory_methods.keys()}")if hf_token is not None:if Context.hf_token is not None and Context.hf_token != hf_token:warnings.warn("""You are loading a model/Space with a different access token than the one you used to load a previous model/Space. This is not recommended, as it may cause unexpected behavior."""4 unmodified linesreturn blocksdef from_model(model_name: str, hf_token: str | None, alias: str | None, **kwargs):model_url = f"https://huggingface.co/{model_name}"api_url = f"https://api-inference.huggingface.co/models/{model_name}"print(f"Fetching model from: {model_url}")headers = {"Authorization": f"Bearer {hf_token}"} if hf_token is not None else {}response = httpx.request("GET", api_url, headers=headers)if response.status_code != 200:raise ModelNotFoundError(3 unmodified linesheaders["X-Wait-For-Model"] = "true"client = huggingface_hub.InferenceClient(model=model_name, headers=headers, token=hf_token,)# For tasks that are not yet supported by the InferenceClient243 unmodified lineselse:raise ValueError(f"Unsupported pipeline type: {p}")def query_huggingface_inference_endpoints(*data):if preprocess is not None:data = preprocess(*data)data = fn(*data) # type: ignoreif postprocess is not None:data = postprocess(data) # type: ignorereturn data5 unmodified lines"inputs": inputs,"outputs": outputs,"title": model_name,# "examples": examples,}kwargs = dict(interface_info, **kwargs)4 unmodified linesdef from_spaces(space_name: str, hf_token: str | None, alias: str | None, **kwargs) -> Blocks:client = Client(space_name,hf_token=hf_token,download_files=False,_skip_components=False,)space_url = f"https://huggingface.co/spaces/{space_name}"print(f"Fetching Space from: {space_url}")headers = {}if hf_token is not None:headers["Authorization"] = f"Bearer {hf_token}"iframe_url = (30 unmodified lines"Blocks or Interface locally. You may find this Guide helpful: ""https://gradio.app/using_blocks_like_functions/")if client.app_version < version.Version("4.0.0b14"):return from_spaces_blocks(space=space_name, hf_token=hf_token)def from_spaces_blocks(space: str, hf_token: str | None) -> Blocks:38 unmodified linesconfig = external_utils.streamline_spaces_interface(config)api_url = f"{iframe_url}/api/predict/"headers = {"Content-Type": "application/json"}if hf_token is not None:headers["Authorization"] = f"Bearer {hf_token}"# The function should call the API with preprocessed data33 unmodified linessrc: str | None = None,hf_token: str | None = None,alias: str | None = None,**kwargs,) -> Blocks:return load_blocks_from_repo(name, src, hf_token, alias)8 unmodified lines910111213141517 unmodified lines3334353637383940414243444546474 unmodified lines5253545556575810 unmodified lines6970717273747517 unmodified lines939495969798994 unmodified lines1041051061071081091101111121131141151161171181193 unmodified lines123124125126127128129243 unmodified lines3733743753763773783793803813823833843853865 unmodified lines3923933943953963973984 unmodified lines40340440540640740840941041141241341430 unmodified lines44544644744844945045138 unmodified lines49049149249349449549633 unmodified lines5305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116128 unmodified linesimport tempfileimport warningsfrom pathlib import Pathfrom typing import TYPE_CHECKING, Callable, Literalimport httpximport huggingface_hub17 unmodified linesfrom gradio.interface import InterfaceHF_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.server_timeout = 600@document()def load(name: str,src: str | None = None,hf_token: str | Literal[False] | None = None,alias: str | None = None,**kwargs,) -> Blocks:4 unmodified linesParameters:name: the name of the model (e.g. "gpt2" or "facebook/bart-base") or space (e.g. "flax-community/spanish-gpt2"), can include the `src` as prefix (e.g. "models/facebook/bart-base")src: the source of the model: `models` or `spaces` (or leave empty if source is provided as a prefix in `name`)hf_token: optional access token for loading private Hugging Face Hub models or spaces. Will default to the locally saved token if not provided. Pass `token=False` if you don't want to send your token to the server. Find your token here: https://huggingface.co/settings/tokens. Warning: only provide a token if you are loading a trusted private Space as it can be read by the Space you are loading.alias: optional string used as the name of the loaded model instead of the default name (only applies if loading a Space running Gradio 2.x)Returns:a Gradio Blocks object for the given model10 unmodified linesdef load_blocks_from_repo(name: str,src: str | None = None,hf_token: str | Literal[False] | None = None,alias: str | None = None,**kwargs,) -> Blocks:17 unmodified linesif src.lower() not in factory_methods:raise ValueError(f"parameter: src must be one of {factory_methods.keys()}")if hf_token is not None and hf_token is not False:if Context.hf_token is not None and Context.hf_token != hf_token:warnings.warn("""You are loading a model/Space with a different access token than the one you used to load a previous model/Space. This is not recommended, as it may cause unexpected behavior."""4 unmodified linesreturn blocksdef from_model(model_name: str, hf_token: str | Literal[False] | None, alias: str | None, **kwargs):model_url = f"https://huggingface.co/{model_name}"api_url = f"https://api-inference.huggingface.co/models/{model_name}"print(f"Fetching model from: {model_url}")headers = ({} if hf_token in [False, None] else {"Authorization": f"Bearer {hf_token}"})response = httpx.request("GET", api_url, headers=headers)if response.status_code != 200:raise ModelNotFoundError(3 unmodified linesheaders["X-Wait-For-Model"] = "true"client = huggingface_hub.InferenceClient(model=model_name, headers=headers, token=hf_token, timeout=server_timeout,)# For tasks that are not yet supported by the InferenceClient243 unmodified lineselse:raise ValueError(f"Unsupported pipeline type: {p}")def query_huggingface_inference_endpoints(*data, **kwargs):if preprocess is not None:data = preprocess(*data)try:data = fn(*data, **kwargs) # type: ignoreexcept huggingface_hub.utils.HfHubHTTPError as e:if "429" in str(e):raise TooManyRequestsError() from eif postprocess is not None:data = postprocess(data) # type: ignorereturn data5 unmodified lines"inputs": inputs,"outputs": outputs,"title": model_name,#"examples": examples,}kwargs = dict(interface_info, **kwargs)4 unmodified linesdef from_spaces(space_name: str, hf_token: str | None, alias: str | None, **kwargs) -> Blocks:space_url = f"https://huggingface.co/spaces/{space_name}"print(f"Fetching Space from: {space_url}")headers = {}if hf_token not in [False, None]:headers["Authorization"] = f"Bearer {hf_token}"iframe_url = (30 unmodified lines"Blocks or Interface locally. You may find this Guide helpful: ""https://gradio.app/using_blocks_like_functions/")return from_spaces_blocks(space=space_name, hf_token=hf_token)def from_spaces_blocks(space: str, hf_token: str | None) -> Blocks:38 unmodified linesconfig = external_utils.streamline_spaces_interface(config)api_url = f"{iframe_url}/api/predict/"headers = {"Content-Type": "application/json"}if hf_token not in [False, None]:headers["Authorization"] = f"Bearer {hf_token}"# The function should call the API with preprocessed data33 unmodified linessrc: str | None = None,hf_token: str | None = None,alias: str | None = None,**kwargs, # ignore) -> Blocks:try:return load_blocks_from_repo(name, src, hf_token, alias)except Exception as e:print(e)return gradio.Interface(lambda: None, ['text'], ['image'])def list_uniq(l):return sorted(set(l), key=l.index)def get_status(model_name: str):from huggingface_hub import AsyncInferenceClientclient = AsyncInferenceClient(token=HF_TOKEN, timeout=10)return client.get_model_status(model_name)def is_loadable(model_name: str, force_gpu: bool = False):try:status = get_status(model_name)except Exception as e:print(e)print(f"Couldn't load {model_name}.")return Falsegpu_state = isinstance(status.compute_type, dict) and "gpu" in status.compute_type.keys()if status is None or status.state not in ["Loadable", "Loaded"] or (force_gpu and not gpu_state):print(f"Couldn't load {model_name}. Model state:'{status.state}', GPU:{gpu_state}")return status is not None and status.state in ["Loadable", "Loaded"] and (not force_gpu or gpu_state)def find_model_list(author: str="", tags: list[str]=[], not_tag="", sort: str="last_modified", limit: int=30, force_gpu=False, check_status=False):from huggingface_hub import HfApiapi = HfApi(token=HF_TOKEN)default_tags = ["diffusers"]if not sort: sort = "last_modified"limit = limit * 20 if check_status and force_gpu else limit * 5models = []try:model_infos = api.list_models(author=author, #task="text-to-image",tags=list_uniq(default_tags + tags), cardData=True, sort=sort, limit=limit)except Exception as e:print(f"Error: Failed to list models.")print(e)return modelsfor model in model_infos:if not model.private and not model.gated or HF_TOKEN is not None:loadable = is_loadable(model.id, force_gpu) if check_status else Trueif not_tag and not_tag in model.tags or not loadable: continuemodels.append(model.id)if len(models) == limit: breakreturn modelsdef save_image(image, savefile, modelname, prompt, nprompt, height=0, width=0, steps=0, cfg=0, seed=-1):from PIL import Image, PngImagePluginimport jsontry:metadata = {"prompt": prompt, "negative_prompt": nprompt, "Model": {"Model": modelname.split("/")[-1]}}if steps > 0: metadata["num_inference_steps"] = stepsif cfg > 0: metadata["guidance_scale"] = cfgif seed != -1: metadata["seed"] = seedif width > 0 and height > 0: metadata["resolution"] = f"{width} x {height}"metadata_str = json.dumps(metadata)info = PngImagePlugin.PngInfo()info.add_text("metadata", metadata_str)image.save(savefile, "PNG", pnginfo=info)return str(Path(savefile).resolve())except Exception as e:print(f"Failed to save image file: {e}")raise Exception(f"Failed to save image file:") from edef randomize_seed():from random import seed, randintMAX_SEED = 2**32-1seed()rseed = randint(0, MAX_SEED)return rseed
app.py+75-62
externalmod.py+105-24