v2ray commited on
Commit
ef1ffa0
1 Parent(s): edec988

Added balance tags script.

Browse files
Files changed (4) hide show
  1. .gitignore +1 -0
  2. balance_tags.py +131 -0
  3. constants.py +2 -0
  4. utils.py +15 -6
.gitignore CHANGED
@@ -1,3 +1,4 @@
1
  images/
2
  __pycache__/
3
  .ipynb_checkpoints/
 
 
1
  images/
2
  __pycache__/
3
  .ipynb_checkpoints/
4
+ model_tags.txt
balance_tags.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import tqdm
4
+ import utils
5
+ import shutil
6
+ import random
7
+ import argparse
8
+ from constants import *
9
+
10
+ def get_model_tags(model_tags_path):
11
+ if not os.path.isfile(model_tags_path):
12
+ raise FileNotFoundError(f"\"{model_tags_path}\" is not a file, please place one there!")
13
+ index_tag_dict = {}
14
+ with open(model_tags_path, "r", encoding="utf8") as model_tags_file:
15
+ for line in model_tags_file:
16
+ line = line.split()
17
+ if len(line) != 2:
18
+ continue
19
+ index_tag_dict[int(line[0])] = line[1]
20
+ if len(index_tag_dict) <= 0:
21
+ return []
22
+ sorted_index_tag_tuple_list = sorted(index_tag_dict.items(), key=lambda x: x[0])
23
+ if len(sorted_index_tag_tuple_list) != sorted_index_tag_tuple_list[-1][0] + 1:
24
+ raise ValueError(f"The index specified in \"{model_tags_path}\" is not continuous!")
25
+ return [tag for _, tag in sorted_index_tag_tuple_list]
26
+
27
+ def get_tags_set(tags_path):
28
+ if not os.path.isfile(tags_path):
29
+ raise FileNotFoundError(f"\"{tags_path}\" is not a file!")
30
+ with open(tags_path, "r", encoding="utf8") as tags_file:
31
+ tags_text = tags_file.read()
32
+ tags_set = set()
33
+ for tag in tags_text.split(","):
34
+ tag = tag.strip()
35
+ if tag:
36
+ tag = tag.replace(" ", "_")
37
+ if tag == "nsfw": tag = "rating:explicit"
38
+ elif tag == "qfw": tag = "rating:questionable"
39
+ elif tag == "sfw": tag = "rating:safe"
40
+ tags_set.add(tag)
41
+ return tags_set
42
+
43
+ def parse_args():
44
+ parser = argparse.ArgumentParser(description="Balance the dataset based on tag frequency.")
45
+ parser.add_argument("-c", "--count", type=int, help="The target selection count, must be an integer greater than 0")
46
+ parser.add_argument("-d", "--display", action="store_true", help="Display the count of images in each bucket")
47
+ parser.add_argument("-r", "--reverse", action="store_true", help="Display in reverse order, only for displaying")
48
+ args = parser.parse_args()
49
+ if not args.display:
50
+ if args.reverse:
51
+ print("You can't specify reverse when not using display mode!")
52
+ sys.exit(1)
53
+ if not isinstance(args.count, int):
54
+ print("You must specify the target selection count when not using display mode!")
55
+ sys.exit(1)
56
+ if args.count <= 0:
57
+ print("Target selection count must be an integer greater than 0!")
58
+ sys.exit(1)
59
+ elif isinstance(args.count, int):
60
+ print("You can't specify the target selection count when using display mode!")
61
+ sys.exit(1)
62
+ return args
63
+
64
+ def main():
65
+ args = parse_args()
66
+ print("Starting...\nGetting model tags...")
67
+ model_tags = get_model_tags(MODEL_TAGS_PATH)
68
+ print("Getting paths...")
69
+ image_id_image_tags_path_tuple_tuple_list = sorted(utils.get_image_id_image_tags_path_tuple_dict(IMAGE_DIR).items(), key=lambda x: x[0])
70
+ print("Got", len(image_id_image_tags_path_tuple_tuple_list), "images.\nShuffling paths...")
71
+ random.seed(42)
72
+ random.shuffle(image_id_image_tags_path_tuple_tuple_list)
73
+ print("Making buckets...")
74
+ in_bucket_image_count = 0
75
+ buckets = {tag: [] for tag in model_tags}
76
+ for image_id_image_tags_path_tuple_tuple in tqdm.tqdm(image_id_image_tags_path_tuple_tuple_list, desc="Making buckets"):
77
+ did_append = False
78
+ for tag in get_tags_set(image_id_image_tags_path_tuple_tuple[1][1]):
79
+ bucket = buckets.get(tag)
80
+ if bucket is None:
81
+ continue
82
+ bucket.append(image_id_image_tags_path_tuple_tuple)
83
+ did_append = True
84
+ if did_append:
85
+ in_bucket_image_count += 1
86
+ print("Got", in_bucket_image_count, "unique images in buckets.")
87
+ buckets = sorted(buckets.items(), key=lambda x: len(x[1]))
88
+ if args.display:
89
+ if args.reverse: range_iter = range(len(buckets) - 1, -1, -1)
90
+ else: range_iter = range(len(buckets))
91
+ for i in range_iter: print(buckets[i][0], len(buckets[i][1]))
92
+ return
93
+ print("Selecting...")
94
+ total = min(args.count, in_bucket_image_count)
95
+ selected = {} # Key: Image ID, Value: Tuple(Image path, Tags path).
96
+ with tqdm.tqdm(total=total, desc="Selecting") as progress_bar:
97
+ while len(selected) < total:
98
+ for tag, image_id_image_tags_path_tuple_tuple_list in buckets:
99
+ if len(selected) >= total:
100
+ break
101
+ if len(image_id_image_tags_path_tuple_tuple_list) <= 0:
102
+ continue
103
+ for i in range(len(image_id_image_tags_path_tuple_tuple_list) - 1, -1, -1):
104
+ if image_id_image_tags_path_tuple_tuple_list[i][0] in selected:
105
+ del image_id_image_tags_path_tuple_tuple_list[i]
106
+ break
107
+ else:
108
+ last_item = image_id_image_tags_path_tuple_tuple_list[-1]
109
+ selected[last_item[0]] = last_item[1]
110
+ del image_id_image_tags_path_tuple_tuple_list[-1]
111
+ progress_bar.update(1)
112
+ print("Selected", len(selected), "images.\nDeleting unselected images...")
113
+ temp_dir = "__tag_bal_trans_tmp__"
114
+ if os.path.exists(temp_dir):
115
+ shutil.rmtree(temp_dir)
116
+ os.makedirs(temp_dir)
117
+ for image_tags_path_tuple in tqdm.tqdm(selected.values(), desc="Moving"):
118
+ image_path = image_tags_path_tuple[0]
119
+ tags_path = image_tags_path_tuple[1]
120
+ os.rename(image_path, os.path.join(temp_dir, os.path.basename(image_path)))
121
+ os.rename(tags_path, os.path.join(temp_dir, os.path.basename(tags_path)))
122
+ shutil.rmtree(IMAGE_DIR)
123
+ shutil.move(temp_dir, IMAGE_DIR)
124
+ print("Finished.")
125
+
126
+ if __name__ == "__main__":
127
+ try:
128
+ main()
129
+ except KeyboardInterrupt:
130
+ print("\nScript interrupted by user, exiting...")
131
+ sys.exit(1)
constants.py CHANGED
@@ -10,3 +10,5 @@ IMAGE_EXT = {
10
  ".png", ".jpg", ".jpeg", ".bmp", ".tiff", ".tif",
11
  ".webp", ".heic", ".heif", ".avif", ".jxl",
12
  }
 
 
 
10
  ".png", ".jpg", ".jpeg", ".bmp", ".tiff", ".tif",
11
  ".webp", ".heic", ".heif", ".avif", ".jxl",
12
  }
13
+
14
+ MODEL_TAGS_PATH = "model_tags.txt"
utils.py CHANGED
@@ -59,13 +59,22 @@ def validate_image(image_path, tags_path, width=None, height=None, convert_to_av
59
  async def submit_validation(thread_pool, image_path, tags_path, width=None, height=None, convert_to_avif=False):
60
  return await asyncio.wrap_future(thread_pool.submit(validate_image, image_path, tags_path, width, height, convert_to_avif))
61
 
62
- def get_existing_image_tags_set(image_dir):
63
  if not os.path.isdir(image_dir):
64
- return set()
65
- existing_image_tags = set()
66
  for path in os.listdir(image_dir):
67
  image_id, ext = os.path.splitext(path)
68
- if ext != ".txt":
 
 
 
 
 
 
69
  continue
70
- existing_image_tags.add(image_id)
71
- return existing_image_tags
 
 
 
 
59
  async def submit_validation(thread_pool, image_path, tags_path, width=None, height=None, convert_to_avif=False):
60
  return await asyncio.wrap_future(thread_pool.submit(validate_image, image_path, tags_path, width, height, convert_to_avif))
61
 
62
+ def get_image_id_image_tags_path_tuple_dict(image_dir):
63
  if not os.path.isdir(image_dir):
64
+ raise FileNotFoundError(f"\"{image_dir}\" is not a directory!")
65
+ image_id_image_tags_path_tuple_dict = {}
66
  for path in os.listdir(image_dir):
67
  image_id, ext = os.path.splitext(path)
68
+ if ext == ".txt":
69
+ continue
70
+ path = os.path.join(image_dir, path)
71
+ if not os.path.isfile(path):
72
+ continue
73
+ tags_path = os.path.splitext(path)[0] + ".txt"
74
+ if not os.path.isfile(tags_path):
75
  continue
76
+ image_id_image_tags_path_tuple_dict[image_id] = (path, tags_path)
77
+ return image_id_image_tags_path_tuple_dict
78
+
79
+ def get_existing_image_tags_set(image_dir):
80
+ return {tags_path for _, tags_path in get_image_id_image_tags_path_tuple_dict(image_dir)}