Spaces:
Running
on
Zero
Running
on
Zero
Delete tagger.py
Browse files
tagger.py
DELETED
|
@@ -1,549 +0,0 @@
|
|
| 1 |
-
from PIL import Image
|
| 2 |
-
import torch
|
| 3 |
-
import gradio as gr
|
| 4 |
-
import spaces
|
| 5 |
-
from transformers import (
|
| 6 |
-
AutoImageProcessor,
|
| 7 |
-
AutoModelForImageClassification,
|
| 8 |
-
)
|
| 9 |
-
from pathlib import Path
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
WD_MODEL_NAMES = ["p1atdev/wd-swinv2-tagger-v3-hf"]
|
| 13 |
-
WD_MODEL_NAME = WD_MODEL_NAMES[0]
|
| 14 |
-
|
| 15 |
-
wd_model = AutoModelForImageClassification.from_pretrained(WD_MODEL_NAME, trust_remote_code=True)
|
| 16 |
-
wd_model.to("cuda" if torch.cuda.is_available() else "cpu")
|
| 17 |
-
wd_processor = AutoImageProcessor.from_pretrained(WD_MODEL_NAME, trust_remote_code=True)
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
def _people_tag(noun: str, minimum: int = 1, maximum: int = 5):
|
| 21 |
-
return (
|
| 22 |
-
[f"1{noun}"]
|
| 23 |
-
+ [f"{num}{noun}s" for num in range(minimum + 1, maximum + 1)]
|
| 24 |
-
+ [f"{maximum+1}+{noun}s"]
|
| 25 |
-
)
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
PEOPLE_TAGS = (
|
| 29 |
-
_people_tag("girl") + _people_tag("boy") + _people_tag("other") + ["no humans"]
|
| 30 |
-
)
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
RATING_MAP = {
|
| 34 |
-
"sfw": "safe",
|
| 35 |
-
"general": "safe",
|
| 36 |
-
"sensitive": "sensitive",
|
| 37 |
-
"questionable": "nsfw",
|
| 38 |
-
"explicit": "explicit, nsfw",
|
| 39 |
-
}
|
| 40 |
-
DANBOORU_TO_E621_RATING_MAP = {
|
| 41 |
-
"sfw": "rating_safe",
|
| 42 |
-
"general": "rating_safe",
|
| 43 |
-
"safe": "rating_safe",
|
| 44 |
-
"sensitive": "rating_safe",
|
| 45 |
-
"nsfw": "rating_explicit",
|
| 46 |
-
"explicit, nsfw": "rating_explicit",
|
| 47 |
-
"explicit": "rating_explicit",
|
| 48 |
-
"rating:safe": "rating_safe",
|
| 49 |
-
"rating:general": "rating_safe",
|
| 50 |
-
"rating:sensitive": "rating_safe",
|
| 51 |
-
"rating:questionable, nsfw": "rating_explicit",
|
| 52 |
-
"rating:explicit, nsfw": "rating_explicit",
|
| 53 |
-
}
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
# https://github.com/toriato/stable-diffusion-webui-wd14-tagger/blob/a9eacb1eff904552d3012babfa28b57e1d3e295c/tagger/ui.py#L368
|
| 57 |
-
kaomojis = [
|
| 58 |
-
"0_0",
|
| 59 |
-
"(o)_(o)",
|
| 60 |
-
"+_+",
|
| 61 |
-
"+_-",
|
| 62 |
-
"._.",
|
| 63 |
-
"<o>_<o>",
|
| 64 |
-
"<|>_<|>",
|
| 65 |
-
"=_=",
|
| 66 |
-
">_<",
|
| 67 |
-
"3_3",
|
| 68 |
-
"6_9",
|
| 69 |
-
">_o",
|
| 70 |
-
"@_@",
|
| 71 |
-
"^_^",
|
| 72 |
-
"o_o",
|
| 73 |
-
"u_u",
|
| 74 |
-
"x_x",
|
| 75 |
-
"|_|",
|
| 76 |
-
"||_||",
|
| 77 |
-
]
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
def replace_underline(x: str):
|
| 81 |
-
return x.strip().replace("_", " ") if x not in kaomojis else x.strip()
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
def to_list(s):
|
| 85 |
-
return [x.strip() for x in s.split(",") if not s == ""]
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
def list_sub(a, b):
|
| 89 |
-
return [e for e in a if e not in b]
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
def list_uniq(l):
|
| 93 |
-
return sorted(set(l), key=l.index)
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
def load_dict_from_csv(filename):
|
| 97 |
-
dict = {}
|
| 98 |
-
if not Path(filename).exists():
|
| 99 |
-
if Path('./tagger/', filename).exists(): filename = str(Path('./tagger/', filename))
|
| 100 |
-
else: return dict
|
| 101 |
-
try:
|
| 102 |
-
with open(filename, 'r', encoding="utf-8") as f:
|
| 103 |
-
lines = f.readlines()
|
| 104 |
-
except Exception:
|
| 105 |
-
print(f"Failed to open dictionary file: {filename}")
|
| 106 |
-
return dict
|
| 107 |
-
for line in lines:
|
| 108 |
-
parts = line.strip().split(',')
|
| 109 |
-
dict[parts[0]] = parts[1]
|
| 110 |
-
return dict
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
anime_series_dict = load_dict_from_csv('character_series_dict.csv')
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
def character_list_to_series_list(character_list):
|
| 117 |
-
output_series_tag = []
|
| 118 |
-
series_tag = ""
|
| 119 |
-
series_dict = anime_series_dict
|
| 120 |
-
for tag in character_list:
|
| 121 |
-
series_tag = series_dict.get(tag, "")
|
| 122 |
-
if tag.endswith(")"):
|
| 123 |
-
tags = tag.split("(")
|
| 124 |
-
character_tag = "(".join(tags[:-1])
|
| 125 |
-
if character_tag.endswith(" "):
|
| 126 |
-
character_tag = character_tag[:-1]
|
| 127 |
-
series_tag = tags[-1].replace(")", "")
|
| 128 |
-
|
| 129 |
-
if series_tag:
|
| 130 |
-
output_series_tag.append(series_tag)
|
| 131 |
-
|
| 132 |
-
return output_series_tag
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
def select_random_character(series: str, character: str):
|
| 136 |
-
from random import seed, randrange
|
| 137 |
-
seed()
|
| 138 |
-
character_list = list(anime_series_dict.keys())
|
| 139 |
-
character = character_list[randrange(len(character_list) - 1)]
|
| 140 |
-
series = anime_series_dict.get(character.split(",")[0].strip(), "")
|
| 141 |
-
return series, character
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
def danbooru_to_e621(dtag, e621_dict):
|
| 145 |
-
def d_to_e(match, e621_dict):
|
| 146 |
-
dtag = match.group(0)
|
| 147 |
-
etag = e621_dict.get(replace_underline(dtag), "")
|
| 148 |
-
if etag:
|
| 149 |
-
return etag
|
| 150 |
-
else:
|
| 151 |
-
return dtag
|
| 152 |
-
|
| 153 |
-
import re
|
| 154 |
-
tag = re.sub(r'[\w ]+', lambda wrapper: d_to_e(wrapper, e621_dict), dtag, 2)
|
| 155 |
-
return tag
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
danbooru_to_e621_dict = load_dict_from_csv('danbooru_e621.csv')
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
def convert_danbooru_to_e621_prompt(input_prompt: str = "", prompt_type: str = "danbooru"):
|
| 162 |
-
if prompt_type == "danbooru": return input_prompt
|
| 163 |
-
tags = input_prompt.split(",") if input_prompt else []
|
| 164 |
-
people_tags: list[str] = []
|
| 165 |
-
other_tags: list[str] = []
|
| 166 |
-
rating_tags: list[str] = []
|
| 167 |
-
|
| 168 |
-
e621_dict = danbooru_to_e621_dict
|
| 169 |
-
for tag in tags:
|
| 170 |
-
tag = replace_underline(tag)
|
| 171 |
-
tag = danbooru_to_e621(tag, e621_dict)
|
| 172 |
-
if tag in PEOPLE_TAGS:
|
| 173 |
-
people_tags.append(tag)
|
| 174 |
-
elif tag in DANBOORU_TO_E621_RATING_MAP.keys():
|
| 175 |
-
rating_tags.append(DANBOORU_TO_E621_RATING_MAP.get(tag.replace(" ",""), ""))
|
| 176 |
-
else:
|
| 177 |
-
other_tags.append(tag)
|
| 178 |
-
|
| 179 |
-
rating_tags = sorted(set(rating_tags), key=rating_tags.index)
|
| 180 |
-
rating_tags = [rating_tags[0]] if rating_tags else []
|
| 181 |
-
rating_tags = ["explicit, nsfw"] if rating_tags and rating_tags[0] == "explicit" else rating_tags
|
| 182 |
-
|
| 183 |
-
output_prompt = ", ".join(people_tags + other_tags + rating_tags)
|
| 184 |
-
|
| 185 |
-
return output_prompt
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
def translate_prompt(prompt: str = ""):
|
| 189 |
-
def translate_to_english(prompt):
|
| 190 |
-
import httpcore
|
| 191 |
-
setattr(httpcore, 'SyncHTTPTransport', 'AsyncHTTPProxy')
|
| 192 |
-
from googletrans import Translator
|
| 193 |
-
translator = Translator()
|
| 194 |
-
try:
|
| 195 |
-
translated_prompt = translator.translate(prompt, src='auto', dest='en').text
|
| 196 |
-
return translated_prompt
|
| 197 |
-
except Exception as e:
|
| 198 |
-
print(e)
|
| 199 |
-
return prompt
|
| 200 |
-
|
| 201 |
-
def is_japanese(s):
|
| 202 |
-
import unicodedata
|
| 203 |
-
for ch in s:
|
| 204 |
-
name = unicodedata.name(ch, "")
|
| 205 |
-
if "CJK UNIFIED" in name or "HIRAGANA" in name or "KATAKANA" in name:
|
| 206 |
-
return True
|
| 207 |
-
return False
|
| 208 |
-
|
| 209 |
-
def to_list(s):
|
| 210 |
-
return [x.strip() for x in s.split(",")]
|
| 211 |
-
|
| 212 |
-
prompts = to_list(prompt)
|
| 213 |
-
outputs = []
|
| 214 |
-
for p in prompts:
|
| 215 |
-
p = translate_to_english(p) if is_japanese(p) else p
|
| 216 |
-
outputs.append(p)
|
| 217 |
-
|
| 218 |
-
return ", ".join(outputs)
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
def translate_prompt_to_ja(prompt: str = ""):
|
| 222 |
-
def translate_to_japanese(prompt):
|
| 223 |
-
import httpcore
|
| 224 |
-
setattr(httpcore, 'SyncHTTPTransport', 'AsyncHTTPProxy')
|
| 225 |
-
from googletrans import Translator
|
| 226 |
-
translator = Translator()
|
| 227 |
-
try:
|
| 228 |
-
translated_prompt = translator.translate(prompt, src='en', dest='ja').text
|
| 229 |
-
return translated_prompt
|
| 230 |
-
except Exception as e:
|
| 231 |
-
print(e)
|
| 232 |
-
return prompt
|
| 233 |
-
|
| 234 |
-
def is_japanese(s):
|
| 235 |
-
import unicodedata
|
| 236 |
-
for ch in s:
|
| 237 |
-
name = unicodedata.name(ch, "")
|
| 238 |
-
if "CJK UNIFIED" in name or "HIRAGANA" in name or "KATAKANA" in name:
|
| 239 |
-
return True
|
| 240 |
-
return False
|
| 241 |
-
|
| 242 |
-
def to_list(s):
|
| 243 |
-
return [x.strip() for x in s.split(",")]
|
| 244 |
-
|
| 245 |
-
prompts = to_list(prompt)
|
| 246 |
-
outputs = []
|
| 247 |
-
for p in prompts:
|
| 248 |
-
p = translate_to_japanese(p) if not is_japanese(p) else p
|
| 249 |
-
outputs.append(p)
|
| 250 |
-
|
| 251 |
-
return ", ".join(outputs)
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
def tags_to_ja(itag, dict):
|
| 255 |
-
def t_to_j(match, dict):
|
| 256 |
-
tag = match.group(0)
|
| 257 |
-
ja = dict.get(replace_underline(tag), "")
|
| 258 |
-
if ja:
|
| 259 |
-
return ja
|
| 260 |
-
else:
|
| 261 |
-
return tag
|
| 262 |
-
|
| 263 |
-
import re
|
| 264 |
-
tag = re.sub(r'[\w ]+', lambda wrapper: t_to_j(wrapper, dict), itag, 2)
|
| 265 |
-
|
| 266 |
-
return tag
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
def convert_tags_to_ja(input_prompt: str = ""):
|
| 270 |
-
tags = input_prompt.split(",") if input_prompt else []
|
| 271 |
-
out_tags = []
|
| 272 |
-
|
| 273 |
-
tags_to_ja_dict = load_dict_from_csv('all_tags_ja_ext.csv')
|
| 274 |
-
dict = tags_to_ja_dict
|
| 275 |
-
for tag in tags:
|
| 276 |
-
tag = replace_underline(tag)
|
| 277 |
-
tag = tags_to_ja(tag, dict)
|
| 278 |
-
out_tags.append(tag)
|
| 279 |
-
|
| 280 |
-
return ", ".join(out_tags)
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
enable_auto_recom_prompt = True
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
animagine_ps = to_list("masterpiece, best quality, very aesthetic, absurdres")
|
| 287 |
-
animagine_nps = to_list("lowres, (bad), text, error, fewer, extra, missing, worst quality, jpeg artifacts, low quality, watermark, unfinished, displeasing, oldest, early, chromatic aberration, signature, extra digits, artistic error, username, scan, [abstract]")
|
| 288 |
-
pony_ps = to_list("score_9, score_8_up, score_7_up, masterpiece, best quality, very aesthetic, absurdres")
|
| 289 |
-
pony_nps = to_list("source_pony, score_6, score_5, score_4, busty, ugly face, mutated hands, low res, blurry face, black and white, the simpsons, overwatch, apex legends")
|
| 290 |
-
other_ps = to_list("anime artwork, anime style, studio anime, highly detailed, cinematic photo, 35mm photograph, film, bokeh, professional, 4k, highly detailed")
|
| 291 |
-
other_nps = to_list("photo, deformed, black and white, realism, disfigured, low contrast, drawing, painting, crayon, sketch, graphite, impressionist, noisy, blurry, soft, deformed, ugly")
|
| 292 |
-
default_ps = to_list("highly detailed, masterpiece, best quality, very aesthetic, absurdres")
|
| 293 |
-
default_nps = to_list("score_6, score_5, score_4, lowres, (bad), text, error, fewer, extra, missing, worst quality, jpeg artifacts, low quality, watermark, unfinished, displeasing, oldest, early, chromatic aberration, signature, extra digits, artistic error, username, scan, [abstract]")
|
| 294 |
-
def insert_recom_prompt(prompt: str = "", neg_prompt: str = "", type: str = "None"):
|
| 295 |
-
global enable_auto_recom_prompt
|
| 296 |
-
prompts = to_list(prompt)
|
| 297 |
-
neg_prompts = to_list(neg_prompt)
|
| 298 |
-
|
| 299 |
-
prompts = list_sub(prompts, animagine_ps + pony_ps)
|
| 300 |
-
neg_prompts = list_sub(neg_prompts, animagine_nps + pony_nps)
|
| 301 |
-
|
| 302 |
-
last_empty_p = [""] if not prompts and type != "None" else []
|
| 303 |
-
last_empty_np = [""] if not neg_prompts and type != "None" else []
|
| 304 |
-
|
| 305 |
-
if type == "Auto":
|
| 306 |
-
enable_auto_recom_prompt = True
|
| 307 |
-
else:
|
| 308 |
-
enable_auto_recom_prompt = False
|
| 309 |
-
if type == "Animagine":
|
| 310 |
-
prompts = prompts + animagine_ps
|
| 311 |
-
neg_prompts = neg_prompts + animagine_nps
|
| 312 |
-
elif type == "Pony":
|
| 313 |
-
prompts = prompts + pony_ps
|
| 314 |
-
neg_prompts = neg_prompts + pony_nps
|
| 315 |
-
|
| 316 |
-
prompt = ", ".join(list_uniq(prompts) + last_empty_p)
|
| 317 |
-
neg_prompt = ", ".join(list_uniq(neg_prompts) + last_empty_np)
|
| 318 |
-
|
| 319 |
-
return prompt, neg_prompt
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
def load_model_prompt_dict():
|
| 323 |
-
import json
|
| 324 |
-
dict = {}
|
| 325 |
-
path = 'model_dict.json' if Path('model_dict.json').exists() else './tagger/model_dict.json'
|
| 326 |
-
try:
|
| 327 |
-
with open('model_dict.json', encoding='utf-8') as f:
|
| 328 |
-
dict = json.load(f)
|
| 329 |
-
except Exception:
|
| 330 |
-
pass
|
| 331 |
-
return dict
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
model_prompt_dict = load_model_prompt_dict()
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
def insert_model_recom_prompt(prompt: str = "", neg_prompt: str = "", model_name: str = "None"):
|
| 338 |
-
if not model_name or not enable_auto_recom_prompt: return prompt, neg_prompt
|
| 339 |
-
prompts = to_list(prompt)
|
| 340 |
-
neg_prompts = to_list(neg_prompt)
|
| 341 |
-
prompts = list_sub(prompts, animagine_ps + pony_ps + other_ps)
|
| 342 |
-
neg_prompts = list_sub(neg_prompts, animagine_nps + pony_nps + other_nps)
|
| 343 |
-
last_empty_p = [""] if not prompts and type != "None" else []
|
| 344 |
-
last_empty_np = [""] if not neg_prompts and type != "None" else []
|
| 345 |
-
ps = []
|
| 346 |
-
nps = []
|
| 347 |
-
if model_name in model_prompt_dict.keys():
|
| 348 |
-
ps = to_list(model_prompt_dict[model_name]["prompt"])
|
| 349 |
-
nps = to_list(model_prompt_dict[model_name]["negative_prompt"])
|
| 350 |
-
else:
|
| 351 |
-
ps = default_ps
|
| 352 |
-
nps = default_nps
|
| 353 |
-
prompts = prompts + ps
|
| 354 |
-
neg_prompts = neg_prompts + nps
|
| 355 |
-
prompt = ", ".join(list_uniq(prompts) + last_empty_p)
|
| 356 |
-
neg_prompt = ", ".join(list_uniq(neg_prompts) + last_empty_np)
|
| 357 |
-
return prompt, neg_prompt
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
tag_group_dict = load_dict_from_csv('tag_group.csv')
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
def remove_specific_prompt(input_prompt: str = "", keep_tags: str = "all"):
|
| 364 |
-
def is_dressed(tag):
|
| 365 |
-
import re
|
| 366 |
-
p = re.compile(r'dress|cloth|uniform|costume|vest|sweater|coat|shirt|jacket|blazer|apron|leotard|hood|sleeve|skirt|shorts|pant|loafer|ribbon|necktie|bow|collar|glove|sock|shoe|boots|wear|emblem')
|
| 367 |
-
return p.search(tag)
|
| 368 |
-
|
| 369 |
-
def is_background(tag):
|
| 370 |
-
import re
|
| 371 |
-
p = re.compile(r'background|outline|light|sky|build|day|screen|tree|city')
|
| 372 |
-
return p.search(tag)
|
| 373 |
-
|
| 374 |
-
un_tags = ['solo']
|
| 375 |
-
group_list = ['groups', 'body_parts', 'attire', 'posture', 'objects', 'creatures', 'locations', 'disambiguation_pages', 'commonly_misused_tags', 'phrases', 'verbs_and_gerunds', 'subjective', 'nudity', 'sex_objects', 'sex', 'sex_acts', 'image_composition', 'artistic_license', 'text', 'year_tags', 'metatags']
|
| 376 |
-
keep_group_dict = {
|
| 377 |
-
"body": ['groups', 'body_parts'],
|
| 378 |
-
"dress": ['groups', 'body_parts', 'attire'],
|
| 379 |
-
"all": group_list,
|
| 380 |
-
}
|
| 381 |
-
|
| 382 |
-
def is_necessary(tag, keep_tags, group_dict):
|
| 383 |
-
if keep_tags == "all":
|
| 384 |
-
return True
|
| 385 |
-
elif tag in un_tags or group_dict.get(tag, "") in explicit_group:
|
| 386 |
-
return False
|
| 387 |
-
elif keep_tags == "body" and is_dressed(tag):
|
| 388 |
-
return False
|
| 389 |
-
elif is_background(tag):
|
| 390 |
-
return False
|
| 391 |
-
else:
|
| 392 |
-
return True
|
| 393 |
-
|
| 394 |
-
if keep_tags == "all": return input_prompt
|
| 395 |
-
keep_group = keep_group_dict.get(keep_tags, keep_group_dict["body"])
|
| 396 |
-
explicit_group = list(set(group_list) ^ set(keep_group))
|
| 397 |
-
|
| 398 |
-
tags = input_prompt.split(",") if input_prompt else []
|
| 399 |
-
people_tags: list[str] = []
|
| 400 |
-
other_tags: list[str] = []
|
| 401 |
-
|
| 402 |
-
group_dict = tag_group_dict
|
| 403 |
-
for tag in tags:
|
| 404 |
-
tag = replace_underline(tag)
|
| 405 |
-
if tag in PEOPLE_TAGS:
|
| 406 |
-
people_tags.append(tag)
|
| 407 |
-
elif is_necessary(tag, keep_tags, group_dict):
|
| 408 |
-
other_tags.append(tag)
|
| 409 |
-
|
| 410 |
-
output_prompt = ", ".join(people_tags + other_tags)
|
| 411 |
-
|
| 412 |
-
return output_prompt
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
def sort_taglist(tags: list[str]):
|
| 416 |
-
if not tags: return []
|
| 417 |
-
character_tags: list[str] = []
|
| 418 |
-
series_tags: list[str] = []
|
| 419 |
-
people_tags: list[str] = []
|
| 420 |
-
group_list = ['groups', 'body_parts', 'attire', 'posture', 'objects', 'creatures', 'locations', 'disambiguation_pages', 'commonly_misused_tags', 'phrases', 'verbs_and_gerunds', 'subjective', 'nudity', 'sex_objects', 'sex', 'sex_acts', 'image_composition', 'artistic_license', 'text', 'year_tags', 'metatags']
|
| 421 |
-
group_tags = {}
|
| 422 |
-
other_tags: list[str] = []
|
| 423 |
-
rating_tags: list[str] = []
|
| 424 |
-
|
| 425 |
-
group_dict = tag_group_dict
|
| 426 |
-
group_set = set(group_dict.keys())
|
| 427 |
-
character_set = set(anime_series_dict.keys())
|
| 428 |
-
series_set = set(anime_series_dict.values())
|
| 429 |
-
rating_set = set(DANBOORU_TO_E621_RATING_MAP.keys()) | set(DANBOORU_TO_E621_RATING_MAP.values())
|
| 430 |
-
|
| 431 |
-
for tag in tags:
|
| 432 |
-
tag = replace_underline(tag)
|
| 433 |
-
if tag in PEOPLE_TAGS:
|
| 434 |
-
people_tags.append(tag)
|
| 435 |
-
elif tag in rating_set:
|
| 436 |
-
rating_tags.append(tag)
|
| 437 |
-
elif tag in group_set:
|
| 438 |
-
elem = group_dict[tag]
|
| 439 |
-
group_tags[elem] = group_tags[elem] + [tag] if elem in group_tags else [tag]
|
| 440 |
-
elif tag in character_set:
|
| 441 |
-
character_tags.append(tag)
|
| 442 |
-
elif tag in series_set:
|
| 443 |
-
series_tags.append(tag)
|
| 444 |
-
else:
|
| 445 |
-
other_tags.append(tag)
|
| 446 |
-
|
| 447 |
-
output_group_tags: list[str] = []
|
| 448 |
-
for k in group_list:
|
| 449 |
-
output_group_tags.extend(group_tags.get(k, []))
|
| 450 |
-
|
| 451 |
-
rating_tags = [rating_tags[0]] if rating_tags else []
|
| 452 |
-
rating_tags = ["explicit, nsfw"] if rating_tags and rating_tags[0] == "explicit" else rating_tags
|
| 453 |
-
|
| 454 |
-
output_tags = character_tags + series_tags + people_tags + output_group_tags + other_tags + rating_tags
|
| 455 |
-
|
| 456 |
-
return output_tags
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
def sort_tags(tags: str):
|
| 460 |
-
if not tags: return ""
|
| 461 |
-
taglist: list[str] = []
|
| 462 |
-
for tag in tags.split(","):
|
| 463 |
-
taglist.append(tag.strip())
|
| 464 |
-
taglist = list(filter(lambda x: x != "", taglist))
|
| 465 |
-
return ", ".join(sort_taglist(taglist))
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
def postprocess_results(results: dict[str, float], general_threshold: float, character_threshold: float):
|
| 469 |
-
results = {
|
| 470 |
-
k: v for k, v in sorted(results.items(), key=lambda item: item[1], reverse=True)
|
| 471 |
-
}
|
| 472 |
-
|
| 473 |
-
rating = {}
|
| 474 |
-
character = {}
|
| 475 |
-
general = {}
|
| 476 |
-
|
| 477 |
-
for k, v in results.items():
|
| 478 |
-
if k.startswith("rating:"):
|
| 479 |
-
rating[k.replace("rating:", "")] = v
|
| 480 |
-
continue
|
| 481 |
-
elif k.startswith("character:"):
|
| 482 |
-
character[k.replace("character:", "")] = v
|
| 483 |
-
continue
|
| 484 |
-
|
| 485 |
-
general[k] = v
|
| 486 |
-
|
| 487 |
-
character = {k: v for k, v in character.items() if v >= character_threshold}
|
| 488 |
-
general = {k: v for k, v in general.items() if v >= general_threshold}
|
| 489 |
-
|
| 490 |
-
return rating, character, general
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
def gen_prompt(rating: list[str], character: list[str], general: list[str]):
|
| 494 |
-
people_tags: list[str] = []
|
| 495 |
-
other_tags: list[str] = []
|
| 496 |
-
rating_tag = RATING_MAP[rating[0]]
|
| 497 |
-
|
| 498 |
-
for tag in general:
|
| 499 |
-
if tag in PEOPLE_TAGS:
|
| 500 |
-
people_tags.append(tag)
|
| 501 |
-
else:
|
| 502 |
-
other_tags.append(tag)
|
| 503 |
-
|
| 504 |
-
all_tags = people_tags + other_tags
|
| 505 |
-
|
| 506 |
-
return ", ".join(all_tags)
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
@spaces.GPU()
|
| 510 |
-
def predict_tags(image: Image.Image, general_threshold: float = 0.3, character_threshold: float = 0.8):
|
| 511 |
-
inputs = wd_processor.preprocess(image, return_tensors="pt")
|
| 512 |
-
|
| 513 |
-
outputs = wd_model(**inputs.to(wd_model.device, wd_model.dtype))
|
| 514 |
-
logits = torch.sigmoid(outputs.logits[0]) # take the first logits
|
| 515 |
-
|
| 516 |
-
# get probabilities
|
| 517 |
-
results = {
|
| 518 |
-
wd_model.config.id2label[i]: float(logit.float()) for i, logit in enumerate(logits)
|
| 519 |
-
}
|
| 520 |
-
# rating, character, general
|
| 521 |
-
rating, character, general = postprocess_results(
|
| 522 |
-
results, general_threshold, character_threshold
|
| 523 |
-
)
|
| 524 |
-
prompt = gen_prompt(
|
| 525 |
-
list(rating.keys()), list(character.keys()), list(general.keys())
|
| 526 |
-
)
|
| 527 |
-
output_series_tag = ""
|
| 528 |
-
output_series_list = character_list_to_series_list(character.keys())
|
| 529 |
-
if output_series_list:
|
| 530 |
-
output_series_tag = output_series_list[0]
|
| 531 |
-
else:
|
| 532 |
-
output_series_tag = ""
|
| 533 |
-
return output_series_tag, ", ".join(character.keys()), prompt, gr.update(interactive=True)
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
def predict_tags_wd(image: Image.Image, input_tags: str, algo: list[str], general_threshold: float = 0.3,
|
| 537 |
-
character_threshold: float = 0.8, input_series: str = "", input_character: str = ""):
|
| 538 |
-
if not "Use WD Tagger" in algo and len(algo) != 0:
|
| 539 |
-
return input_series, input_character, input_tags, gr.update(interactive=True)
|
| 540 |
-
return predict_tags(image, general_threshold, character_threshold)
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
def compose_prompt_to_copy(character: str, series: str, general: str):
|
| 544 |
-
characters = character.split(",") if character else []
|
| 545 |
-
serieses = series.split(",") if series else []
|
| 546 |
-
generals = general.split(",") if general else []
|
| 547 |
-
tags = characters + serieses + generals
|
| 548 |
-
cprompt = ",".join(tags) if tags else ""
|
| 549 |
-
return cprompt
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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