ACCC1380 commited on
Commit
f5822b5
1 Parent(s): ed620e7

Upload lora-scripts/sd-scripts/finetune/clean_captions_and_tags.py with huggingface_hub

Browse files
lora-scripts/sd-scripts/finetune/clean_captions_and_tags.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # このスクリプトのライセンスは、Apache License 2.0とします
2
+ # (c) 2022 Kohya S. @kohya_ss
3
+
4
+ import argparse
5
+ import glob
6
+ import os
7
+ import json
8
+ import re
9
+
10
+ from tqdm import tqdm
11
+ from library.utils import setup_logging
12
+ setup_logging()
13
+ import logging
14
+ logger = logging.getLogger(__name__)
15
+
16
+ PATTERN_HAIR_LENGTH = re.compile(r', (long|short|medium) hair, ')
17
+ PATTERN_HAIR_CUT = re.compile(r', (bob|hime) cut, ')
18
+ PATTERN_HAIR = re.compile(r', ([\w\-]+) hair, ')
19
+ PATTERN_WORD = re.compile(r', ([\w\-]+|hair ornament), ')
20
+
21
+ # 複数人がいるとき、複数の髪色や目の色が定義されていれば削除する
22
+ PATTERNS_REMOVE_IN_MULTI = [
23
+ PATTERN_HAIR_LENGTH,
24
+ PATTERN_HAIR_CUT,
25
+ re.compile(r', [\w\-]+ eyes, '),
26
+ re.compile(r', ([\w\-]+ sleeves|sleeveless), '),
27
+ # 複数の髪型定義がある場合は削除する
28
+ re.compile(
29
+ r', (ponytail|braid|ahoge|twintails|[\w\-]+ bun|single hair bun|single side bun|two side up|two tails|[\w\-]+ braid|sidelocks), '),
30
+ ]
31
+
32
+
33
+ def clean_tags(image_key, tags):
34
+ # replace '_' to ' '
35
+ tags = tags.replace('^_^', '^@@@^')
36
+ tags = tags.replace('_', ' ')
37
+ tags = tags.replace('^@@@^', '^_^')
38
+
39
+ # remove rating: deepdanbooruのみ
40
+ tokens = tags.split(", rating")
41
+ if len(tokens) == 1:
42
+ # WD14 taggerのときはこちらになるのでメッセージは出さない
43
+ # logger.info("no rating:")
44
+ # logger.info(f"{image_key} {tags}")
45
+ pass
46
+ else:
47
+ if len(tokens) > 2:
48
+ logger.info("multiple ratings:")
49
+ logger.info(f"{image_key} {tags}")
50
+ tags = tokens[0]
51
+
52
+ tags = ", " + tags.replace(", ", ", , ") + ", " # カンマ付きで検索をするための身も蓋もない対策
53
+
54
+ # 複数の人物がいる場合は髪色等のタグを削除する
55
+ if 'girls' in tags or 'boys' in tags:
56
+ for pat in PATTERNS_REMOVE_IN_MULTI:
57
+ found = pat.findall(tags)
58
+ if len(found) > 1: # 二つ以上、タグがある
59
+ tags = pat.sub("", tags)
60
+
61
+ # 髪の特殊対応
62
+ srch_hair_len = PATTERN_HAIR_LENGTH.search(tags) # 髪の長さタグは例外なので避けておく(全員が同じ髪の長さの場合)
63
+ if srch_hair_len:
64
+ org = srch_hair_len.group()
65
+ tags = PATTERN_HAIR_LENGTH.sub(", @@@, ", tags)
66
+
67
+ found = PATTERN_HAIR.findall(tags)
68
+ if len(found) > 1:
69
+ tags = PATTERN_HAIR.sub("", tags)
70
+
71
+ if srch_hair_len:
72
+ tags = tags.replace(", @@@, ", org) # 戻す
73
+
74
+ # white shirtとshirtみたいな重複タグの削除
75
+ found = PATTERN_WORD.findall(tags)
76
+ for word in found:
77
+ if re.search(f", ((\w+) )+{word}, ", tags):
78
+ tags = tags.replace(f", {word}, ", "")
79
+
80
+ tags = tags.replace(", , ", ", ")
81
+ assert tags.startswith(", ") and tags.endswith(", ")
82
+ tags = tags[2:-2]
83
+ return tags
84
+
85
+
86
+ # 上から順に検索、置換される
87
+ # ('置換元文字列', '置換後文字列')
88
+ CAPTION_REPLACEMENTS = [
89
+ ('anime anime', 'anime'),
90
+ ('young ', ''),
91
+ ('anime girl', 'girl'),
92
+ ('cartoon female', 'girl'),
93
+ ('cartoon lady', 'girl'),
94
+ ('cartoon character', 'girl'), # a or ~s
95
+ ('cartoon woman', 'girl'),
96
+ ('cartoon women', 'girls'),
97
+ ('cartoon girl', 'girl'),
98
+ ('anime female', 'girl'),
99
+ ('anime lady', 'girl'),
100
+ ('anime character', 'girl'), # a or ~s
101
+ ('anime woman', 'girl'),
102
+ ('anime women', 'girls'),
103
+ ('lady', 'girl'),
104
+ ('female', 'girl'),
105
+ ('woman', 'girl'),
106
+ ('women', 'girls'),
107
+ ('people', 'girls'),
108
+ ('person', 'girl'),
109
+ ('a cartoon figure', 'a figure'),
110
+ ('a cartoon image', 'an image'),
111
+ ('a cartoon picture', 'a picture'),
112
+ ('an anime cartoon image', 'an image'),
113
+ ('a cartoon anime drawing', 'a drawing'),
114
+ ('a cartoon drawing', 'a drawing'),
115
+ ('girl girl', 'girl'),
116
+ ]
117
+
118
+
119
+ def clean_caption(caption):
120
+ for rf, rt in CAPTION_REPLACEMENTS:
121
+ replaced = True
122
+ while replaced:
123
+ bef = caption
124
+ caption = caption.replace(rf, rt)
125
+ replaced = bef != caption
126
+ return caption
127
+
128
+
129
+ def main(args):
130
+ if os.path.exists(args.in_json):
131
+ logger.info(f"loading existing metadata: {args.in_json}")
132
+ with open(args.in_json, "rt", encoding='utf-8') as f:
133
+ metadata = json.load(f)
134
+ else:
135
+ logger.error("no metadata / メタデータファイルがありません")
136
+ return
137
+
138
+ logger.info("cleaning captions and tags.")
139
+ image_keys = list(metadata.keys())
140
+ for image_key in tqdm(image_keys):
141
+ tags = metadata[image_key].get('tags')
142
+ if tags is None:
143
+ logger.error(f"image does not have tags / メタデータにタグがありません: {image_key}")
144
+ else:
145
+ org = tags
146
+ tags = clean_tags(image_key, tags)
147
+ metadata[image_key]['tags'] = tags
148
+ if args.debug and org != tags:
149
+ logger.info("FROM: " + org)
150
+ logger.info("TO: " + tags)
151
+
152
+ caption = metadata[image_key].get('caption')
153
+ if caption is None:
154
+ logger.error(f"image does not have caption / メタデータにキャプションがありません: {image_key}")
155
+ else:
156
+ org = caption
157
+ caption = clean_caption(caption)
158
+ metadata[image_key]['caption'] = caption
159
+ if args.debug and org != caption:
160
+ logger.info("FROM: " + org)
161
+ logger.info("TO: " + caption)
162
+
163
+ # metadataを書き出して終わり
164
+ logger.info(f"writing metadata: {args.out_json}")
165
+ with open(args.out_json, "wt", encoding='utf-8') as f:
166
+ json.dump(metadata, f, indent=2)
167
+ logger.info("done!")
168
+
169
+
170
+ def setup_parser() -> argparse.ArgumentParser:
171
+ parser = argparse.ArgumentParser()
172
+ # parser.add_argument("train_data_dir", type=str, help="directory for train images / 学習画像データのディレクトリ")
173
+ parser.add_argument("in_json", type=str, help="metadata file to input / 読み込むメタデータファイル")
174
+ parser.add_argument("out_json", type=str, help="metadata file to output / メタデータファイル書き出し先")
175
+ parser.add_argument("--debug", action="store_true", help="debug mode")
176
+
177
+ return parser
178
+
179
+
180
+ if __name__ == '__main__':
181
+ parser = setup_parser()
182
+
183
+ args, unknown = parser.parse_known_args()
184
+ if len(unknown) == 1:
185
+ logger.warning("WARNING: train_data_dir argument is removed. This script will not work with three arguments in future. Please specify two arguments: in_json and out_json.")
186
+ logger.warning("All captions and tags in the metadata are processed.")
187
+ logger.warning("警告: train_data_dir引数は不要になりました。将来的には三つの引数を指定すると動かなくなる予定です。読み込み元のメタデータと書き出し先の二つの引数だけ指定してください。")
188
+ logger.warning("メタデータ内のすべてのキャプションとタグが処理されます。")
189
+ args.in_json = args.out_json
190
+ args.out_json = unknown[0]
191
+ elif len(unknown) > 0:
192
+ raise ValueError(f"error: unrecognized arguments: {unknown}")
193
+
194
+ main(args)