Spaces:
Running
Running
two more characters
#5
by
Pixartist
- opened
- README.md +4 -3
- Utils/dbimutils.py +54 -0
- app.py +235 -300
- requirements.txt +2 -0
README.md
CHANGED
@@ -1,12 +1,13 @@
|
|
1 |
---
|
2 |
-
title: WaifuDiffusion
|
3 |
emoji: 💬
|
4 |
colorFrom: blue
|
5 |
colorTo: red
|
6 |
sdk: gradio
|
7 |
-
sdk_version:
|
8 |
app_file: app.py
|
9 |
pinned: false
|
|
|
10 |
---
|
11 |
|
12 |
# Configuration
|
@@ -35,4 +36,4 @@ Path to your main application file (which contains either `gradio` or `streamlit
|
|
35 |
Path is relative to the root of the repository.
|
36 |
|
37 |
`pinned`: _boolean_
|
38 |
-
Whether the Space stays on top of your list.
|
|
|
1 |
---
|
2 |
+
title: WaifuDiffusion v1.4 Tags
|
3 |
emoji: 💬
|
4 |
colorFrom: blue
|
5 |
colorTo: red
|
6 |
sdk: gradio
|
7 |
+
sdk_version: 3.16.2
|
8 |
app_file: app.py
|
9 |
pinned: false
|
10 |
+
duplicated_from: NoCrypt/DeepDanbooru_string
|
11 |
---
|
12 |
|
13 |
# Configuration
|
|
|
36 |
Path is relative to the root of the repository.
|
37 |
|
38 |
`pinned`: _boolean_
|
39 |
+
Whether the Space stays on top of your list.
|
Utils/dbimutils.py
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# DanBooru IMage Utility functions
|
2 |
+
|
3 |
+
import cv2
|
4 |
+
import numpy as np
|
5 |
+
from PIL import Image
|
6 |
+
|
7 |
+
|
8 |
+
def smart_imread(img, flag=cv2.IMREAD_UNCHANGED):
|
9 |
+
if img.endswith(".gif"):
|
10 |
+
img = Image.open(img)
|
11 |
+
img = img.convert("RGB")
|
12 |
+
img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
|
13 |
+
else:
|
14 |
+
img = cv2.imread(img, flag)
|
15 |
+
return img
|
16 |
+
|
17 |
+
|
18 |
+
def smart_24bit(img):
|
19 |
+
if img.dtype is np.dtype(np.uint16):
|
20 |
+
img = (img / 257).astype(np.uint8)
|
21 |
+
|
22 |
+
if len(img.shape) == 2:
|
23 |
+
img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
|
24 |
+
elif img.shape[2] == 4:
|
25 |
+
trans_mask = img[:, :, 3] == 0
|
26 |
+
img[trans_mask] = [255, 255, 255, 255]
|
27 |
+
img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
|
28 |
+
return img
|
29 |
+
|
30 |
+
|
31 |
+
def make_square(img, target_size):
|
32 |
+
old_size = img.shape[:2]
|
33 |
+
desired_size = max(old_size)
|
34 |
+
desired_size = max(desired_size, target_size)
|
35 |
+
|
36 |
+
delta_w = desired_size - old_size[1]
|
37 |
+
delta_h = desired_size - old_size[0]
|
38 |
+
top, bottom = delta_h // 2, delta_h - (delta_h // 2)
|
39 |
+
left, right = delta_w // 2, delta_w - (delta_w // 2)
|
40 |
+
|
41 |
+
color = [255, 255, 255]
|
42 |
+
new_im = cv2.copyMakeBorder(
|
43 |
+
img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color
|
44 |
+
)
|
45 |
+
return new_im
|
46 |
+
|
47 |
+
|
48 |
+
def smart_resize(img, size):
|
49 |
+
# Assumes the image has already gone through make_square
|
50 |
+
if img.shape[0] > size:
|
51 |
+
img = cv2.resize(img, (size, size), interpolation=cv2.INTER_AREA)
|
52 |
+
elif img.shape[0] < size:
|
53 |
+
img = cv2.resize(img, (size, size), interpolation=cv2.INTER_CUBIC)
|
54 |
+
return img
|
app.py
CHANGED
@@ -1,4 +1,8 @@
|
|
|
|
|
|
1 |
import argparse
|
|
|
|
|
2 |
import os
|
3 |
|
4 |
import gradio as gr
|
@@ -6,344 +10,275 @@ import huggingface_hub
|
|
6 |
import numpy as np
|
7 |
import onnxruntime as rt
|
8 |
import pandas as pd
|
9 |
-
|
|
|
|
|
10 |
|
11 |
-
|
12 |
-
DESCRIPTION = """
|
13 |
-
Demo for the WaifuDiffusion tagger models
|
14 |
|
15 |
-
|
16 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
|
18 |
-
|
19 |
|
20 |
-
|
21 |
-
|
22 |
-
CONV_MODEL_DSV3_REPO = "SmilingWolf/wd-convnext-tagger-v3"
|
23 |
-
VIT_MODEL_DSV3_REPO = "SmilingWolf/wd-vit-tagger-v3"
|
24 |
-
VIT_LARGE_MODEL_DSV3_REPO = "SmilingWolf/wd-vit-large-tagger-v3"
|
25 |
-
EVA02_LARGE_MODEL_DSV3_REPO = "SmilingWolf/wd-eva02-large-tagger-v3"
|
26 |
|
27 |
-
|
28 |
-
MOAT_MODEL_DSV2_REPO = "SmilingWolf/wd-v1-4-moat-tagger-v2"
|
29 |
-
SWIN_MODEL_DSV2_REPO = "SmilingWolf/wd-v1-4-swinv2-tagger-v2"
|
30 |
-
CONV_MODEL_DSV2_REPO = "SmilingWolf/wd-v1-4-convnext-tagger-v2"
|
31 |
-
CONV2_MODEL_DSV2_REPO = "SmilingWolf/wd-v1-4-convnextv2-tagger-v2"
|
32 |
-
VIT_MODEL_DSV2_REPO = "SmilingWolf/wd-v1-4-vit-tagger-v2"
|
33 |
|
34 |
-
|
35 |
-
|
36 |
-
SWINV2_MODEL_IS_DSV1_REPO = "deepghs/idolsankaku-swinv2-tagger-v1"
|
37 |
|
38 |
-
|
|
|
|
|
|
|
|
|
|
|
39 |
MODEL_FILENAME = "model.onnx"
|
40 |
LABEL_FILENAME = "selected_tags.csv"
|
41 |
|
42 |
-
# https://github.com/toriato/stable-diffusion-webui-wd14-tagger/blob/a9eacb1eff904552d3012babfa28b57e1d3e295c/tagger/ui.py#L368
|
43 |
-
kaomojis = [
|
44 |
-
"0_0",
|
45 |
-
"(o)_(o)",
|
46 |
-
"+_+",
|
47 |
-
"+_-",
|
48 |
-
"._.",
|
49 |
-
"<o>_<o>",
|
50 |
-
"<|>_<|>",
|
51 |
-
"=_=",
|
52 |
-
">_<",
|
53 |
-
"3_3",
|
54 |
-
"6_9",
|
55 |
-
">_o",
|
56 |
-
"@_@",
|
57 |
-
"^_^",
|
58 |
-
"o_o",
|
59 |
-
"u_u",
|
60 |
-
"x_x",
|
61 |
-
"|_|",
|
62 |
-
"||_||",
|
63 |
-
]
|
64 |
-
|
65 |
|
66 |
def parse_args() -> argparse.Namespace:
|
67 |
parser = argparse.ArgumentParser()
|
68 |
parser.add_argument("--score-slider-step", type=float, default=0.05)
|
69 |
parser.add_argument("--score-general-threshold", type=float, default=0.35)
|
70 |
parser.add_argument("--score-character-threshold", type=float, default=0.85)
|
|
|
71 |
return parser.parse_args()
|
72 |
|
73 |
|
74 |
-
def
|
75 |
-
|
76 |
-
|
77 |
-
lambda x: x.replace("_", " ") if x not in kaomojis else x
|
78 |
)
|
79 |
-
|
80 |
-
|
81 |
-
rating_indexes = list(np.where(dataframe["category"] == 9)[0])
|
82 |
-
general_indexes = list(np.where(dataframe["category"] == 0)[0])
|
83 |
-
character_indexes = list(np.where(dataframe["category"] == 4)[0])
|
84 |
-
return tag_names, rating_indexes, general_indexes, character_indexes
|
85 |
-
|
86 |
-
|
87 |
-
def mcut_threshold(probs):
|
88 |
-
"""
|
89 |
-
Maximum Cut Thresholding (MCut)
|
90 |
-
Largeron, C., Moulin, C., & Gery, M. (2012). MCut: A Thresholding Strategy
|
91 |
-
for Multi-label Classification. In 11th International Symposium, IDA 2012
|
92 |
-
(pp. 172-183).
|
93 |
-
"""
|
94 |
-
sorted_probs = probs[probs.argsort()[::-1]]
|
95 |
-
difs = sorted_probs[:-1] - sorted_probs[1:]
|
96 |
-
t = difs.argmax()
|
97 |
-
thresh = (sorted_probs[t] + sorted_probs[t + 1]) / 2
|
98 |
-
return thresh
|
99 |
-
|
100 |
-
|
101 |
-
class Predictor:
|
102 |
-
def __init__(self):
|
103 |
-
self.model_target_size = None
|
104 |
-
self.last_loaded_repo = None
|
105 |
-
|
106 |
-
def download_model(self, model_repo):
|
107 |
-
csv_path = huggingface_hub.hf_hub_download(
|
108 |
-
model_repo,
|
109 |
-
LABEL_FILENAME,
|
110 |
-
use_auth_token=HF_TOKEN,
|
111 |
-
)
|
112 |
-
model_path = huggingface_hub.hf_hub_download(
|
113 |
-
model_repo,
|
114 |
-
MODEL_FILENAME,
|
115 |
-
use_auth_token=HF_TOKEN,
|
116 |
-
)
|
117 |
-
return csv_path, model_path
|
118 |
-
|
119 |
-
def load_model(self, model_repo):
|
120 |
-
if model_repo == self.last_loaded_repo:
|
121 |
-
return
|
122 |
-
|
123 |
-
csv_path, model_path = self.download_model(model_repo)
|
124 |
-
|
125 |
-
tags_df = pd.read_csv(csv_path)
|
126 |
-
sep_tags = load_labels(tags_df)
|
127 |
-
|
128 |
-
self.tag_names = sep_tags[0]
|
129 |
-
self.rating_indexes = sep_tags[1]
|
130 |
-
self.general_indexes = sep_tags[2]
|
131 |
-
self.character_indexes = sep_tags[3]
|
132 |
-
|
133 |
-
model = rt.InferenceSession(model_path)
|
134 |
-
_, height, width, _ = model.get_inputs()[0].shape
|
135 |
-
self.model_target_size = height
|
136 |
-
|
137 |
-
self.last_loaded_repo = model_repo
|
138 |
-
self.model = model
|
139 |
-
|
140 |
-
def prepare_image(self, image):
|
141 |
-
target_size = self.model_target_size
|
142 |
-
|
143 |
-
canvas = Image.new("RGBA", image.size, (255, 255, 255))
|
144 |
-
canvas.alpha_composite(image)
|
145 |
-
image = canvas.convert("RGB")
|
146 |
|
147 |
-
# Pad image to square
|
148 |
-
image_shape = image.size
|
149 |
-
max_dim = max(image_shape)
|
150 |
-
pad_left = (max_dim - image_shape[0]) // 2
|
151 |
-
pad_top = (max_dim - image_shape[1]) // 2
|
152 |
|
153 |
-
|
154 |
-
|
155 |
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
|
|
|
|
|
|
|
|
162 |
|
163 |
-
|
164 |
-
|
165 |
|
166 |
-
# Convert PIL-native RGB to BGR
|
167 |
-
image_array = image_array[:, :, ::-1]
|
168 |
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
model_repo,
|
175 |
-
general_thresh,
|
176 |
-
general_mcut_enabled,
|
177 |
-
character_thresh,
|
178 |
-
character_mcut_enabled,
|
179 |
-
):
|
180 |
-
self.load_model(model_repo)
|
181 |
-
|
182 |
-
image = self.prepare_image(image)
|
183 |
-
|
184 |
-
input_name = self.model.get_inputs()[0].name
|
185 |
-
label_name = self.model.get_outputs()[0].name
|
186 |
-
preds = self.model.run([label_name], {input_name: image})[0]
|
187 |
-
|
188 |
-
labels = list(zip(self.tag_names, preds[0].astype(float)))
|
189 |
-
|
190 |
-
# First 4 labels are actually ratings: pick one with argmax
|
191 |
-
ratings_names = [labels[i] for i in self.rating_indexes]
|
192 |
-
rating = dict(ratings_names)
|
193 |
-
|
194 |
-
# Then we have general tags: pick any where prediction confidence > threshold
|
195 |
-
general_names = [labels[i] for i in self.general_indexes]
|
196 |
-
|
197 |
-
if general_mcut_enabled:
|
198 |
-
general_probs = np.array([x[1] for x in general_names])
|
199 |
-
general_thresh = mcut_threshold(general_probs)
|
200 |
-
|
201 |
-
general_res = [x for x in general_names if x[1] > general_thresh]
|
202 |
-
general_res = dict(general_res)
|
203 |
-
|
204 |
-
# Everything else is characters: pick any where prediction confidence > threshold
|
205 |
-
character_names = [labels[i] for i in self.character_indexes]
|
206 |
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
|
|
211 |
|
212 |
-
character_res = [x for x in character_names if x[1] > character_thresh]
|
213 |
-
character_res = dict(character_res)
|
214 |
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
223 |
)
|
224 |
|
225 |
-
|
|
|
|
|
|
|
|
|
226 |
|
227 |
|
228 |
def main():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
229 |
args = parse_args()
|
230 |
|
231 |
-
|
232 |
-
|
233 |
-
dropdown_list = [
|
234 |
-
SWINV2_MODEL_DSV3_REPO,
|
235 |
-
CONV_MODEL_DSV3_REPO,
|
236 |
-
VIT_MODEL_DSV3_REPO,
|
237 |
-
VIT_LARGE_MODEL_DSV3_REPO,
|
238 |
-
EVA02_LARGE_MODEL_DSV3_REPO,
|
239 |
-
# ---
|
240 |
-
MOAT_MODEL_DSV2_REPO,
|
241 |
-
SWIN_MODEL_DSV2_REPO,
|
242 |
-
CONV_MODEL_DSV2_REPO,
|
243 |
-
CONV2_MODEL_DSV2_REPO,
|
244 |
-
VIT_MODEL_DSV2_REPO,
|
245 |
-
# ---
|
246 |
-
SWINV2_MODEL_IS_DSV1_REPO,
|
247 |
-
EVA02_LARGE_MODEL_IS_DSV1_REPO,
|
248 |
-
]
|
249 |
-
|
250 |
-
with gr.Blocks(title=TITLE) as demo:
|
251 |
-
with gr.Column():
|
252 |
-
gr.Markdown(
|
253 |
-
value=f"<h1 style='text-align: center; margin-bottom: 1rem'>{TITLE}</h1>"
|
254 |
-
)
|
255 |
-
gr.Markdown(value=DESCRIPTION)
|
256 |
-
with gr.Row():
|
257 |
-
with gr.Column(variant="panel"):
|
258 |
-
image = gr.Image(type="pil", image_mode="RGBA", label="Input")
|
259 |
-
model_repo = gr.Dropdown(
|
260 |
-
dropdown_list,
|
261 |
-
value=SWINV2_MODEL_DSV3_REPO,
|
262 |
-
label="Model",
|
263 |
-
)
|
264 |
-
with gr.Row():
|
265 |
-
general_thresh = gr.Slider(
|
266 |
-
0,
|
267 |
-
1,
|
268 |
-
step=args.score_slider_step,
|
269 |
-
value=args.score_general_threshold,
|
270 |
-
label="General Tags Threshold",
|
271 |
-
scale=3,
|
272 |
-
)
|
273 |
-
general_mcut_enabled = gr.Checkbox(
|
274 |
-
value=False,
|
275 |
-
label="Use MCut threshold",
|
276 |
-
scale=1,
|
277 |
-
)
|
278 |
-
with gr.Row():
|
279 |
-
character_thresh = gr.Slider(
|
280 |
-
0,
|
281 |
-
1,
|
282 |
-
step=args.score_slider_step,
|
283 |
-
value=args.score_character_threshold,
|
284 |
-
label="Character Tags Threshold",
|
285 |
-
scale=3,
|
286 |
-
)
|
287 |
-
character_mcut_enabled = gr.Checkbox(
|
288 |
-
value=False,
|
289 |
-
label="Use MCut threshold",
|
290 |
-
scale=1,
|
291 |
-
)
|
292 |
-
with gr.Row():
|
293 |
-
clear = gr.ClearButton(
|
294 |
-
components=[
|
295 |
-
image,
|
296 |
-
model_repo,
|
297 |
-
general_thresh,
|
298 |
-
general_mcut_enabled,
|
299 |
-
character_thresh,
|
300 |
-
character_mcut_enabled,
|
301 |
-
],
|
302 |
-
variant="secondary",
|
303 |
-
size="lg",
|
304 |
-
)
|
305 |
-
submit = gr.Button(value="Submit", variant="primary", size="lg")
|
306 |
-
with gr.Column(variant="panel"):
|
307 |
-
sorted_general_strings = gr.Textbox(label="Output (string)")
|
308 |
-
rating = gr.Label(label="Rating")
|
309 |
-
character_res = gr.Label(label="Output (characters)")
|
310 |
-
general_res = gr.Label(label="Output (tags)")
|
311 |
-
clear.add(
|
312 |
-
[
|
313 |
-
sorted_general_strings,
|
314 |
-
rating,
|
315 |
-
character_res,
|
316 |
-
general_res,
|
317 |
-
]
|
318 |
-
)
|
319 |
-
|
320 |
-
submit.click(
|
321 |
-
predictor.predict,
|
322 |
-
inputs=[
|
323 |
-
image,
|
324 |
-
model_repo,
|
325 |
-
general_thresh,
|
326 |
-
general_mcut_enabled,
|
327 |
-
character_thresh,
|
328 |
-
character_mcut_enabled,
|
329 |
-
],
|
330 |
-
outputs=[sorted_general_strings, rating, character_res, general_res],
|
331 |
-
)
|
332 |
|
333 |
-
|
334 |
-
[["power.jpg", SWINV2_MODEL_DSV3_REPO, 0.35, False, 0.85, False]],
|
335 |
-
inputs=[
|
336 |
-
image,
|
337 |
-
model_repo,
|
338 |
-
general_thresh,
|
339 |
-
general_mcut_enabled,
|
340 |
-
character_thresh,
|
341 |
-
character_mcut_enabled,
|
342 |
-
],
|
343 |
-
)
|
344 |
|
345 |
-
|
346 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
347 |
|
348 |
|
349 |
if __name__ == "__main__":
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
import argparse
|
4 |
+
import functools
|
5 |
+
import html
|
6 |
import os
|
7 |
|
8 |
import gradio as gr
|
|
|
10 |
import numpy as np
|
11 |
import onnxruntime as rt
|
12 |
import pandas as pd
|
13 |
+
import piexif
|
14 |
+
import piexif.helper
|
15 |
+
import PIL.Image
|
16 |
|
17 |
+
from Utils import dbimutils
|
|
|
|
|
18 |
|
19 |
+
TITLE = "WaifuDiffusion v1.4 Tags"
|
20 |
+
DESCRIPTION = """
|
21 |
+
Demo for:
|
22 |
+
- [SmilingWolf/wd-v1-4-moat-tagger-v2](https://huggingface.co/SmilingWolf/wd-v1-4-moat-tagger-v2)
|
23 |
+
- [SmilingWolf/wd-v1-4-swinv2-tagger-v2](https://huggingface.co/SmilingWolf/wd-v1-4-convnext-tagger-v2)
|
24 |
+
- [SmilingWolf/wd-v1-4-convnext-tagger-v2](https://huggingface.co/SmilingWolf/wd-v1-4-convnext-tagger-v2)
|
25 |
+
- [SmilingWolf/wd-v1-4-convnextv2-tagger-v2](https://huggingface.co/SmilingWolf/wd-v1-4-convnextv2-tagger-v2)
|
26 |
+
- [SmilingWolf/wd-v1-4-vit-tagger-v2](https://huggingface.co/SmilingWolf/wd-v1-4-vit-tagger-v2)
|
27 |
|
28 |
+
Includes "ready to copy" prompt and a prompt analyzer.
|
29 |
|
30 |
+
Modified from [NoCrypt/DeepDanbooru_string](https://huggingface.co/spaces/NoCrypt/DeepDanbooru_string)
|
31 |
+
Modified from [hysts/DeepDanbooru](https://huggingface.co/spaces/hysts/DeepDanbooru)
|
|
|
|
|
|
|
|
|
32 |
|
33 |
+
PNG Info code forked from [AUTOMATIC1111/stable-diffusion-webui](https://github.com/AUTOMATIC1111/stable-diffusion-webui)
|
|
|
|
|
|
|
|
|
|
|
34 |
|
35 |
+
Example image by [ほし☆☆☆](https://www.pixiv.net/en/users/43565085)
|
36 |
+
"""
|
|
|
37 |
|
38 |
+
HF_TOKEN = os.environ["HF_TOKEN"]
|
39 |
+
MOAT_MODEL_REPO = "SmilingWolf/wd-v1-4-moat-tagger-v2"
|
40 |
+
SWIN_MODEL_REPO = "SmilingWolf/wd-v1-4-swinv2-tagger-v2"
|
41 |
+
CONV_MODEL_REPO = "SmilingWolf/wd-v1-4-convnext-tagger-v2"
|
42 |
+
CONV2_MODEL_REPO = "SmilingWolf/wd-v1-4-convnextv2-tagger-v2"
|
43 |
+
VIT_MODEL_REPO = "SmilingWolf/wd-v1-4-vit-tagger-v2"
|
44 |
MODEL_FILENAME = "model.onnx"
|
45 |
LABEL_FILENAME = "selected_tags.csv"
|
46 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
47 |
|
48 |
def parse_args() -> argparse.Namespace:
|
49 |
parser = argparse.ArgumentParser()
|
50 |
parser.add_argument("--score-slider-step", type=float, default=0.05)
|
51 |
parser.add_argument("--score-general-threshold", type=float, default=0.35)
|
52 |
parser.add_argument("--score-character-threshold", type=float, default=0.85)
|
53 |
+
parser.add_argument("--share", action="store_true")
|
54 |
return parser.parse_args()
|
55 |
|
56 |
|
57 |
+
def load_model(model_repo: str, model_filename: str) -> rt.InferenceSession:
|
58 |
+
path = huggingface_hub.hf_hub_download(
|
59 |
+
model_repo, model_filename, use_auth_token=HF_TOKEN
|
|
|
60 |
)
|
61 |
+
model = rt.InferenceSession(path)
|
62 |
+
return model
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
63 |
|
|
|
|
|
|
|
|
|
|
|
64 |
|
65 |
+
def change_model(model_name):
|
66 |
+
global loaded_models
|
67 |
|
68 |
+
if model_name == "MOAT":
|
69 |
+
model = load_model(MOAT_MODEL_REPO, MODEL_FILENAME)
|
70 |
+
elif model_name == "SwinV2":
|
71 |
+
model = load_model(SWIN_MODEL_REPO, MODEL_FILENAME)
|
72 |
+
elif model_name == "ConvNext":
|
73 |
+
model = load_model(CONV_MODEL_REPO, MODEL_FILENAME)
|
74 |
+
elif model_name == "ConvNextV2":
|
75 |
+
model = load_model(CONV2_MODEL_REPO, MODEL_FILENAME)
|
76 |
+
elif model_name == "ViT":
|
77 |
+
model = load_model(VIT_MODEL_REPO, MODEL_FILENAME)
|
78 |
|
79 |
+
loaded_models[model_name] = model
|
80 |
+
return loaded_models[model_name]
|
81 |
|
|
|
|
|
82 |
|
83 |
+
def load_labels() -> list[str]:
|
84 |
+
path = huggingface_hub.hf_hub_download(
|
85 |
+
MOAT_MODEL_REPO, LABEL_FILENAME, use_auth_token=HF_TOKEN
|
86 |
+
)
|
87 |
+
df = pd.read_csv(path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
88 |
|
89 |
+
tag_names = df["name"].tolist()
|
90 |
+
rating_indexes = list(np.where(df["category"] == 9)[0])
|
91 |
+
general_indexes = list(np.where(df["category"] == 0)[0])
|
92 |
+
character_indexes = list(np.where(df["category"] == 4)[0])
|
93 |
+
return tag_names, rating_indexes, general_indexes, character_indexes
|
94 |
|
|
|
|
|
95 |
|
96 |
+
def plaintext_to_html(text):
|
97 |
+
text = (
|
98 |
+
"<p>" + "<br>\n".join([f"{html.escape(x)}" for x in text.split("\n")]) + "</p>"
|
99 |
+
)
|
100 |
+
return text
|
101 |
+
|
102 |
+
|
103 |
+
def predict(
|
104 |
+
image: PIL.Image.Image,
|
105 |
+
model_name: str,
|
106 |
+
general_threshold: float,
|
107 |
+
character_threshold: float,
|
108 |
+
tag_names: list[str],
|
109 |
+
rating_indexes: list[np.int64],
|
110 |
+
general_indexes: list[np.int64],
|
111 |
+
character_indexes: list[np.int64],
|
112 |
+
):
|
113 |
+
global loaded_models
|
114 |
+
|
115 |
+
rawimage = image
|
116 |
+
|
117 |
+
model = loaded_models[model_name]
|
118 |
+
if model is None:
|
119 |
+
model = change_model(model_name)
|
120 |
+
|
121 |
+
_, height, width, _ = model.get_inputs()[0].shape
|
122 |
+
|
123 |
+
# Alpha to white
|
124 |
+
image = image.convert("RGBA")
|
125 |
+
new_image = PIL.Image.new("RGBA", image.size, "WHITE")
|
126 |
+
new_image.paste(image, mask=image)
|
127 |
+
image = new_image.convert("RGB")
|
128 |
+
image = np.asarray(image)
|
129 |
+
|
130 |
+
# PIL RGB to OpenCV BGR
|
131 |
+
image = image[:, :, ::-1]
|
132 |
+
|
133 |
+
image = dbimutils.make_square(image, height)
|
134 |
+
image = dbimutils.smart_resize(image, height)
|
135 |
+
image = image.astype(np.float32)
|
136 |
+
image = np.expand_dims(image, 0)
|
137 |
+
|
138 |
+
input_name = model.get_inputs()[0].name
|
139 |
+
label_name = model.get_outputs()[0].name
|
140 |
+
probs = model.run([label_name], {input_name: image})[0]
|
141 |
+
|
142 |
+
labels = list(zip(tag_names, probs[0].astype(float)))
|
143 |
+
|
144 |
+
# First 4 labels are actually ratings: pick one with argmax
|
145 |
+
ratings_names = [labels[i] for i in rating_indexes]
|
146 |
+
rating = dict(ratings_names)
|
147 |
+
|
148 |
+
# Then we have general tags: pick any where prediction confidence > threshold
|
149 |
+
general_names = [labels[i] for i in general_indexes]
|
150 |
+
general_res = [x for x in general_names if x[1] > general_threshold]
|
151 |
+
general_res = dict(general_res)
|
152 |
+
|
153 |
+
# Everything else is characters: pick any where prediction confidence > threshold
|
154 |
+
character_names = [labels[i] for i in character_indexes]
|
155 |
+
character_res = [x for x in character_names if x[1] > character_threshold]
|
156 |
+
character_res = dict(character_res)
|
157 |
+
|
158 |
+
b = dict(sorted(general_res.items(), key=lambda item: item[1], reverse=True))
|
159 |
+
a = (
|
160 |
+
", ".join(list(b.keys()))
|
161 |
+
.replace("_", " ")
|
162 |
+
.replace("(", "\(")
|
163 |
+
.replace(")", "\)")
|
164 |
+
)
|
165 |
+
c = ", ".join(list(b.keys()))
|
166 |
+
|
167 |
+
items = rawimage.info
|
168 |
+
geninfo = ""
|
169 |
+
|
170 |
+
if "exif" in rawimage.info:
|
171 |
+
exif = piexif.load(rawimage.info["exif"])
|
172 |
+
exif_comment = (exif or {}).get("Exif", {}).get(piexif.ExifIFD.UserComment, b"")
|
173 |
+
try:
|
174 |
+
exif_comment = piexif.helper.UserComment.load(exif_comment)
|
175 |
+
except ValueError:
|
176 |
+
exif_comment = exif_comment.decode("utf8", errors="ignore")
|
177 |
+
|
178 |
+
items["exif comment"] = exif_comment
|
179 |
+
geninfo = exif_comment
|
180 |
+
|
181 |
+
for field in [
|
182 |
+
"jfif",
|
183 |
+
"jfif_version",
|
184 |
+
"jfif_unit",
|
185 |
+
"jfif_density",
|
186 |
+
"dpi",
|
187 |
+
"exif",
|
188 |
+
"loop",
|
189 |
+
"background",
|
190 |
+
"timestamp",
|
191 |
+
"duration",
|
192 |
+
]:
|
193 |
+
items.pop(field, None)
|
194 |
+
|
195 |
+
geninfo = items.get("parameters", geninfo)
|
196 |
+
|
197 |
+
info = f"""
|
198 |
+
<p><h4>PNG Info</h4></p>
|
199 |
+
"""
|
200 |
+
for key, text in items.items():
|
201 |
+
info += (
|
202 |
+
f"""
|
203 |
+
<div>
|
204 |
+
<p><b>{plaintext_to_html(str(key))}</b></p>
|
205 |
+
<p>{plaintext_to_html(str(text))}</p>
|
206 |
+
</div>
|
207 |
+
""".strip()
|
208 |
+
+ "\n"
|
209 |
)
|
210 |
|
211 |
+
if len(info) == 0:
|
212 |
+
message = "Nothing found in the image."
|
213 |
+
info = f"<div><p>{message}<p></div>"
|
214 |
+
|
215 |
+
return (a, c, rating, character_res, general_res, info)
|
216 |
|
217 |
|
218 |
def main():
|
219 |
+
global loaded_models
|
220 |
+
loaded_models = {
|
221 |
+
"MOAT": None,
|
222 |
+
"SwinV2": None,
|
223 |
+
"ConvNext": None,
|
224 |
+
"ConvNextV2": None,
|
225 |
+
"ViT": None,
|
226 |
+
}
|
227 |
+
|
228 |
args = parse_args()
|
229 |
|
230 |
+
change_model("MOAT")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
231 |
|
232 |
+
tag_names, rating_indexes, general_indexes, character_indexes = load_labels()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
233 |
|
234 |
+
func = functools.partial(
|
235 |
+
predict,
|
236 |
+
tag_names=tag_names,
|
237 |
+
rating_indexes=rating_indexes,
|
238 |
+
general_indexes=general_indexes,
|
239 |
+
character_indexes=character_indexes,
|
240 |
+
)
|
241 |
+
|
242 |
+
gr.Interface(
|
243 |
+
fn=func,
|
244 |
+
inputs=[
|
245 |
+
gr.Image(type="pil", label="Input"),
|
246 |
+
gr.Radio(
|
247 |
+
["MOAT", "SwinV2", "ConvNext", "ConvNextV2", "ViT"],
|
248 |
+
value="MOAT",
|
249 |
+
label="Model",
|
250 |
+
),
|
251 |
+
gr.Slider(
|
252 |
+
0,
|
253 |
+
1,
|
254 |
+
step=args.score_slider_step,
|
255 |
+
value=args.score_general_threshold,
|
256 |
+
label="General Tags Threshold",
|
257 |
+
),
|
258 |
+
gr.Slider(
|
259 |
+
0,
|
260 |
+
1,
|
261 |
+
step=args.score_slider_step,
|
262 |
+
value=args.score_character_threshold,
|
263 |
+
label="Character Tags Threshold",
|
264 |
+
),
|
265 |
+
],
|
266 |
+
outputs=[
|
267 |
+
gr.Textbox(label="Output (string)"),
|
268 |
+
gr.Textbox(label="Output (raw string)"),
|
269 |
+
gr.Label(label="Rating"),
|
270 |
+
gr.Label(label="Output (characters)"),
|
271 |
+
gr.Label(label="Output (tags)"),
|
272 |
+
gr.HTML(),
|
273 |
+
],
|
274 |
+
examples=[["power.jpg", "MOAT", 0.35, 0.85]],
|
275 |
+
title=TITLE,
|
276 |
+
description=DESCRIPTION,
|
277 |
+
allow_flagging="never",
|
278 |
+
).launch(
|
279 |
+
enable_queue=True,
|
280 |
+
share=args.share,
|
281 |
+
)
|
282 |
|
283 |
|
284 |
if __name__ == "__main__":
|
requirements.txt
CHANGED
@@ -1,3 +1,5 @@
|
|
1 |
pillow>=9.0.0
|
|
|
2 |
onnxruntime>=1.12.0
|
|
|
3 |
huggingface-hub
|
|
|
1 |
pillow>=9.0.0
|
2 |
+
piexif>=1.1.3
|
3 |
onnxruntime>=1.12.0
|
4 |
+
opencv-python
|
5 |
huggingface-hub
|