Upload 13 files
Browse filesFiles changed (3)
- README.md+1
- app.py+86-97
- multit2i.py+90-88
7 unmodified lines89101112137 unmodified linesapp_file: app.pypinned: falseshort_description: Text-to-Image---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference7 unmodified lines8910111213147 unmodified linesapp_file: app.pypinned: falseshort_description: Text-to-Imagelicense: mit---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707110 unmodified lines828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140import gradio as grfrom model import modelsfrom multit2i import (load_models,infer_multi,infer_multi_random,save_gallery_images,change_model,get_model_info_md,loaded_models,get_positive_prefix,get_positive_suffix,get_negative_prefix,get_negative_suffix,get_recom_prompt_type,set_recom_prompt_preset,get_tag_type,)from tagger.tagger import (predict_tags_wd,remove_specific_prompt,convert_danbooru_to_e621_prompt,insert_recom_prompt,compose_prompt_to_copy,)from tagger.fl2sd3longcap import predict_tags_fl2_sd3from tagger.v2 import (V2_ALL_MODELS,v2_random_prompt,)from tagger.utils import (V2_ASPECT_RATIO_OPTIONS,V2_RATING_OPTIONS,V2_LENGTH_OPTIONS,V2_IDENTITY_OPTIONS,)load_models(models, 5)#load_models(models, 20) # Fetching 20 models at the same time. default: 5css = """#model_info { text-align: center; }"""with gr.Blocks(theme="NoCrypt/miku@>=1.2.2", css=css) as demo:with gr.Column():with gr.Accordion("Advanced settings", open=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)v2_length = gr.Radio(label="Length", info="The total length of the tags.", choices=list(V2_LENGTH_OPTIONS), value="long")v2_identity = gr.Radio(label="Keep identity", info="How strictly to keep the identity of the character or subject. If you specify the detail of subject in the prompt, you should choose `strict`. Otherwise, choose `none` or `lax`. `none` is very creative but sometimes ignores the input prompt.", choices=list(V2_IDENTITY_OPTIONS), value="lax")v2_ban_tags = gr.Textbox(label="Ban tags", info="Tags to ban from the output.", placeholder="alternate costumen, ...", value="censored")v2_tag_type = gr.Radio(label="Tag Type", info="danbooru for common, e621 for Pony.", choices=["danbooru", "e621"], value="danbooru", visible=False)v2_model = gr.Dropdown(label="Model", choices=list(V2_ALL_MODELS.keys()), value=list(V2_ALL_MODELS.keys())[0])v2_copy = gr.Button(value="Copy to clipboard", size="sm", interactive=False)with gr.Accordion("Model", open=True):model_name = gr.Dropdown(label="Select Model", show_label=False, choices=list(loaded_models.keys()), value=list(loaded_models.keys())[0], allow_custom_value=True)model_info = gr.Markdown(value=get_model_info_md(list(loaded_models.keys())[0]), elem_id="model_info")with gr.Group():with gr.Accordion("Prompt from Image File", open=False):tagger_image = gr.Image(label="Input image", type="pil", sources=["upload", "clipboard"], height=256)10 unmodified linesv2_series = gr.Textbox(label="Series", placeholder="vocaloid", scale=2)random_prompt = gr.Button(value="Extend Prompt 🎲", size="sm", scale=1)clear_prompt = gr.Button(value="Clear Prompt 🗑️", size="sm", scale=1)prompt = gr.Text(label="Prompt", lines=1, 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.Row():run_button = gr.Button("Generate Image", scale=6)random_button = gr.Button("Random Model 🎲", scale=3)image_num = gr.Number(label="Count", minimum=1, maximum=16, value=1, step=1, interactive=True, scale=1)results = gr.Gallery(label="Gallery", interactive=False, show_download_button=True, show_share_button=False,container=True, format="png", object_fit="contain")image_files = gr.Files(label="Download", interactive=False)clear_results = gr.Button("Clear Gallery / Download")examples = gr.Examples(examples = [["souryuu asuka langley, 1girl, neon genesis evangelion, plugsuit, pilot suit, red bodysuit, sitting, crossing legs, black eye patch, cat hat, throne, symmetrical, looking down, from bottom, looking at viewer, outdoors"],["sailor moon, magical girl transformation, sparkles and ribbons, soft pastel colors, crescent moon motif, starry night sky background, shoujo manga style"],["kafuu chino, 1girl, solo"],["1girl"],["beautiful sunset"],],inputs=[prompt],)gr.Markdown(f"""This demo was created in reference to the following demos.- [Nymbo/Flood](https://huggingface.co/spaces/Nymbo/Flood).- [Yntec/ToyWorldXL](https://huggingface.co/spaces/Yntec/ToyWorldXL).""")gr.DuplicateButton(value="Duplicate Space")model_name.change(change_model, [model_name], [model_info], queue=False, show_api=False)gr.on(triggers=[run_button.click, prompt.submit],fn=infer_multi,inputs=[prompt, neg_prompt, results, image_num, model_name,positive_prefix, positive_suffix, negative_prefix, negative_suffix],outputs=[results],queue=True,show_progress="full",show_api=True,).success(save_gallery_images, [results], [results, image_files], queue=False, show_api=False)gr.on(triggers=[random_button.click],fn=infer_multi_random,inputs=[prompt, neg_prompt, results, image_num,positive_prefix, positive_suffix, negative_prefix, negative_suffix],outputs=[results],queue=True,show_progress="full",show_api=True,).success(save_gallery_images, [results], [results, image_files], queue=False, show_api=False)clear_prompt.click(lambda: (None, None, None), None, [prompt, v2_series, v2_character], queue=False, show_api=False)clear_results.click(lambda: (None, None), None, [results, image_files], queue=False, show_api=False)recom_prompt_preset.change(set_recom_prompt_preset, [recom_prompt_preset],[positive_prefix, positive_suffix, negative_prefix, negative_suffix], queue=False, show_api=False)random_prompt.click(v2_random_prompt, [prompt, v2_series, v2_character, v2_rating, v2_aspect_ratio, v2_length,v2_identity, v2_ban_tags, v2_model], [prompt, v2_series, v2_character], show_api=False,1234567891011121314151617181920212223242526272829303132333435363710 unmodified lines48495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129import gradio as grfrom model import modelsfrom multit2i import (load_models, infer_fn, infer_rand_fn, save_gallery,change_model, warm_model, get_model_info_md, loaded_models,get_positive_prefix, get_positive_suffix, get_negative_prefix, get_negative_suffix,get_recom_prompt_type, set_recom_prompt_preset, get_tag_type,)from tagger.tagger import (predict_tags_wd, remove_specific_prompt, convert_danbooru_to_e621_prompt,insert_recom_prompt, compose_prompt_to_copy,)from tagger.fl2sd3longcap import predict_tags_fl2_sd3from tagger.v2 import V2_ALL_MODELS, v2_random_promptfrom tagger.utils import (V2_ASPECT_RATIO_OPTIONS, V2_RATING_OPTIONS,V2_LENGTH_OPTIONS, V2_IDENTITY_OPTIONS,)max_images = 8load_models(models)css = """.model_info { text-align: center; }.output { width=112px; height=112px; !important; }.gallery { width=100%; min_height=768px; !important; }"""with gr.Blocks(theme="NoCrypt/miku@>=1.2.2", fill_width=True, css=css) as demo:with gr.Column():with gr.Group():model_name = gr.Dropdown(label="Select Model", choices=list(loaded_models.keys()), value=list(loaded_models.keys())[0], allow_custom_value=True)model_info = gr.Markdown(value=get_model_info_md(list(loaded_models.keys())[0]), elem_classes="model_info")with gr.Group():with gr.Accordion("Prompt from Image File", open=False):tagger_image = gr.Image(label="Input image", type="pil", sources=["upload", "clipboard"], height=256)10 unmodified linesv2_series = gr.Textbox(label="Series", placeholder="vocaloid", scale=2)random_prompt = gr.Button(value="Extend Prompt 🎲", size="sm", scale=1)clear_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)v2_length = gr.Radio(label="Length", info="The total length of the tags.", choices=list(V2_LENGTH_OPTIONS), value="long")v2_identity = gr.Radio(label="Keep identity", info="How strictly to keep the identity of the character or subject. If you specify the detail of subject in the prompt, you should choose `strict`. Otherwise, choose `none` or `lax`. `none` is very creative but sometimes ignores the input prompt.", choices=list(V2_IDENTITY_OPTIONS), value="lax")v2_ban_tags = gr.Textbox(label="Ban tags", info="Tags to ban from the output.", placeholder="alternate costumen, ...", value="censored")v2_tag_type = gr.Radio(label="Tag Type", info="danbooru for common, e621 for Pony.", choices=["danbooru", "e621"], value="danbooru", visible=False)v2_model = gr.Dropdown(label="Model", choices=list(V2_ALL_MODELS.keys()), value=list(V2_ALL_MODELS.keys())[0])v2_copy = gr.Button(value="Copy to clipboard", size="sm", interactive=False)image_num = gr.Slider(label="Number of images", minimum=1, maximum=max_images, value=1, step=1, interactive=True, scale=1)with gr.Row():run_button = gr.Button("Generate Image", scale=6)random_button = gr.Button("Random Model 🎲", scale=3)stop_button = gr.Button('Stop', interactive=False, scale=1)with gr.Column():with gr.Group():with gr.Row():output = [gr.Image(label='', elem_classes="output", type="filepath", format=".png",show_download_button=True, show_share_button=False, show_label=False,interactive=False, min_width=80, visible=True) for _ in range(max_images)]with gr.Group():results = gr.Gallery(label="Gallery", elem_classes="gallery", interactive=False, show_download_button=True, show_share_button=False,container=True, format="png", object_fit="cover", columns=2, rows=2)image_files = gr.Files(label="Download", interactive=False)clear_results = gr.Button("Clear Gallery / Download 🗑️")with gr.Column():examples = gr.Examples(examples = [["souryuu asuka langley, 1girl, neon genesis evangelion, plugsuit, pilot suit, red bodysuit, sitting, crossing legs, black eye patch, cat hat, throne, symmetrical, looking down, from bottom, looking at viewer, outdoors"],["sailor moon, magical girl transformation, sparkles and ribbons, soft pastel colors, crescent moon motif, starry night sky background, shoujo manga style"],["kafuu chino, 1girl, solo"],["1girl"],["beautiful sunset"],],inputs=[prompt],)gr.Markdown(f"""This demo was created in reference to the following demos.<br>[Nymbo/Flood](https://huggingface.co/spaces/Nymbo/Flood),[Yntec/ToyWorldXL](https://huggingface.co/spaces/Yntec/ToyWorldXL),[Yntec/Diffusion80XX](https://huggingface.co/spaces/Yntec/Diffusion80XX).""")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)\.success(warm_model, [model_name], None, queue=True, show_api=False)for i, o in enumerate(output):img_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)clear_prompt.click(lambda: None, None, [prompt], queue=False, show_api=False)clear_results.click(lambda: (None, None), None, [results, image_files], queue=False, show_api=False)recom_prompt_preset.change(set_recom_prompt_preset, [recom_prompt_preset],[positive_prefix, positive_suffix, negative_prefix, negative_suffix], queue=False, show_api=False)random_prompt.click(v2_random_prompt, [prompt, v2_series, v2_character, v2_rating, v2_aspect_ratio, v2_length,v2_identity, v2_ban_tags, v2_model], [prompt, v2_series, v2_character], show_api=False,
79 unmodified lines80818283848586878889909192939495969798991001011021031041051061071081091101111129 unmodified lines12212312412512612712832 unmodified lines161162163164165166167168169170171172173174175176177178179180181182183184185186187107 unmodified lines29529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935079 unmodified linesreturn infodef save_gallery_images(images, progress=gr.Progress(track_tqdm=True)):from datetime import datetime, timezone, timedeltaprogress(0, desc="Updating gallery...")dt_now = datetime.now(timezone(timedelta(hours=9)))basename = dt_now.strftime('%Y%m%d_%H%M%S_')i = 1if not images: return imagesoutput_images = []output_paths = []for image in images:filename = f'{image[1]}_{basename}{str(i)}.png'i += 1oldpath = Path(image[0])newpath = oldpathtry:if oldpath.stem == "image" and oldpath.exists():newpath = oldpath.resolve().rename(Path(filename).resolve())except Exception as e:print(e)passfinally:output_paths.append(str(newpath))output_images.append((str(newpath), str(filename)))progress(1, desc="Gallery updated.")return gr.update(value=output_images), gr.update(value=output_paths)def load_from_model(model_name: str, hf_token: str = None):import httpximport huggingface_hub9 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)inputs = gr.components.Textbox(label="Input")outputs = gr.components.Image(label="Output")fn = client.text_to_image32 unmodified linesreturn loaded_models[model_name]async def async_load_models(models: list, limit: int=5):sem = asyncio.Semaphore(limit)async def async_load_model(model: str):async with sem:try:return await asyncio.to_thread(load_model, model)except Exception as e:print(e)tasks = [asyncio.create_task(async_load_model(model)) for model in models]return await asyncio.gather(*tasks, return_exceptions=True)def load_models(models: list, limit: int=5):loop = asyncio.new_event_loop()try:loop.run_until_complete(async_load_models(models, limit))except Exception as e:print(e)passfinally:loop.close()positive_prefix = {107 unmodified linesreturn get_model_info_md(model_name)def infer(prompt: str, neg_prompt: str, model_name: str):from PIL import Imageimport randomseed = ""rand = random.randint(1, 500)for i in range(rand):seed += " "caption = model_name.split("/")[-1]try:model = load_model(model_name)if not model: return (Image.Image(), None)image_path = model(prompt + seed)image = Image.open(image_path).convert('RGBA')except Exception as e:print(e)return (Image.Image(), None)return (image, caption)async def infer_multi(prompt: str, neg_prompt: str, results: list, image_num: float, model_name: str,pos_pre: list = [], pos_suf: list = [], neg_pre: list = [], neg_suf: list = [], progress=gr.Progress(track_tqdm=True)):from tqdm.asyncio import tqdm_asyncioimage_num = int(image_num)images = results if results else []prompt, neg_prompt = recom_prompt(prompt, neg_prompt, pos_pre, pos_suf, neg_pre, neg_suf)tasks = [asyncio.to_thread(infer, prompt, neg_prompt, model_name) for i in range(image_num)]#results = await asyncio.gather(*tasks, return_exceptions=True)results = await tqdm_asyncio.gather(*tasks)if not results: results = []for result in results:with lock:if result and result[1]: images.append(result)yield imagesasync def infer_multi_random(prompt: str, neg_prompt: str, results: list, image_num: float,pos_pre: list = [], pos_suf: list = [], neg_pre: list = [], neg_suf: list = [], progress=gr.Progress(track_tqdm=True)):from tqdm.asyncio import tqdm_asyncioimport randomimage_num = int(image_num)images = results if results else []random.seed()model_names = random.choices(list(loaded_models.keys()), k = image_num)prompt, neg_prompt = recom_prompt(prompt, neg_prompt, pos_pre, pos_suf, neg_pre, neg_suf)tasks = [asyncio.to_thread(infer, prompt, neg_prompt, model_name) for model_name in model_names]#results = await asyncio.gather(*tasks, return_exceptions=True)results = await tqdm_asyncio.gather(*tasks)if not results: results = []for result in results:with lock:if result and result[1]: images.append(result)yield images79 unmodified lines80818283848586878889909192939495969798991001011021031041051061071081091101111121131141159 unmodified lines12512612712812913013132 unmodified lines164165166167168169170171172107 unmodified lines28028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135279 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 Nonedt_now = datetime.now(timezone(timedelta(hours=9)))filename = f"{model_name.split('/')[-1]}_{dt_now.strftime('%Y%m%d_%H%M%S')}.png"try:if 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 Noneexcept Exception as e:print(e)return Nonedef save_gallery(image_path: str | None, images: list[tuple] | None):if images is None: images = []files = [i[0] for i in images]if image_path is None: return images, filesfiles.insert(0, str(image_path))images.insert(0, (str(image_path), Path(image_path).stem))return images, files# https://github.com/gradio-app/gradio/blob/main/gradio/external.py# https://huggingface.co/docs/huggingface_hub/package_reference/inference_clientdef load_from_model(model_name: str, hf_token: str = None):import httpximport huggingface_hub9 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_image32 unmodified linesreturn loaded_models[model_name]def load_models(models: list):for model in models:load_model(model)positive_prefix = {107 unmodified linesreturn 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)for i in range(rand):noise += " "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)except (Exception, asyncio.TimeoutError) as e:print(e)print(f"Task timed out: {model_name}")if not task.done(): task.cancel()result = 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}")result = Nonefinally:loop.close()return 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 Nonerandom.seed()model_name = random.choice(list(loaded_models.keys()))try: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}")result = Nonefinally:loop.close()return result
README.md+1
app.py+86-97
multit2i.py+90-88