Upload 4 files
Browse filesFiles changed (4)
- README.md+3-3
- app.py+14-6
- model.py+1-1
- multit2i.py+86-18
12345678910---title: Popular SDXL Anime Text-to-Image Models Playground (John6666)emoji: 🖼️colorFrom: bluecolorTo: purplesdk: gradiosdk_version: 4.39.0app_file: app.pypinned: falseshort_description: Text-to-Image12345678910---title: 200+ Popular SDXL Anime Text-to-Image Models Playground (John6666)emoji: 🖼️⬇️colorFrom: bluecolorTo: purplesdk: gradiosdk_version: 4.40.0app_file: app.pypinned: falseshort_description: Text-to-Image
49 unmodified lines5051525354555657585960616238 unmodified lines1011021031041051062 unmodified lines10911011111211311411511611711811912049 unmodified linesclear_prompt = gr.Button(value="Clear Prompt 🗑️", size="sm", scale=1)prompt = gr.Text(label="Prompt", lines=2, max_lines=8, placeholder="1girl, solo, ...", show_copy_button=True)neg_prompt = gr.Text(label="Negative Prompt", lines=1, max_lines=8, placeholder="", visible=False)with gr.Accordion("Recommended Prompt", open=False):recom_prompt_preset = gr.Radio(label="Set Presets", choices=get_recom_prompt_type(), value="Common")with gr.Row():positive_prefix = gr.CheckboxGroup(label="Use Positive Prefix", choices=get_positive_prefix(), value=[])positive_suffix = gr.CheckboxGroup(label="Use Positive Suffix", choices=get_positive_suffix(), value=["Common"])negative_prefix = gr.CheckboxGroup(label="Use Negative Prefix", choices=get_negative_prefix(), value=[], visible=False)negative_suffix = gr.CheckboxGroup(label="Use Negative Suffix", choices=get_negative_suffix(), value=["Common"], visible=False)with gr.Accordion("Prompt Transformer", open=False):v2_rating = gr.Radio(label="Rating", choices=list(V2_RATING_OPTIONS), value="sfw")v2_aspect_ratio = gr.Radio(label="Aspect ratio", info="The aspect ratio of the image.", choices=list(V2_ASPECT_RATIO_OPTIONS), value="square", visible=False)38 unmodified lines""")gr.DuplicateButton(value="Duplicate Space")gr.on(triggers=[run_button.click, prompt.submit, random_button.click], fn=lambda: gr.update(interactive=True), inputs=None, outputs=stop_button, show_api=False)model_name.change(change_model, [model_name], [model_info], queue=False, show_api=False)\2 unmodified linesimg_i = gr.Number(i, visible=False)image_num.change(lambda i, n: gr.update(visible = (i < n)), [img_i, image_num], o, show_api=False)gen_event = gr.on(triggers=[run_button.click, prompt.submit],fn=lambda i, n, m, t1, t2, l1, l2, l3, l4: infer_fn(m, t1, t2, l1, l2, l3, l4) if (i < n) else None,inputs=[img_i, image_num, model_name, prompt, neg_prompt, positive_prefix, positive_suffix, negative_prefix, negative_suffix],outputs=[o], queue=True, show_api=False)gen_event2 = gr.on(triggers=[random_button.click],fn=lambda i, n, m, t1, t2, l1, l2, l3, l4: infer_rand_fn(m, t1, t2, l1, l2, l3, l4) if (i < n) else None,inputs=[img_i, image_num, model_name, prompt, neg_prompt, positive_prefix, positive_suffix, negative_prefix, negative_suffix],outputs=[o], queue=True, show_api=False)o.change(save_gallery, [o, results], [results, image_files], show_api=False)stop_button.click(lambda: gr.update(interactive=False), None, stop_button, cancels=[gen_event, gen_event2], show_api=False)49 unmodified lines50515253545556575859606162636465666738 unmodified lines1061071081091101111122 unmodified lines11511611711811912012112212312412512612712849 unmodified linesclear_prompt = gr.Button(value="Clear Prompt 🗑️", size="sm", scale=1)prompt = gr.Text(label="Prompt", lines=2, max_lines=8, placeholder="1girl, solo, ...", show_copy_button=True)neg_prompt = gr.Text(label="Negative Prompt", lines=1, max_lines=8, placeholder="", visible=False)with gr.Accordion("Advanced options", open=False):width = gr.Number(label="Width", info="If 0, the default value is used.", maximum=1216, step=32, value=None)height = gr.Number(label="Height", info="If 0, the default value is used.", maximum=1216, step=32, value=None)steps = gr.Number(label="Number of inference steps", info="If 0, the default value is used.", maximum=100, step=1, value=None)cfg = gr.Number(label="Guidance scale", info="If 0, the default value is used.", maximum=30.0, step=0.1, value=None)with gr.Accordion("Recommended Prompt", open=False):recom_prompt_preset = gr.Radio(label="Set Presets", choices=get_recom_prompt_type(), value="Common")with gr.Row():positive_prefix = gr.CheckboxGroup(label="Use Positive Prefix", choices=get_positive_prefix(), value=[])positive_suffix = gr.CheckboxGroup(label="Use Positive Suffix", choices=get_positive_suffix(), value=["Common"])negative_prefix = gr.CheckboxGroup(label="Use Negative Prefix", choices=get_negative_prefix(), value=[])negative_suffix = gr.CheckboxGroup(label="Use Negative Suffix", choices=get_negative_suffix(), value=["Common"])with gr.Accordion("Prompt Transformer", open=False):v2_rating = gr.Radio(label="Rating", choices=list(V2_RATING_OPTIONS), value="sfw")v2_aspect_ratio = gr.Radio(label="Aspect ratio", info="The aspect ratio of the image.", choices=list(V2_ASPECT_RATIO_OPTIONS), value="square", visible=False)38 unmodified lines""")gr.DuplicateButton(value="Duplicate Space")gr.Markdown(f"Just a few edits to *model.py* are all it takes to complete your own collection.")gr.on(triggers=[run_button.click, prompt.submit, random_button.click], fn=lambda: gr.update(interactive=True), inputs=None, outputs=stop_button, show_api=False)model_name.change(change_model, [model_name], [model_info], queue=False, show_api=False)\2 unmodified linesimg_i = gr.Number(i, visible=False)image_num.change(lambda i, n: gr.update(visible = (i < n)), [img_i, image_num], o, show_api=False)gen_event = gr.on(triggers=[run_button.click, prompt.submit],fn=lambda i, n, m, t1, t2, n1, n2, n3, n4, l1, l2, l3, l4: infer_fn(m, t1, t2, n1, n2, n3, n4, l1, l2, l3, l4) if (i < n) else None,inputs=[img_i, image_num, model_name, prompt, neg_prompt, height, width, steps, cfg,positive_prefix, positive_suffix, negative_prefix, negative_suffix],outputs=[o], queue=True, show_api=False)gen_event2 = gr.on(triggers=[random_button.click],fn=lambda i, n, m, t1, t2, n1, n2, n3, n4, l1, l2, l3, l4: infer_rand_fn(m, t1, t2, n1, n2, n3, n4, l1, l2, l3, l4) if (i < n) else None,inputs=[img_i, image_num, model_name, prompt, neg_prompt, height, width, steps, cfg,positive_prefix, positive_suffix, negative_prefix, negative_suffix],outputs=[o], queue=True, show_api=False)o.change(save_gallery, [o, results], [results, image_files], show_api=False)stop_button.click(lambda: gr.update(interactive=False), None, stop_button, cancels=[gen_event, gen_event2], show_api=False)
1234567from multit2i import find_model_listmodels = find_model_list("John6666", ["anime"], "", "downloads", 200)# Examples:1234567from multit2i import find_model_listmodels = find_model_list("John6666", ["anime"], "", "downloads", 250)# Examples:
1 unmodified line23456772 unmodified lines808182838485863 unmodified lines9091929394959628 unmodified lines12512612712812913013113213313413513613726 unmodified lines164165166167168169106 unmodified lines2762772782792802812822832842852862872882892902912922932942952961 unmodified line2982993003013023033044 unmodified lines3093103113123133143153163173183193203213223233243253263273283 unmodified lines3323333343353363373383392 unmodified lines3423433443453463473481 unmodified lineimport asynciofrom threading import RLockfrom pathlib import Pathlock = RLock()72 unmodified linesreturn infodef rename_image(image_path: str | None, model_name: str):from PIL import Imagefrom datetime import datetime, timezone, timedeltaif image_path is None: return None3 unmodified linesif Path(image_path).exists():png_path = "image.png"Image.open(image_path).convert('RGBA').save(png_path, "PNG")new_path = str(Path(png_path).resolve().rename(Path(filename).resolve()))return new_pathelse:return None28 unmodified linesf"Could not find model: {model_name}. If it is a private or gated model, please provide your Hugging Face access token (https://huggingface.co/settings/tokens) as the argument for the `hf_token` parameter.")headers["X-Wait-For-Model"] = "true"client = huggingface_hub.InferenceClient(model=model_name, headers=headers, token=hf_token, timeout=600)inputs = gr.components.Textbox(label="Input")outputs = gr.components.Image(label="Output")fn = client.text_to_imagedef query_huggingface_inference_endpoints(*data):return fn(*data)interface_info = {"fn": query_huggingface_inference_endpoints,26 unmodified linesreturn loaded_models[model_name]def load_models(models: list):for model in models:load_model(model)106 unmodified linesdef change_model(model_name: str):load_model(model_name)return get_model_info_md(model_name)def warm_model(model_name: str):model = load_model(model_name)if model:try:print(f"Warming model: {model_name}")model(" ")except Exception as e:print(e)async def infer(model_name: str, prompt: str, neg_prompt: str, timeout: float):import randomnoise = ""rand = random.randint(1, 500)1 unmodified linenoise += " "model = load_model(model_name)if not model: return Nonetask = asyncio.create_task(asyncio.to_thread(model, f'{prompt} {noise}'))await asyncio.sleep(0)try:result = await asyncio.wait_for(task, timeout=timeout)4 unmodified linesresult = Noneif task.done() and result is not None:with lock:image = rename_image(result, model_name)return imagereturn Noneinfer_timeout = 300def infer_fn(model_name: str, prompt: str, neg_prompt: str,pos_pre: list = [], pos_suf: list = [], neg_pre: list = [], neg_suf: list = []):if model_name == 'NA':return Nonetry:prompt, neg_prompt = recom_prompt(prompt, neg_prompt, pos_pre, pos_suf, neg_pre, neg_suf)loop = asyncio.new_event_loop()result = loop.run_until_complete(infer(model_name, prompt, neg_prompt, infer_timeout))except (Exception, asyncio.CancelledError) as e:print(e)print(f"Task aborted: {model_name}")3 unmodified linesreturn resultdef infer_rand_fn(model_name_dummy: str, prompt: str, neg_prompt: str,pos_pre: list = [], pos_suf: list = [], neg_pre: list = [], neg_suf: list = []):import randomif model_name_dummy == 'NA':return None2 unmodified linestry:prompt, neg_prompt = recom_prompt(prompt, neg_prompt, pos_pre, pos_suf, neg_pre, neg_suf)loop = asyncio.new_event_loop()result = loop.run_until_complete(infer(model_name, prompt, neg_prompt, infer_timeout))except (Exception, asyncio.CancelledError) as e:print(e)print(f"Task aborted: {model_name}")1 unmodified line2345678910111272 unmodified lines858687888990913 unmodified lines959697989910010110210310428 unmodified lines13313413513613713813914014114214314414514626 unmodified lines173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206106 unmodified lines3133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593601 unmodified line3623633643653663673683694 unmodified lines3743753763773783793803813823833843853863873883893903913923933943 unmodified lines3983994004014024034044054062 unmodified lines4094104114124134144154161 unmodified lineimport asynciofrom threading import RLockfrom pathlib import Pathfrom huggingface_hub import InferenceClientserver_timeout = 600inference_timeout = 300lock = RLock()72 unmodified linesreturn infodef rename_image(image_path: str | None, model_name: str, save_path: str | None = None):from PIL import Imagefrom datetime import datetime, timezone, timedeltaif image_path is None: return None3 unmodified linesif Path(image_path).exists():png_path = "image.png"Image.open(image_path).convert('RGBA').save(png_path, "PNG")if save_path is not None:new_path = str(Path(png_path).resolve().rename(Path(save_path).resolve()))else:new_path = str(Path(png_path).resolve().rename(Path(filename).resolve()))return new_pathelse:return None28 unmodified linesf"Could not find model: {model_name}. If it is a private or gated model, please provide your Hugging Face access token (https://huggingface.co/settings/tokens) as the argument for the `hf_token` parameter.")headers["X-Wait-For-Model"] = "true"client = huggingface_hub.InferenceClient(model=model_name, headers=headers,token=hf_token, timeout=server_timeout)inputs = gr.components.Textbox(label="Input")outputs = gr.components.Image(label="Output")fn = client.text_to_imagedef query_huggingface_inference_endpoints(*data, **kwargs):return fn(*data, **kwargs)interface_info = {"fn": query_huggingface_inference_endpoints,26 unmodified linesreturn loaded_models[model_name]def load_model_api(model_name: str):global loaded_modelsglobal model_info_dictif model_name in loaded_models.keys(): return loaded_models[model_name]try:client = InferenceClient(timeout=5)status = client.get_model_status(model_name)if status is None or status.framework != "diffusers" or status.state not in ["Loadable", "Loaded"]:print(f"Failed to load by API: {model_name}")return Noneelse:loaded_models[model_name] = InferenceClient(model_name, timeout=server_timeout)print(f"Loaded by API: {model_name}")except Exception as e:if model_name in loaded_models.keys(): del loaded_models[model_name]print(f"Failed to load by API: {model_name}")print(e)return Nonetry:model_info_dict[model_name] = get_t2i_model_info_dict(model_name)print(f"Assigned by API: {model_name}")except Exception as e:if model_name in model_info_dict.keys(): del model_info_dict[model_name]print(f"Failed to assigned by API: {model_name}")print(e)return loaded_models[model_name]def load_models(models: list):for model in models:load_model(model)106 unmodified linesdef change_model(model_name: str):load_model_api(model_name)return get_model_info_md(model_name)def warm_model(model_name: str):model = load_model_api(model_name)if model:try:print(f"Warming model: {model_name}")infer_body(model, " ")except Exception as e:print(e)# https://huggingface.co/docs/api-inference/detailed_parameters# https://huggingface.co/docs/huggingface_hub/package_reference/inference_clientdef infer_body(client: InferenceClient | gr.Interface, prompt: str, neg_prompt: str | None = None,height: int | None = None, width: int | None = None,steps: int | None = None, cfg: int | None = None):png_path = "image.png"kwargs = {}if height is not None and height >= 256: kwargs["height"] = heightif width is not None and width >= 256: kwargs["width"] = widthif steps is not None and steps >= 1: kwargs["num_inference_steps"] = stepsif cfg is not None and cfg > 0: cfg = kwargs["guidance_scale"] = cfgtry:if isinstance(client, InferenceClient):image = client.text_to_image(prompt=prompt, negative_prompt=neg_prompt, **kwargs)elif isinstance(client, gr.Interface):image = client.fn(prompt=prompt, negative_prompt=neg_prompt, **kwargs)else: return Noneimage.save(png_path)return str(Path(png_path).resolve())except Exception as e:print(e)return Noneasync def infer(model_name: str, prompt: str, neg_prompt: str | None = None,height: int | None = None, width: int | None = None,steps: int | None = None, cfg: int | None = None,save_path: str | None = None, timeout: float = inference_timeout):import randomnoise = ""rand = random.randint(1, 500)1 unmodified linenoise += " "model = load_model(model_name)if not model: return Nonetask = asyncio.create_task(asyncio.to_thread(infer_body, model, f"{prompt} {noise}", neg_prompt,height, width, steps, cfg))await asyncio.sleep(0)try:result = await asyncio.wait_for(task, timeout=timeout)4 unmodified linesresult = Noneif task.done() and result is not None:with lock:image = rename_image(result, model_name, save_path)return imagereturn Nonedef infer_fn(model_name: str, prompt: str, neg_prompt: str | None = None, height: int | None = None,width: int | None = None, steps: int | None = None, cfg: int | None = None,pos_pre: list = [], pos_suf: list = [], neg_pre: list = [], neg_suf: list = [], save_path: str | None = None):if model_name == 'NA':return Nonetry:prompt, neg_prompt = recom_prompt(prompt, neg_prompt, pos_pre, pos_suf, neg_pre, neg_suf)loop = asyncio.new_event_loop()result = loop.run_until_complete(infer(model_name, prompt, neg_prompt, height, width,steps, cfg, save_path, inference_timeout))except (Exception, asyncio.CancelledError) as e:print(e)print(f"Task aborted: {model_name}")3 unmodified linesreturn resultdef infer_rand_fn(model_name_dummy: str, prompt: str, neg_prompt: str | None = None, height: int | None = None,width: int | None = None, steps: int | None = None, cfg: int | None = None,pos_pre: list = [], pos_suf: list = [], neg_pre: list = [], neg_suf: list = [], save_path: str | None = None):import randomif model_name_dummy == 'NA':return None2 unmodified linestry:prompt, neg_prompt = recom_prompt(prompt, neg_prompt, pos_pre, pos_suf, neg_pre, neg_suf)loop = asyncio.new_event_loop()result = loop.run_until_complete(infer(model_name, prompt, neg_prompt, height, width,steps, cfg, save_path, inference_timeout))except (Exception, asyncio.CancelledError) as e:print(e)print(f"Task aborted: {model_name}")
README.md+3-3
app.py+14-6
model.py+1-1
multit2i.py+86-18