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

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

Browse files
lora-scripts/sd-scripts/finetune/merge_dd_tags_to_metadata.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ from pathlib import Path
4
+ from typing import List
5
+ from tqdm import tqdm
6
+ import library.train_util as train_util
7
+ import os
8
+ from library.utils import setup_logging
9
+
10
+ setup_logging()
11
+ import logging
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ def main(args):
17
+ assert not args.recursive or (
18
+ args.recursive and args.full_path
19
+ ), "recursive requires full_path / recursiveはfull_pathと同時に指定してください"
20
+
21
+ train_data_dir_path = Path(args.train_data_dir)
22
+ image_paths: List[Path] = train_util.glob_images_pathlib(train_data_dir_path, args.recursive)
23
+ logger.info(f"found {len(image_paths)} images.")
24
+
25
+ if args.in_json is None and Path(args.out_json).is_file():
26
+ args.in_json = args.out_json
27
+
28
+ if args.in_json is not None:
29
+ logger.info(f"loading existing metadata: {args.in_json}")
30
+ metadata = json.loads(Path(args.in_json).read_text(encoding="utf-8"))
31
+ logger.warning("tags data for existing images will be overwritten / 既存の画像のタグは上書きされます")
32
+ else:
33
+ logger.info("new metadata will be created / 新しいメタデータファイルが作成されます")
34
+ metadata = {}
35
+
36
+ logger.info("merge tags to metadata json.")
37
+ for image_path in tqdm(image_paths):
38
+ tags_path = image_path.with_suffix(args.caption_extension)
39
+ tags = tags_path.read_text(encoding="utf-8").strip()
40
+
41
+ if not os.path.exists(tags_path):
42
+ tags_path = os.path.join(image_path, args.caption_extension)
43
+
44
+ image_key = str(image_path) if args.full_path else image_path.stem
45
+ if image_key not in metadata:
46
+ metadata[image_key] = {}
47
+
48
+ metadata[image_key]["tags"] = tags
49
+ if args.debug:
50
+ logger.info(f"{image_key} {tags}")
51
+
52
+ # metadataを書き出して終わり
53
+ logger.info(f"writing metadata: {args.out_json}")
54
+ Path(args.out_json).write_text(json.dumps(metadata, indent=2), encoding="utf-8")
55
+
56
+ logger.info("done!")
57
+
58
+
59
+ def setup_parser() -> argparse.ArgumentParser:
60
+ parser = argparse.ArgumentParser()
61
+ parser.add_argument("train_data_dir", type=str, help="directory for train images / 学習画像データのディレクトリ")
62
+ parser.add_argument("out_json", type=str, help="metadata file to output / メタデータファイル書き出し先")
63
+ parser.add_argument(
64
+ "--in_json",
65
+ type=str,
66
+ help="metadata file to input (if omitted and out_json exists, existing out_json is read) / 読み込むメタデータファイル(省略時、out_jsonが存在すればそれを読み込む)",
67
+ )
68
+ parser.add_argument(
69
+ "--full_path",
70
+ action="store_true",
71
+ help="use full path as image-key in metadata (supports multiple directories) / メタデータで画像キーをフルパスにする(複数の学習画像ディレクトリに対応)",
72
+ )
73
+ parser.add_argument(
74
+ "--recursive",
75
+ action="store_true",
76
+ help="recursively look for training tags in all child folders of train_data_dir / train_data_dirのすべての子フォルダにある学習タグを再帰的に探す",
77
+ )
78
+ parser.add_argument(
79
+ "--caption_extension",
80
+ type=str,
81
+ default=".txt",
82
+ help="extension of caption (tag) file / 読み込むキャプション(タグ)ファイルの拡張子",
83
+ )
84
+ parser.add_argument("--debug", action="store_true", help="debug mode, print tags")
85
+
86
+ return parser
87
+
88
+
89
+ if __name__ == "__main__":
90
+ parser = setup_parser()
91
+
92
+ args = parser.parse_args()
93
+ main(args)