SmilingWolf
commited on
Commit
•
ff17aaa
1
Parent(s):
b40c0ad
Danbooru2022 Explorer v1.0
Browse files- .gitattributes +1 -0
- Utils/dbimutils.py +54 -0
- app.py +206 -0
- index/cosine_ids.npy +3 -0
- index/cosine_infos.json +1 -0
- index/cosine_knn.index +3 -0
.gitattributes
CHANGED
@@ -32,3 +32,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
32 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
33 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
34 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
32 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
33 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
34 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
35 |
+
*.index filter=lfs diff=lfs merge=lfs -text
|
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,206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import functools
|
3 |
+
import json
|
4 |
+
from pathlib import Path
|
5 |
+
|
6 |
+
import faiss
|
7 |
+
import gradio as gr
|
8 |
+
import numpy as np
|
9 |
+
import PIL.Image
|
10 |
+
import requests
|
11 |
+
import tensorflow as tf
|
12 |
+
from huggingface_hub import hf_hub_download
|
13 |
+
|
14 |
+
from Utils import dbimutils
|
15 |
+
|
16 |
+
TITLE = "## Danbooru Explorer"
|
17 |
+
DESCRIPTION = """
|
18 |
+
Image similarity-based retrieval tool using:
|
19 |
+
- [SmilingWolf/wd-v1-4-convnext-tagger-v2](https://huggingface.co/SmilingWolf/wd-v1-4-convnext-tagger-v2) as feature extractor
|
20 |
+
- [Faiss](https://github.com/facebookresearch/faiss) and [autofaiss](https://github.com/criteo/autofaiss) for indexing
|
21 |
+
"""
|
22 |
+
|
23 |
+
CONV_MODEL_REPO = "SmilingWolf/wd-v1-4-convnext-tagger-v2"
|
24 |
+
CONV_MODEL_REVISION = "v2.0"
|
25 |
+
CONV_FEXT_LAYER = "predictions_norm"
|
26 |
+
|
27 |
+
|
28 |
+
def parse_args() -> argparse.Namespace:
|
29 |
+
parser = argparse.ArgumentParser()
|
30 |
+
parser.add_argument("--share", action="store_true")
|
31 |
+
return parser.parse_args()
|
32 |
+
|
33 |
+
|
34 |
+
def download_model(model_repo, model_revision):
|
35 |
+
model_files = [
|
36 |
+
{"filename": "saved_model.pb", "subfolder": ""},
|
37 |
+
{"filename": "keras_metadata.pb", "subfolder": ""},
|
38 |
+
{"filename": "variables.index", "subfolder": "variables"},
|
39 |
+
{"filename": "variables.data-00000-of-00001", "subfolder": "variables"},
|
40 |
+
]
|
41 |
+
|
42 |
+
model_file_paths = []
|
43 |
+
for elem in model_files:
|
44 |
+
model_file_paths.append(
|
45 |
+
Path(hf_hub_download(model_repo, revision=model_revision, **elem))
|
46 |
+
)
|
47 |
+
|
48 |
+
model_path = model_file_paths[0].parents[0]
|
49 |
+
return model_path
|
50 |
+
|
51 |
+
|
52 |
+
def load_model(model_repo, model_revision, feature_extraction_layer):
|
53 |
+
model_path = download_model(model_repo, model_revision)
|
54 |
+
full_model = tf.keras.models.load_model(model_path)
|
55 |
+
model = tf.keras.models.Model(
|
56 |
+
full_model.inputs, full_model.get_layer(feature_extraction_layer).output
|
57 |
+
)
|
58 |
+
return model
|
59 |
+
|
60 |
+
|
61 |
+
def danbooru_id_to_url(image_id, selected_ratings, api_username="", api_key=""):
|
62 |
+
headers = {"User-Agent": "image_similarity_tool"}
|
63 |
+
ratings_to_letters = {
|
64 |
+
"General": "g",
|
65 |
+
"Sensitive": "s",
|
66 |
+
"Questionable": "q",
|
67 |
+
"Explicit": "e",
|
68 |
+
}
|
69 |
+
|
70 |
+
acceptable_ratings = [ratings_to_letters[x] for x in selected_ratings]
|
71 |
+
|
72 |
+
image_url = f"https://danbooru.donmai.us/posts/{image_id}.json"
|
73 |
+
if api_username != "" and api_key != "":
|
74 |
+
image_url = f"{image_url}?api_key={api_key}&login={api_username}"
|
75 |
+
|
76 |
+
r = requests.get(image_url, headers=headers)
|
77 |
+
if r.status_code != 200:
|
78 |
+
return None
|
79 |
+
|
80 |
+
content = json.loads(r.text)
|
81 |
+
image_url = content["large_file_url"] if "large_file_url" in content else None
|
82 |
+
image_url = image_url if content["rating"] in acceptable_ratings else None
|
83 |
+
return image_url
|
84 |
+
|
85 |
+
|
86 |
+
class SimilaritySearcher:
|
87 |
+
def __init__(self, model, images_ids):
|
88 |
+
self.knn_index = None
|
89 |
+
self.knn_metric = None
|
90 |
+
|
91 |
+
self.model = model
|
92 |
+
self.images_ids = images_ids
|
93 |
+
|
94 |
+
def change_index(self, knn_metric):
|
95 |
+
if knn_metric == self.knn_metric:
|
96 |
+
return
|
97 |
+
|
98 |
+
if knn_metric == "ip":
|
99 |
+
self.knn_index = faiss.read_index("index/ip_knn.index")
|
100 |
+
config = json.loads(open("index/ip_infos.json").read())["index_param"]
|
101 |
+
elif knn_metric == "cosine":
|
102 |
+
self.knn_index = faiss.read_index("index/cosine_knn.index")
|
103 |
+
config = json.loads(open("index/cosine_infos.json").read())["index_param"]
|
104 |
+
|
105 |
+
faiss.ParameterSpace().set_index_parameters(self.knn_index, config)
|
106 |
+
self.knn_metric = knn_metric
|
107 |
+
|
108 |
+
def predict(
|
109 |
+
self, image, selected_ratings, knn_metric, api_username, api_key, n_neighbours
|
110 |
+
):
|
111 |
+
_, height, width, _ = self.model.inputs[0].shape
|
112 |
+
|
113 |
+
self.change_index(knn_metric)
|
114 |
+
|
115 |
+
# Alpha to white
|
116 |
+
image = image.convert("RGBA")
|
117 |
+
new_image = PIL.Image.new("RGBA", image.size, "WHITE")
|
118 |
+
new_image.paste(image, mask=image)
|
119 |
+
image = new_image.convert("RGB")
|
120 |
+
image = np.asarray(image)
|
121 |
+
|
122 |
+
# PIL RGB to OpenCV BGR
|
123 |
+
image = image[:, :, ::-1]
|
124 |
+
|
125 |
+
image = dbimutils.make_square(image, height)
|
126 |
+
image = dbimutils.smart_resize(image, height)
|
127 |
+
image = image.astype(np.float32)
|
128 |
+
image = np.expand_dims(image, 0)
|
129 |
+
target = self.model(image).numpy()
|
130 |
+
|
131 |
+
if self.knn_metric == "cosine":
|
132 |
+
faiss.normalize_L2(target)
|
133 |
+
|
134 |
+
dists, indexes = self.knn_index.search(target, k=n_neighbours)
|
135 |
+
neighbours_ids = self.images_ids[indexes][0]
|
136 |
+
neighbours_ids = [int(x) for x in neighbours_ids]
|
137 |
+
|
138 |
+
captions = []
|
139 |
+
for image_id, dist in zip(neighbours_ids, dists[0]):
|
140 |
+
captions.append(f"{image_id}/{dist:.2f}")
|
141 |
+
|
142 |
+
image_urls = []
|
143 |
+
for image_id in neighbours_ids:
|
144 |
+
current_url = danbooru_id_to_url(
|
145 |
+
image_id, selected_ratings, api_username, api_key
|
146 |
+
)
|
147 |
+
if current_url is not None:
|
148 |
+
image_urls.append(current_url)
|
149 |
+
return list(zip(image_urls, captions))
|
150 |
+
|
151 |
+
|
152 |
+
def main():
|
153 |
+
args = parse_args()
|
154 |
+
model = load_model(CONV_MODEL_REPO, CONV_MODEL_REVISION, CONV_FEXT_LAYER)
|
155 |
+
images_ids = np.load("index/cosine_ids.npy")
|
156 |
+
|
157 |
+
searcher = SimilaritySearcher(model=model, images_ids=images_ids)
|
158 |
+
|
159 |
+
with gr.Blocks() as demo:
|
160 |
+
gr.Markdown(TITLE)
|
161 |
+
gr.Markdown(DESCRIPTION)
|
162 |
+
|
163 |
+
with gr.Row():
|
164 |
+
input = gr.Image(type="pil", label="Input")
|
165 |
+
with gr.Column():
|
166 |
+
with gr.Row():
|
167 |
+
api_username = gr.Textbox(label="Danbooru API Username")
|
168 |
+
api_key = gr.Textbox(label="Danbooru API Key")
|
169 |
+
with gr.Row():
|
170 |
+
selected_ratings = gr.CheckboxGroup(
|
171 |
+
choices=["General", "Sensitive", "Questionable", "Explicit"],
|
172 |
+
value=["General", "Sensitive"],
|
173 |
+
label="Ratings",
|
174 |
+
)
|
175 |
+
selected_metric = gr.Radio(
|
176 |
+
choices=["cosine"],
|
177 |
+
value="cosine",
|
178 |
+
label="Metric selection",
|
179 |
+
visible=False,
|
180 |
+
)
|
181 |
+
n_neighbours = gr.Slider(
|
182 |
+
minimum=1, maximum=20, value=5, step=1, label="# of images"
|
183 |
+
)
|
184 |
+
find_btn = gr.Button("Find similar images")
|
185 |
+
similar_images = gr.Gallery(label="Similar images")
|
186 |
+
|
187 |
+
similar_images.style(grid=5)
|
188 |
+
find_btn.click(
|
189 |
+
fn=searcher.predict,
|
190 |
+
inputs=[
|
191 |
+
input,
|
192 |
+
selected_ratings,
|
193 |
+
selected_metric,
|
194 |
+
api_username,
|
195 |
+
api_key,
|
196 |
+
n_neighbours,
|
197 |
+
],
|
198 |
+
outputs=[similar_images],
|
199 |
+
)
|
200 |
+
|
201 |
+
demo.queue()
|
202 |
+
demo.launch(share=args.share)
|
203 |
+
|
204 |
+
|
205 |
+
if __name__ == "__main__":
|
206 |
+
main()
|
index/cosine_ids.npy
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:df724519c8c1981e49d80e2430261deb4fb6edf6d9c04e134427879710747394
|
3 |
+
size 21830676
|
index/cosine_infos.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"index_key": "OPQ256_1280,IVF16384_HNSW32,PQ256x8", "index_param": "nprobe=16,efSearch=32,ht=2048", "index_path": "/home/SmilingWolf/eval/index/ConvNextBV1_01_14_2023_08h37m46s_cosine_knn.index", "size in bytes": 1535843672, "avg_search_speed_ms": 10.164478485783887, "99p_search_speed_ms": 12.419190758373587, "reconstruction error %": 22.007358074188232, "nb vectors": 5457637, "vectors dimension": 1024, "compression ratio": 14.555180035276402}
|
index/cosine_knn.index
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:3a718ab8370df8b9d84002c55f945ef241e4cc3450d306c2ecd97661f51022ad
|
3 |
+
size 1535843672
|