faisalhr1997 SmilingWolf commited on
Commit
907dd29
·
0 Parent(s):

Duplicate from SmilingWolf/wd-v1-4-tags

Browse files

Co-authored-by: Smiling Wolf <[email protected]>

Files changed (7) hide show
  1. .gitattributes +27 -0
  2. .gitignore +1 -0
  3. README.md +39 -0
  4. Utils/dbimutils.py +54 -0
  5. app.py +214 -0
  6. power.jpg +0 -0
  7. requirements.txt +4 -0
.gitattributes ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bin.* filter=lfs diff=lfs merge=lfs -text
5
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.model filter=lfs diff=lfs merge=lfs -text
12
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
13
+ *.onnx filter=lfs diff=lfs merge=lfs -text
14
+ *.ot filter=lfs diff=lfs merge=lfs -text
15
+ *.parquet filter=lfs diff=lfs merge=lfs -text
16
+ *.pb filter=lfs diff=lfs merge=lfs -text
17
+ *.pt filter=lfs diff=lfs merge=lfs -text
18
+ *.pth filter=lfs diff=lfs merge=lfs -text
19
+ *.rar filter=lfs diff=lfs merge=lfs -text
20
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
21
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
22
+ *.tflite filter=lfs diff=lfs merge=lfs -text
23
+ *.tgz filter=lfs diff=lfs merge=lfs -text
24
+ *.xz filter=lfs diff=lfs merge=lfs -text
25
+ *.zip filter=lfs diff=lfs merge=lfs -text
26
+ *.zstandard filter=lfs diff=lfs merge=lfs -text
27
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ images
README.md ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: WaifuDiffusion v1.4 Tags
3
+ emoji: 💬
4
+ colorFrom: blue
5
+ colorTo: red
6
+ sdk: gradio
7
+ sdk_version: 3.13
8
+ app_file: app.py
9
+ pinned: false
10
+ duplicated_from: SmilingWolf/wd-v1-4-tags
11
+ ---
12
+
13
+ # Configuration
14
+
15
+ `title`: _string_
16
+ Display title for the Space
17
+
18
+ `emoji`: _string_
19
+ Space emoji (emoji-only character allowed)
20
+
21
+ `colorFrom`: _string_
22
+ Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray)
23
+
24
+ `colorTo`: _string_
25
+ Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray)
26
+
27
+ `sdk`: _string_
28
+ Can be either `gradio`, `streamlit`, or `static`
29
+
30
+ `sdk_version` : _string_
31
+ Only applicable for `streamlit` SDK.
32
+ See [doc](https://hf.co/docs/hub/spaces) for more info on supported versions.
33
+
34
+ `app_file`: _string_
35
+ Path to your main application file (which contains either `gradio` or `streamlit` Python code, or `static` html code).
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 ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import functools
7
+ import html
8
+ import os
9
+
10
+ import gradio as gr
11
+ import huggingface_hub
12
+ import numpy as np
13
+ import onnxruntime as rt
14
+ import pandas as pd
15
+ import piexif
16
+ import piexif.helper
17
+ import PIL.Image
18
+
19
+ from Utils import dbimutils
20
+
21
+ TITLE = "WaifuDiffusion v1.4 Tags"
22
+ DESCRIPTION = """
23
+ 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.
24
+
25
+ Modified from [NoCrypt/DeepDanbooru_string](https://huggingface.co/spaces/NoCrypt/DeepDanbooru_string)
26
+ Modified from [hysts/DeepDanbooru](https://huggingface.co/spaces/hysts/DeepDanbooru)
27
+
28
+ PNG Info code forked from [AUTOMATIC1111/stable-diffusion-webui](https://github.com/AUTOMATIC1111/stable-diffusion-webui)
29
+
30
+ Example image by [ほし☆☆☆](https://www.pixiv.net/en/users/43565085)
31
+ """
32
+
33
+ HF_TOKEN = os.environ["HF_TOKEN"]
34
+ VIT_MODEL_REPO = "SmilingWolf/wd-v1-4-vit-tagger"
35
+ CONV_MODEL_REPO = "SmilingWolf/wd-v1-4-convnext-tagger"
36
+ MODEL_FILENAME = "model.onnx"
37
+ LABEL_FILENAME = "selected_tags.csv"
38
+
39
+
40
+ def parse_args() -> argparse.Namespace:
41
+ parser = argparse.ArgumentParser()
42
+ parser.add_argument("--score-slider-step", type=float, default=0.05)
43
+ parser.add_argument("--score-threshold", type=float, default=0.35)
44
+ parser.add_argument("--share", action="store_true")
45
+ return parser.parse_args()
46
+
47
+
48
+ def load_model(model_repo: str, model_filename: str) -> rt.InferenceSession:
49
+ path = huggingface_hub.hf_hub_download(
50
+ model_repo, model_filename, use_auth_token=HF_TOKEN
51
+ )
52
+ model = rt.InferenceSession(path)
53
+ return model
54
+
55
+
56
+ def load_labels() -> list[str]:
57
+ path = huggingface_hub.hf_hub_download(
58
+ VIT_MODEL_REPO, LABEL_FILENAME, use_auth_token=HF_TOKEN
59
+ )
60
+ df = pd.read_csv(path)["name"].tolist()
61
+ return df
62
+
63
+
64
+ def plaintext_to_html(text):
65
+ text = (
66
+ "<p>" + "<br>\n".join([f"{html.escape(x)}" for x in text.split("\n")]) + "</p>"
67
+ )
68
+ return text
69
+
70
+
71
+ def predict(
72
+ image: PIL.Image.Image,
73
+ selected_model: str,
74
+ score_threshold: float,
75
+ models: dict,
76
+ labels: list[str],
77
+ ):
78
+ rawimage = image
79
+
80
+ model = models[selected_model]
81
+ _, height, width, _ = model.get_inputs()[0].shape
82
+
83
+ # Alpha to white
84
+ image = image.convert("RGBA")
85
+ new_image = PIL.Image.new("RGBA", image.size, "WHITE")
86
+ new_image.paste(image, mask=image)
87
+ image = new_image.convert("RGB")
88
+ image = np.asarray(image)
89
+
90
+ # PIL RGB to OpenCV BGR
91
+ image = image[:, :, ::-1]
92
+
93
+ image = dbimutils.make_square(image, height)
94
+ image = dbimutils.smart_resize(image, height)
95
+ image = image.astype(np.float32)
96
+ image = np.expand_dims(image, 0)
97
+
98
+ input_name = model.get_inputs()[0].name
99
+ label_name = model.get_outputs()[0].name
100
+ probs = model.run([label_name], {input_name: image})[0]
101
+
102
+ labels = list(zip(labels, probs[0].astype(float)))
103
+
104
+ # First 4 labels are actually ratings: pick one with argmax
105
+ ratings_names = labels[:4]
106
+ rating = dict(ratings_names)
107
+
108
+ # Everything else is tags: pick any where prediction confidence > threshold
109
+ tags_names = labels[4:]
110
+ res = [x for x in tags_names if x[1] > score_threshold]
111
+ res = dict(res)
112
+
113
+ b = dict(sorted(res.items(), key=lambda item: item[1], reverse=True))
114
+ a = (
115
+ ", ".join(list(b.keys()))
116
+ .replace("_", " ")
117
+ .replace("(", "\(")
118
+ .replace(")", "\)")
119
+ )
120
+ c = ", ".join(list(b.keys()))
121
+
122
+ items = rawimage.info
123
+ geninfo = ""
124
+
125
+ if "exif" in rawimage.info:
126
+ exif = piexif.load(rawimage.info["exif"])
127
+ exif_comment = (exif or {}).get("Exif", {}).get(piexif.ExifIFD.UserComment, b"")
128
+ try:
129
+ exif_comment = piexif.helper.UserComment.load(exif_comment)
130
+ except ValueError:
131
+ exif_comment = exif_comment.decode("utf8", errors="ignore")
132
+
133
+ items["exif comment"] = exif_comment
134
+ geninfo = exif_comment
135
+
136
+ for field in [
137
+ "jfif",
138
+ "jfif_version",
139
+ "jfif_unit",
140
+ "jfif_density",
141
+ "dpi",
142
+ "exif",
143
+ "loop",
144
+ "background",
145
+ "timestamp",
146
+ "duration",
147
+ ]:
148
+ items.pop(field, None)
149
+
150
+ geninfo = items.get("parameters", geninfo)
151
+
152
+ info = f"""
153
+ <p><h4>PNG Info</h4></p>
154
+ """
155
+ for key, text in items.items():
156
+ info += (
157
+ f"""
158
+ <div>
159
+ <p><b>{plaintext_to_html(str(key))}</b></p>
160
+ <p>{plaintext_to_html(str(text))}</p>
161
+ </div>
162
+ """.strip()
163
+ + "\n"
164
+ )
165
+
166
+ if len(info) == 0:
167
+ message = "Nothing found in the image."
168
+ info = f"<div><p>{message}<p></div>"
169
+
170
+ return (a, c, rating, res, info)
171
+
172
+
173
+ def main():
174
+ args = parse_args()
175
+ vit_model = load_model(VIT_MODEL_REPO, MODEL_FILENAME)
176
+ conv_model = load_model(CONV_MODEL_REPO, MODEL_FILENAME)
177
+ labels = load_labels()
178
+
179
+ models = {"ViT": vit_model, "ConvNext": conv_model}
180
+
181
+ func = functools.partial(predict, models=models, labels=labels)
182
+
183
+ gr.Interface(
184
+ fn=func,
185
+ inputs=[
186
+ gr.Image(type="pil", label="Input"),
187
+ gr.Radio(["ViT", "ConvNext"], value="ViT", label="Model"),
188
+ gr.Slider(
189
+ 0,
190
+ 1,
191
+ step=args.score_slider_step,
192
+ value=args.score_threshold,
193
+ label="Score Threshold",
194
+ ),
195
+ ],
196
+ outputs=[
197
+ gr.Textbox(label="Output (string)"),
198
+ gr.Textbox(label="Output (raw string)"),
199
+ gr.Label(label="Rating"),
200
+ gr.Label(label="Output (label)"),
201
+ gr.HTML(),
202
+ ],
203
+ examples=[["power.jpg", "ViT", 0.5]],
204
+ title=TITLE,
205
+ description=DESCRIPTION,
206
+ allow_flagging="never",
207
+ ).launch(
208
+ enable_queue=True,
209
+ share=args.share,
210
+ )
211
+
212
+
213
+ if __name__ == "__main__":
214
+ main()
power.jpg ADDED
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ pillow>=9.0.0
2
+ piexif>=1.1.3
3
+ onnxruntime>=1.12.0
4
+ opencv-python