Commit ·
9ee88e4
1
Parent(s): 104e60a
Update: switch to new models with character support
Browse files19 unmodified lines202122232425264 unmodified lines31323334353637381 unmodified line404142434445466 unmodified lines5354555657585960616263645 unmodified lines707172737475767778798081828315 unmodified lines9910010110210310410510610710810911011111211311411511650 unmodified lines16716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520619 unmodified linesTITLE = "WaifuDiffusion v1.4 Tags"DESCRIPTION = """Demo for [SmilingWolf/wd-v1-4-vit-tagger](https://huggingface.co/SmilingWolf/wd-v1-4-vit-tagger) and [SmilingWolf/wd-v1-4-convnext-tagger](https://huggingface.co/SmilingWolf/wd-v1-4-convnext-tagger) with "ready to copy" prompt and a prompt analyzer.Modified from [NoCrypt/DeepDanbooru_string](https://huggingface.co/spaces/NoCrypt/DeepDanbooru_string)Modified from [hysts/DeepDanbooru](https://huggingface.co/spaces/hysts/DeepDanbooru)4 unmodified lines"""HF_TOKEN = os.environ["HF_TOKEN"]VIT_MODEL_REPO = "SmilingWolf/wd-v1-4-vit-tagger"CONV_MODEL_REPO = "SmilingWolf/wd-v1-4-convnext-tagger"MODEL_FILENAME = "model.onnx"LABEL_FILENAME = "selected_tags.csv"1 unmodified linedef parse_args() -> argparse.Namespace:parser = argparse.ArgumentParser()parser.add_argument("--score-slider-step", type=float, default=0.05)parser.add_argument("--score-threshold", type=float, default=0.35)parser.add_argument("--share", action="store_true")return parser.parse_args()6 unmodified linesreturn modeldef load_labels() -> list[str]:path = huggingface_hub.hf_hub_download(VIT_MODEL_REPO, LABEL_FILENAME, use_auth_token=HF_TOKEN)df = pd.read_csv(path)["name"].tolist()return dfdef plaintext_to_html(text):5 unmodified linesdef predict(image: PIL.Image.Image,selected_model: str,score_threshold: float,models: dict,labels: list[str],):rawimage = imagemodel = models[selected_model]_, height, width, _ = model.get_inputs()[0].shape# Alpha to white15 unmodified lineslabel_name = model.get_outputs()[0].nameprobs = model.run([label_name], {input_name: image})[0]labels = list(zip(labels, probs[0].astype(float)))# First 4 labels are actually ratings: pick one with argmaxratings_names = labels[:4]rating = dict(ratings_names)# Everything else is tags: pick any where prediction confidence > thresholdtags_names = labels[4:]res = [x for x in tags_names if x[1] > score_threshold]res = dict(res)b = dict(sorted(res.items(), key=lambda item: item[1], reverse=True))a = (", ".join(list(b.keys())).replace("_", " ")50 unmodified linesmessage = "Nothing found in the image."info = f"<div><p>{message}<p></div>"return (a, c, rating, res, info)def main():args = parse_args()vit_model = load_model(VIT_MODEL_REPO, MODEL_FILENAME)conv_model = load_model(CONV_MODEL_REPO, MODEL_FILENAME)labels = load_labels()models = {"ViT": vit_model, "ConvNext": conv_model}func = functools.partial(predict, models=models, labels=labels)gr.Interface(fn=func,inputs=[gr.Image(type="pil", label="Input"),gr.Radio(["ViT", "ConvNext"], value="ViT", label="Model"),gr.Slider(0,1,step=args.score_slider_step,value=args.score_threshold,label="Score Threshold",),],outputs=[gr.Textbox(label="Output (string)"),gr.Textbox(label="Output (raw string)"),gr.Label(label="Rating"),gr.Label(label="Output (label)"),gr.HTML(),],examples=[["power.jpg", "ViT", 0.5]],title=TITLE,description=DESCRIPTION,allow_flagging="never",19 unmodified lines2021222324252627282930314 unmodified lines3637383940414243441 unmodified line46474849505152536 unmodified lines606162636465666768697071727374757677787980818283848586878889905 unmodified lines9697989910010110210310410510610710810911011111211311411511611715 unmodified lines13313413513613713813914014114214314414514614714814915015115215315415550 unmodified lines20620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126219 unmodified linesTITLE = "WaifuDiffusion v1.4 Tags"DESCRIPTION = """Demo for:- [SmilingWolf/wd-v1-4-swinv2-tagger-v2](https://huggingface.co/SmilingWolf/wd-v1-4-convnext-tagger-v2)- [SmilingWolf/wd-v1-4-convnext-tagger-v2](https://huggingface.co/SmilingWolf/wd-v1-4-convnext-tagger-v2)- [SmilingWolf/wd-v1-4-vit-tagger-v2](https://huggingface.co/SmilingWolf/wd-v1-4-vit-tagger-v2)Includes "ready to copy" prompt and a prompt analyzer.Modified from [NoCrypt/DeepDanbooru_string](https://huggingface.co/spaces/NoCrypt/DeepDanbooru_string)Modified from [hysts/DeepDanbooru](https://huggingface.co/spaces/hysts/DeepDanbooru)4 unmodified lines"""HF_TOKEN = os.environ["HF_TOKEN"]SWIN_MODEL_REPO = "SmilingWolf/wd-v1-4-swinv2-tagger-v2"CONV_MODEL_REPO = "SmilingWolf/wd-v1-4-convnext-tagger-v2"VIT_MODEL_REPO = "SmilingWolf/wd-v1-4-vit-tagger-v2"MODEL_FILENAME = "model.onnx"LABEL_FILENAME = "selected_tags.csv"1 unmodified linedef parse_args() -> argparse.Namespace:parser = argparse.ArgumentParser()parser.add_argument("--score-slider-step", type=float, default=0.05)parser.add_argument("--score-general-threshold", type=float, default=0.35)parser.add_argument("--score-character-threshold", type=float, default=0.85)parser.add_argument("--share", action="store_true")return parser.parse_args()6 unmodified linesreturn modeldef change_model(model_name):global loaded_modelsif model_name == "SwinV2":model = load_model(SWIN_MODEL_REPO, MODEL_FILENAME)elif model_name == "ConvNext":model = load_model(CONV_MODEL_REPO, MODEL_FILENAME)elif model_name == "ViT":model = load_model(VIT_MODEL_REPO, MODEL_FILENAME)loaded_models[model_name] = modelreturn loaded_models[model_name]def load_labels() -> list[str]:path = huggingface_hub.hf_hub_download(SWIN_MODEL_REPO, LABEL_FILENAME, use_auth_token=HF_TOKEN)df = pd.read_csv(path)tag_names = df["name"].tolist()rating_indexes = list(np.where(df["category"] == 9)[0])general_indexes = list(np.where(df["category"] == 0)[0])character_indexes = list(np.where(df["category"] == 4)[0])return tag_names, rating_indexes, general_indexes, character_indexesdef plaintext_to_html(text):5 unmodified linesdef predict(image: PIL.Image.Image,model_name: str,general_threshold: float,character_threshold: float,tag_names: list[str],rating_indexes: list[np.int64],general_indexes: list[np.int64],character_indexes: list[np.int64],):global loaded_modelsrawimage = imagemodel = loaded_models[model_name]if model is None:model = change_model(model_name)_, height, width, _ = model.get_inputs()[0].shape# Alpha to white15 unmodified lineslabel_name = model.get_outputs()[0].nameprobs = model.run([label_name], {input_name: image})[0]labels = list(zip(tag_names, probs[0].astype(float)))# First 4 labels are actually ratings: pick one with argmaxratings_names = [labels[i] for i in rating_indexes]rating = dict(ratings_names)# Then we have general tags: pick any where prediction confidence > thresholdgeneral_names = [labels[i] for i in general_indexes]general_res = [x for x in general_names if x[1] > general_threshold]general_res = dict(general_res)# Everything else is characters: pick any where prediction confidence > thresholdcharacter_names = [labels[i] for i in character_indexes]character_res = [x for x in character_names if x[1] > character_threshold]character_res = dict(character_res)b = dict(sorted(general_res.items(), key=lambda item: item[1], reverse=True))a = (", ".join(list(b.keys())).replace("_", " ")50 unmodified linesmessage = "Nothing found in the image."info = f"<div><p>{message}<p></div>"return (a, c, rating, character_res, general_res, info)def main():global loaded_modelsloaded_models = {"SwinV2": None, "ConvNext": None, "ViT": None}args = parse_args()swin_model = load_model(SWIN_MODEL_REPO, MODEL_FILENAME)loaded_models["SwinV2"] = swin_modeltag_names, rating_indexes, general_indexes, character_indexes = load_labels()func = functools.partial(predict,tag_names=tag_names,rating_indexes=rating_indexes,general_indexes=general_indexes,character_indexes=character_indexes,)gr.Interface(fn=func,inputs=[gr.Image(type="pil", label="Input"),gr.Radio(["SwinV2", "ConvNext", "ViT"], value="SwinV2", label="Model"),gr.Slider(0,1,step=args.score_slider_step,value=args.score_general_threshold,label="General Tags Threshold",),gr.Slider(0,1,step=args.score_slider_step,value=args.score_character_threshold,label="Character Tags Threshold",),],outputs=[gr.Textbox(label="Output (string)"),gr.Textbox(label="Output (raw string)"),gr.Label(label="Rating"),gr.Label(label="Output (characters)"),gr.Label(label="Output (tags)"),gr.HTML(),],examples=[["power.jpg", "SwinV2", 0.5]],title=TITLE,description=DESCRIPTION,allow_flagging="never",
app.py+86-30