SmilingWolf commited on
Commit
03d2c4c
1 Parent(s): 8a0e72f

Update index to danbooru dataset v3

Browse files

Also change model to wd-swinv2-tagger-v3

Utils/dbimutils.py DELETED
@@ -1,54 +0,0 @@
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,32 +1,22 @@
1
  import argparse
2
- import functools
3
  import json
4
- import os
5
- from pathlib import Path
6
 
7
  import faiss
8
  import gradio as gr
9
  import numpy as np
10
- import PIL.Image
11
  import requests
12
- import tensorflow as tf
13
- from huggingface_hub import hf_hub_download
14
-
15
- from Utils import dbimutils
16
 
17
  TITLE = "## Danbooru Explorer"
18
  DESCRIPTION = """
19
  Image similarity-based retrieval tool using:
20
- - [SmilingWolf/wd-v1-4-convnext-tagger-v2](https://huggingface.co/SmilingWolf/wd-v1-4-convnext-tagger-v2) as feature extractor
 
21
  - [Faiss](https://github.com/facebookresearch/faiss) and [autofaiss](https://github.com/criteo/autofaiss) for indexing
22
 
23
  Also, check out [SmilingWolf/danbooru2022_embeddings_playground](https://huggingface.co/spaces/SmilingWolf/danbooru2022_embeddings_playground) for a similar space with experimental support for text input combined with image input.
24
  """
25
 
26
- CONV_MODEL_REPO = "SmilingWolf/wd-v1-4-convnext-tagger-v2"
27
- CONV_MODEL_REVISION = "v2.0"
28
- CONV_FEXT_LAYER = "predictions_norm"
29
-
30
 
31
  def parse_args() -> argparse.Namespace:
32
  parser = argparse.ArgumentParser()
@@ -34,39 +24,6 @@ def parse_args() -> argparse.Namespace:
34
  return parser.parse_args()
35
 
36
 
37
- def download_model(model_repo, model_revision):
38
- model_files = [
39
- {"filename": "saved_model.pb", "subfolder": ""},
40
- {"filename": "keras_metadata.pb", "subfolder": ""},
41
- {"filename": "variables.index", "subfolder": "variables"},
42
- {"filename": "variables.data-00000-of-00001", "subfolder": "variables"},
43
- ]
44
-
45
- model_file_paths = []
46
- for elem in model_files:
47
- model_file_paths.append(
48
- Path(
49
- hf_hub_download(
50
- model_repo,
51
- revision=model_revision,
52
- **elem,
53
- )
54
- )
55
- )
56
-
57
- model_path = model_file_paths[0].parents[0]
58
- return model_path
59
-
60
-
61
- def load_model(model_repo, model_revision, feature_extraction_layer):
62
- model_path = download_model(model_repo, model_revision)
63
- full_model = tf.keras.models.load_model(model_path)
64
- model = tf.keras.models.Model(
65
- full_model.inputs, full_model.get_layer(feature_extraction_layer).output
66
- )
67
- return model
68
-
69
-
70
  def danbooru_id_to_url(image_id, selected_ratings, api_username="", api_key=""):
71
  headers = {"User-Agent": "image_similarity_tool"}
72
  ratings_to_letters = {
@@ -93,54 +50,30 @@ def danbooru_id_to_url(image_id, selected_ratings, api_username="", api_key=""):
93
 
94
 
95
  class SimilaritySearcher:
96
- def __init__(self, model, images_ids):
97
- self.knn_index = None
98
- self.knn_metric = None
99
-
100
- self.model = model
101
- self.images_ids = images_ids
102
-
103
- def change_index(self, knn_metric):
104
- if knn_metric == self.knn_metric:
105
- return
106
-
107
- if knn_metric == "ip":
108
- self.knn_index = faiss.read_index("index/ip_knn.index")
109
- config = json.loads(open("index/ip_infos.json").read())["index_param"]
110
- elif knn_metric == "cosine":
111
- self.knn_index = faiss.read_index("index/cosine_knn.index")
112
- config = json.loads(open("index/cosine_infos.json").read())["index_param"]
113
 
 
114
  faiss.ParameterSpace().set_index_parameters(self.knn_index, config)
115
- self.knn_metric = knn_metric
116
 
117
  def predict(
118
- self, image, selected_ratings, knn_metric, api_username, api_key, n_neighbours
 
 
 
 
 
119
  ):
120
- _, height, width, _ = self.model.inputs[0].shape
121
-
122
- self.change_index(knn_metric)
123
-
124
- # Alpha to white
125
- image = image.convert("RGBA")
126
- new_image = PIL.Image.new("RGBA", image.size, "WHITE")
127
- new_image.paste(image, mask=image)
128
- image = new_image.convert("RGB")
129
- image = np.asarray(image)
130
-
131
- # PIL RGB to OpenCV BGR
132
- image = image[:, :, ::-1]
133
-
134
- image = dbimutils.make_square(image, height)
135
- image = dbimutils.smart_resize(image, height)
136
- image = image.astype(np.float32)
137
- image = np.expand_dims(image, 0)
138
- target = self.model(image).numpy()
139
-
140
- if self.knn_metric == "cosine":
141
- faiss.normalize_L2(target)
142
 
143
- dists, indexes = self.knn_index.search(target, k=n_neighbours)
144
  neighbours_ids = self.images_ids[indexes][0]
145
  neighbours_ids = [int(x) for x in neighbours_ids]
146
 
@@ -148,7 +81,10 @@ class SimilaritySearcher:
148
  image_urls = []
149
  for image_id, dist in zip(neighbours_ids, dists[0]):
150
  current_url = danbooru_id_to_url(
151
- image_id, selected_ratings, api_username, api_key
 
 
 
152
  )
153
  if current_url is not None:
154
  image_urls.append(current_url)
@@ -158,17 +94,14 @@ class SimilaritySearcher:
158
 
159
  def main():
160
  args = parse_args()
161
- model = load_model(CONV_MODEL_REPO, CONV_MODEL_REVISION, CONV_FEXT_LAYER)
162
- images_ids = np.load("index/cosine_ids.npy")
163
-
164
- searcher = SimilaritySearcher(model=model, images_ids=images_ids)
165
 
166
  with gr.Blocks() as demo:
167
  gr.Markdown(TITLE)
168
  gr.Markdown(DESCRIPTION)
169
 
170
  with gr.Row():
171
- input = gr.Image(type="pil", label="Input")
172
  with gr.Column():
173
  with gr.Row():
174
  api_username = gr.Textbox(label="Danbooru API Username")
@@ -179,12 +112,6 @@ def main():
179
  label="Ratings",
180
  )
181
  with gr.Row():
182
- selected_metric = gr.Radio(
183
- choices=["cosine"],
184
- value="cosine",
185
- label="Metric selection",
186
- visible=False,
187
- )
188
  n_neighbours = gr.Slider(
189
  minimum=1,
190
  maximum=20,
@@ -198,12 +125,11 @@ def main():
198
  find_btn.click(
199
  fn=searcher.predict,
200
  inputs=[
201
- input,
202
  selected_ratings,
203
- selected_metric,
204
  api_username,
205
  api_key,
206
- n_neighbours,
207
  ],
208
  outputs=[similar_images],
209
  )
 
1
  import argparse
 
2
  import json
 
 
3
 
4
  import faiss
5
  import gradio as gr
6
  import numpy as np
 
7
  import requests
8
+ from imgutils.tagging import wd14
 
 
 
9
 
10
  TITLE = "## Danbooru Explorer"
11
  DESCRIPTION = """
12
  Image similarity-based retrieval tool using:
13
+ - [SmilingWolf/wd-swinv2-tagger-v3](https://huggingface.co/SmilingWolf/wd-swinv2-tagger-v3) as feature extractor
14
+ - [dghs-imgutils](https://github.com/deepghs/imgutils) for feature extraction
15
  - [Faiss](https://github.com/facebookresearch/faiss) and [autofaiss](https://github.com/criteo/autofaiss) for indexing
16
 
17
  Also, check out [SmilingWolf/danbooru2022_embeddings_playground](https://huggingface.co/spaces/SmilingWolf/danbooru2022_embeddings_playground) for a similar space with experimental support for text input combined with image input.
18
  """
19
 
 
 
 
 
20
 
21
  def parse_args() -> argparse.Namespace:
22
  parser = argparse.ArgumentParser()
 
24
  return parser.parse_args()
25
 
26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  def danbooru_id_to_url(image_id, selected_ratings, api_username="", api_key=""):
28
  headers = {"User-Agent": "image_similarity_tool"}
29
  ratings_to_letters = {
 
50
 
51
 
52
  class SimilaritySearcher:
53
+ def __init__(self):
54
+ self.images_ids = np.load("index/cosine_ids.npy")
55
+ self.knn_index = faiss.read_index("index/cosine_knn.index")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
+ config = json.loads(open("index/cosine_infos.json").read())["index_param"]
58
  faiss.ParameterSpace().set_index_parameters(self.knn_index, config)
 
59
 
60
  def predict(
61
+ self,
62
+ img_input,
63
+ selected_ratings,
64
+ n_neighbours,
65
+ api_username,
66
+ api_key,
67
  ):
68
+ embeddings = wd14.get_wd14_tags(
69
+ img_input,
70
+ model_name="SwinV2_v3",
71
+ fmt=("embedding"),
72
+ )
73
+ embeddings = np.expand_dims(embeddings, 0)
74
+ faiss.normalize_L2(embeddings)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
+ dists, indexes = self.knn_index.search(embeddings, k=n_neighbours)
77
  neighbours_ids = self.images_ids[indexes][0]
78
  neighbours_ids = [int(x) for x in neighbours_ids]
79
 
 
81
  image_urls = []
82
  for image_id, dist in zip(neighbours_ids, dists[0]):
83
  current_url = danbooru_id_to_url(
84
+ image_id,
85
+ selected_ratings,
86
+ api_username,
87
+ api_key,
88
  )
89
  if current_url is not None:
90
  image_urls.append(current_url)
 
94
 
95
  def main():
96
  args = parse_args()
97
+ searcher = SimilaritySearcher()
 
 
 
98
 
99
  with gr.Blocks() as demo:
100
  gr.Markdown(TITLE)
101
  gr.Markdown(DESCRIPTION)
102
 
103
  with gr.Row():
104
+ img_input = gr.Image(type="pil", label="Input")
105
  with gr.Column():
106
  with gr.Row():
107
  api_username = gr.Textbox(label="Danbooru API Username")
 
112
  label="Ratings",
113
  )
114
  with gr.Row():
 
 
 
 
 
 
115
  n_neighbours = gr.Slider(
116
  minimum=1,
117
  maximum=20,
 
125
  find_btn.click(
126
  fn=searcher.predict,
127
  inputs=[
128
+ img_input,
129
  selected_ratings,
130
+ n_neighbours,
131
  api_username,
132
  api_key,
 
133
  ],
134
  outputs=[similar_images],
135
  )
index/cosine_ids.npy CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:df724519c8c1981e49d80e2430261deb4fb6edf6d9c04e134427879710747394
3
- size 21830676
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:36f75b729ccdb6f46abbae84e1587a4e93387846a31f5ecd6ed0523ec731e3be
3
+ size 26567768
index/cosine_infos.json CHANGED
@@ -1 +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}
 
1
+ {"index_key": "OPQ256_1280,IVF16384_HNSW32,PQ256x8", "index_param": "nprobe=16,efSearch=32,ht=2048", "index_path": "/home/SmilingWolf/eval/index/swinv2_base_2024_03_13_17h37m11s_cosine_knn.index", "size in bytes": 1848491744, "avg_search_speed_ms": 12.240526417507978, "99p_search_speed_ms": 15.45338472060394, "reconstruction error %": 20.334696769714355, "nb vectors": 6641910, "vectors dimension": 1024, "compression ratio": 14.717546588079324}
index/cosine_knn.index CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:3a718ab8370df8b9d84002c55f945ef241e4cc3450d306c2ecd97661f51022ad
3
- size 1535843672
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:615ea848c51b153c4481ecfffcde206c56fc607eb88be99b996ab14f413b985a
3
+ size 1848491744
requirements.txt CHANGED
@@ -1,4 +1,4 @@
1
  pillow>=9.0.0
2
- opencv-python
3
- tensorflow-cpu~=2.15.1
4
  faiss-cpu
 
 
 
1
  pillow>=9.0.0
 
 
2
  faiss-cpu
3
+ dghs-imgutils
4
+ onnxruntime