ACCC1380 commited on
Commit
6354438
1 Parent(s): ce364c7

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

Browse files
lora-scripts/sd-scripts/finetune/merge_captions_to_metadata.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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("captions for existing images will be overwritten / 既存の画像のキャプションは上書きされます")
32
+ else:
33
+ logger.info("new metadata will be created / 新しいメタデータファイルが作成されます")
34
+ metadata = {}
35
+
36
+ logger.info("merge caption texts to metadata json.")
37
+ for image_path in tqdm(image_paths):
38
+ caption_path = image_path.with_suffix(args.caption_extension)
39
+ caption = caption_path.read_text(encoding="utf-8").strip()
40
+
41
+ if not os.path.exists(caption_path):
42
+ caption_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]["caption"] = caption
49
+ if args.debug:
50
+ logger.info(f"{image_key} {caption}")
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
+ logger.info("done!")
56
+
57
+
58
+ def setup_parser() -> argparse.ArgumentParser:
59
+ parser = argparse.ArgumentParser()
60
+ parser.add_argument("train_data_dir", type=str, help="directory for train images / 学習画像データのディレクトリ")
61
+ parser.add_argument("out_json", type=str, help="metadata file to output / メタデータファイル書き出し先")
62
+ parser.add_argument(
63
+ "--in_json",
64
+ type=str,
65
+ help="metadata file to input (if omitted and out_json exists, existing out_json is read) / 読み込むメタデータファイル(省略時、out_jsonが存在すればそれを読み込む)",
66
+ )
67
+ parser.add_argument(
68
+ "--caption_extention",
69
+ type=str,
70
+ default=None,
71
+ help="extension of caption file (for backward compatibility) / 読み込むキャプションファイルの拡張子(スペルミスしていたのを残してあります)",
72
+ )
73
+ parser.add_argument(
74
+ "--caption_extension", type=str, default=".caption", help="extension of caption file / 読み込むキャプションファイルの拡張子"
75
+ )
76
+ parser.add_argument(
77
+ "--full_path",
78
+ action="store_true",
79
+ help="use full path as image-key in metadata (supports multiple directories) / メタデータで画像キーをフルパスにする(複数の学習画像ディレクトリに対応)",
80
+ )
81
+ parser.add_argument(
82
+ "--recursive",
83
+ action="store_true",
84
+ help="recursively look for training tags in all child folders of train_data_dir / train_data_dirのすべての子フォルダにある学習タグを再帰的に探す",
85
+ )
86
+ parser.add_argument("--debug", action="store_true", help="debug mode")
87
+
88
+ return parser
89
+
90
+
91
+ if __name__ == "__main__":
92
+ parser = setup_parser()
93
+
94
+ args = parser.parse_args()
95
+
96
+ # スペルミスしていたオプションを復元する
97
+ if args.caption_extention is not None:
98
+ args.caption_extension = args.caption_extention
99
+
100
+ main(args)