2023-03-08 07:02:14 -07:00
|
|
|
import yaml
|
|
|
|
import json
|
|
|
|
|
2023-06-04 17:01:59 -06:00
|
|
|
from attrs import define, field
|
2023-03-08 07:02:14 -07:00
|
|
|
from data.image_train_item import ImageCaption, ImageTrainItem
|
|
|
|
from utils.fs_helpers import *
|
2023-03-19 16:30:42 -06:00
|
|
|
from typing import Iterable
|
2023-03-08 07:02:14 -07:00
|
|
|
|
2023-03-15 10:06:29 -06:00
|
|
|
from tqdm import tqdm
|
|
|
|
|
2023-03-15 14:47:33 -06:00
|
|
|
DEFAULT_MAX_CAPTION_LENGTH = 2048
|
|
|
|
|
2023-03-12 12:48:15 -06:00
|
|
|
def overlay(overlay, base):
|
|
|
|
return overlay if overlay is not None else base
|
|
|
|
|
|
|
|
def safe_set(val):
|
|
|
|
if isinstance(val, str):
|
2023-03-19 16:30:42 -06:00
|
|
|
return dict.fromkeys([val]) if val else dict()
|
2023-03-12 12:48:15 -06:00
|
|
|
|
|
|
|
if isinstance(val, Iterable):
|
2023-03-19 16:30:42 -06:00
|
|
|
return dict.fromkeys((i for i in val if i is not None))
|
2023-03-12 12:48:15 -06:00
|
|
|
|
2023-03-19 16:30:42 -06:00
|
|
|
return val or dict()
|
2023-03-12 12:48:15 -06:00
|
|
|
|
2023-03-08 07:02:14 -07:00
|
|
|
@define(frozen=True)
|
|
|
|
class Tag:
|
|
|
|
value: str
|
2023-03-12 12:48:15 -06:00
|
|
|
weight: float = field(default=1.0, converter=lambda x: x if x is not None else 1.0)
|
|
|
|
|
2023-03-08 07:02:14 -07:00
|
|
|
@classmethod
|
2023-03-12 12:48:15 -06:00
|
|
|
def parse(cls, data):
|
|
|
|
if isinstance(data, str):
|
|
|
|
return Tag(data)
|
2023-03-08 07:02:14 -07:00
|
|
|
|
2023-03-12 12:48:15 -06:00
|
|
|
if isinstance(data, dict):
|
2023-04-22 16:36:32 -06:00
|
|
|
value = str(data.get("tag"))
|
2023-03-12 12:48:15 -06:00
|
|
|
weight = data.get("weight")
|
|
|
|
if value:
|
|
|
|
return Tag(value, weight)
|
2023-03-08 07:02:14 -07:00
|
|
|
|
2023-03-12 12:48:15 -06:00
|
|
|
return None
|
2023-03-08 07:02:14 -07:00
|
|
|
|
2023-03-12 12:48:15 -06:00
|
|
|
@define
|
2023-03-08 07:02:14 -07:00
|
|
|
class ImageConfig:
|
2023-03-12 12:48:15 -06:00
|
|
|
# Captions
|
2023-03-19 16:30:42 -06:00
|
|
|
main_prompts: dict[str, None] = field(factory=dict, converter=safe_set)
|
2023-03-12 12:48:15 -06:00
|
|
|
rating: float = None
|
|
|
|
max_caption_length: int = None
|
2023-03-19 16:30:42 -06:00
|
|
|
tags: dict[Tag, None] = field(factory=dict, converter=safe_set)
|
2023-06-04 17:01:59 -06:00
|
|
|
batch_id: str = None
|
2023-03-12 12:48:15 -06:00
|
|
|
|
|
|
|
# Options
|
2023-03-08 07:02:14 -07:00
|
|
|
multiply: float = None
|
|
|
|
cond_dropout: float = None
|
|
|
|
flip_p: float = None
|
2023-06-01 14:18:21 -06:00
|
|
|
shuffle_tags: bool = False
|
2023-03-08 07:02:14 -07:00
|
|
|
|
|
|
|
def merge(self, other):
|
|
|
|
if other is None:
|
|
|
|
return self
|
|
|
|
|
|
|
|
return ImageConfig(
|
2023-03-20 17:15:53 -06:00
|
|
|
main_prompts=other.main_prompts | self.main_prompts,
|
2023-03-12 12:48:15 -06:00
|
|
|
rating=overlay(other.rating, self.rating),
|
|
|
|
max_caption_length=overlay(other.max_caption_length, self.max_caption_length),
|
2023-03-20 17:15:53 -06:00
|
|
|
tags= other.tags | self.tags,
|
2023-03-12 12:48:15 -06:00
|
|
|
multiply=overlay(other.multiply, self.multiply),
|
|
|
|
cond_dropout=overlay(other.cond_dropout, self.cond_dropout),
|
|
|
|
flip_p=overlay(other.flip_p, self.flip_p),
|
2023-06-01 14:18:21 -06:00
|
|
|
shuffle_tags=overlay(other.shuffle_tags, self.shuffle_tags),
|
2023-06-04 17:01:59 -06:00
|
|
|
batch_id=overlay(other.batch_id, self.batch_id)
|
2023-03-12 12:48:15 -06:00
|
|
|
)
|
2023-03-08 07:02:14 -07:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def from_dict(cls, data: dict):
|
2023-03-12 12:48:15 -06:00
|
|
|
# Parse standard yaml tag file (with options)
|
|
|
|
parsed_cfg = ImageConfig(
|
|
|
|
main_prompts=safe_set(data.get("main_prompt")),
|
|
|
|
rating=data.get("rating"),
|
|
|
|
max_caption_length=data.get("max_caption_length"),
|
|
|
|
tags=safe_set(map(Tag.parse, data.get("tags", []))),
|
2023-03-08 07:02:14 -07:00
|
|
|
multiply=data.get("multiply"),
|
|
|
|
cond_dropout=data.get("cond_dropout"),
|
2023-03-12 12:48:15 -06:00
|
|
|
flip_p=data.get("flip_p"),
|
2023-06-01 14:18:21 -06:00
|
|
|
shuffle_tags=data.get("shuffle_tags"),
|
2023-06-04 17:01:59 -06:00
|
|
|
batch_id=data.get("batch_id")
|
2023-03-12 12:48:15 -06:00
|
|
|
)
|
|
|
|
|
|
|
|
# Alternatively parse from dedicated `caption` attribute
|
|
|
|
if cap_attr := data.get('caption'):
|
|
|
|
parsed_cfg = parsed_cfg.merge(ImageConfig.parse(cap_attr))
|
|
|
|
|
|
|
|
return parsed_cfg
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def fold(cls, configs):
|
|
|
|
acc = ImageConfig()
|
|
|
|
for cfg in configs:
|
|
|
|
acc = acc.merge(cfg)
|
2023-06-01 14:18:21 -06:00
|
|
|
|
|
|
|
acc.shuffle_tags = any(cfg.shuffle_tags for cfg in configs)
|
2023-06-01 17:17:43 -06:00
|
|
|
#print(f"accum shuffle:{acc.shuffle_tags}")
|
2023-03-12 12:48:15 -06:00
|
|
|
return acc
|
|
|
|
|
|
|
|
def ensure_caption(self):
|
|
|
|
return self
|
2023-03-08 07:02:14 -07:00
|
|
|
|
|
|
|
@classmethod
|
2023-03-12 12:48:15 -06:00
|
|
|
def from_caption_text(cls, text: str):
|
|
|
|
if not text:
|
|
|
|
return ImageConfig()
|
|
|
|
if os.path.isfile(text):
|
|
|
|
return ImageConfig.from_file(text)
|
|
|
|
|
|
|
|
split_caption = list(map(str.strip, text.split(",")))
|
|
|
|
return ImageConfig(
|
|
|
|
main_prompts=split_caption[0],
|
|
|
|
tags=map(Tag.parse, split_caption[1:])
|
|
|
|
)
|
2023-03-08 07:02:14 -07:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def from_file(cls, file: str):
|
2023-03-12 12:48:15 -06:00
|
|
|
match ext(file):
|
|
|
|
case '.jpg' | '.jpeg' | '.png' | '.bmp' | '.webp' | '.jfif':
|
|
|
|
return ImageConfig(image=file)
|
|
|
|
case ".json":
|
|
|
|
return ImageConfig.from_dict(json.load(read_text(file)))
|
|
|
|
case ".yaml" | ".yml":
|
|
|
|
return ImageConfig.from_dict(yaml.safe_load(read_text(file)))
|
|
|
|
case ".txt" | ".caption":
|
|
|
|
return ImageConfig.from_caption_text(read_text(file))
|
|
|
|
case _:
|
|
|
|
return logging.warning(" *** Unrecognized config extension {ext}")
|
2023-03-08 07:02:14 -07:00
|
|
|
|
|
|
|
@classmethod
|
2023-03-12 12:48:15 -06:00
|
|
|
def parse(cls, input):
|
2023-03-08 07:02:14 -07:00
|
|
|
if isinstance(input, str):
|
2023-03-12 12:48:15 -06:00
|
|
|
if os.path.isfile(input):
|
|
|
|
return ImageConfig.from_file(input)
|
|
|
|
else:
|
|
|
|
return ImageConfig.from_caption_text(input)
|
2023-03-08 07:02:14 -07:00
|
|
|
elif isinstance(input, dict):
|
|
|
|
return ImageConfig.from_dict(input)
|
2023-03-12 12:48:15 -06:00
|
|
|
|
2023-03-08 07:02:14 -07:00
|
|
|
|
|
|
|
@define()
|
|
|
|
class Dataset:
|
2023-03-12 12:48:15 -06:00
|
|
|
image_configs: dict[str, ImageConfig]
|
2023-03-08 07:02:14 -07:00
|
|
|
|
2023-03-21 05:09:52 -06:00
|
|
|
def __global_cfg(fileset):
|
2023-03-08 07:02:14 -07:00
|
|
|
cfgs = []
|
2023-03-21 05:09:52 -06:00
|
|
|
|
|
|
|
for cfgfile in ['global.yaml', 'global.yml']:
|
|
|
|
if cfgfile in fileset:
|
|
|
|
cfgs.append(ImageConfig.from_file(fileset[cfgfile]))
|
2023-03-08 07:02:14 -07:00
|
|
|
return ImageConfig.fold(cfgs)
|
|
|
|
|
2023-03-21 05:09:52 -06:00
|
|
|
def __local_cfg(fileset):
|
2023-03-08 07:02:14 -07:00
|
|
|
cfgs = []
|
2023-06-01 14:18:21 -06:00
|
|
|
|
2023-03-21 05:09:52 -06:00
|
|
|
if 'multiply.txt' in fileset:
|
|
|
|
cfgs.append(ImageConfig(multiply=read_float(fileset['multiply.txt'])))
|
|
|
|
if 'cond_dropout.txt' in fileset:
|
|
|
|
cfgs.append(ImageConfig(cond_dropout=read_float(fileset['cond_dropout.txt'])))
|
|
|
|
if 'flip_p.txt' in fileset:
|
|
|
|
cfgs.append(ImageConfig(flip_p=read_float(fileset['flip_p.txt'])))
|
|
|
|
if 'local.yaml' in fileset:
|
|
|
|
cfgs.append(ImageConfig.from_file(fileset['local.yaml']))
|
|
|
|
if 'local.yml' in fileset:
|
|
|
|
cfgs.append(ImageConfig.from_file(fileset['local.yml']))
|
2023-06-04 17:01:59 -06:00
|
|
|
if 'batch_id.txt' in fileset:
|
|
|
|
cfgs.append(ImageConfig(batch_id=read_text(fileset['batch_id.txt'])))
|
2023-06-01 14:18:21 -06:00
|
|
|
|
|
|
|
result = ImageConfig.fold(cfgs)
|
|
|
|
if 'shuffle_tags.txt' in fileset:
|
|
|
|
result.shuffle_tags = True
|
|
|
|
|
|
|
|
return result
|
2023-03-08 07:02:14 -07:00
|
|
|
|
2023-03-21 05:09:52 -06:00
|
|
|
def __sidecar_cfg(imagepath, fileset):
|
2023-03-12 12:48:15 -06:00
|
|
|
cfgs = []
|
2023-03-21 05:09:52 -06:00
|
|
|
for cfgext in ['.txt', '.caption', '.yml', '.yaml']:
|
|
|
|
cfgfile = barename(imagepath) + cfgext
|
|
|
|
if cfgfile in fileset:
|
|
|
|
cfgs.append(ImageConfig.from_file(fileset[cfgfile]))
|
2023-03-08 07:02:14 -07:00
|
|
|
return ImageConfig.fold(cfgs)
|
|
|
|
|
2023-03-12 12:48:15 -06:00
|
|
|
# Use file name for caption only as a last resort
|
|
|
|
@classmethod
|
|
|
|
def __ensure_caption(cls, cfg: ImageConfig, file: str):
|
2023-04-13 02:36:05 -06:00
|
|
|
if cfg.main_prompts:
|
2023-03-12 12:48:15 -06:00
|
|
|
return cfg
|
|
|
|
cap_cfg = ImageConfig.from_caption_text(barename(file).split("_")[0])
|
|
|
|
return cfg.merge(cap_cfg)
|
|
|
|
|
2023-03-08 07:02:14 -07:00
|
|
|
@classmethod
|
|
|
|
def from_path(cls, data_root):
|
|
|
|
# Create a visitor that maintains global config stack
|
|
|
|
# and accumulates image configs as it traverses dataset
|
2023-03-12 12:48:15 -06:00
|
|
|
image_configs = {}
|
2023-03-08 07:02:14 -07:00
|
|
|
def process_dir(files, parent_globals):
|
2023-03-21 05:09:52 -06:00
|
|
|
fileset = {os.path.basename(f): f for f in files}
|
|
|
|
global_cfg = parent_globals.merge(Dataset.__global_cfg(fileset))
|
|
|
|
local_cfg = Dataset.__local_cfg(fileset)
|
2023-03-08 07:02:14 -07:00
|
|
|
for img in filter(is_image, files):
|
2023-03-21 05:09:52 -06:00
|
|
|
img_cfg = Dataset.__sidecar_cfg(img, fileset)
|
2023-03-12 12:48:15 -06:00
|
|
|
resolved_cfg = ImageConfig.fold([global_cfg, local_cfg, img_cfg])
|
|
|
|
image_configs[img] = Dataset.__ensure_caption(resolved_cfg, img)
|
|
|
|
return global_cfg
|
2023-03-08 07:02:14 -07:00
|
|
|
|
|
|
|
walk_and_visit(data_root, process_dir, ImageConfig())
|
|
|
|
return Dataset(image_configs)
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def from_json(cls, json_path):
|
|
|
|
"""
|
|
|
|
Import a dataset definition from a JSON file
|
|
|
|
"""
|
2023-03-12 12:48:15 -06:00
|
|
|
image_configs = {}
|
2023-03-08 07:02:14 -07:00
|
|
|
with open(json_path, encoding='utf-8', mode='r') as stream:
|
|
|
|
for data in json.load(stream):
|
2023-03-12 12:48:15 -06:00
|
|
|
img = data.get("image")
|
|
|
|
cfg = Dataset.__ensure_caption(ImageConfig.parse(data), img)
|
|
|
|
if not img:
|
2023-03-08 07:02:14 -07:00
|
|
|
logging.warning(f" *** Error parsing json image entry in {json_path}: {data}")
|
|
|
|
continue
|
2023-03-12 12:48:15 -06:00
|
|
|
image_configs[img] = cfg
|
|
|
|
return Dataset(image_configs)
|
2023-03-08 07:02:14 -07:00
|
|
|
|
|
|
|
def image_train_items(self, aspects):
|
|
|
|
items = []
|
2023-03-15 10:06:29 -06:00
|
|
|
for image in tqdm(self.image_configs, desc="preloading", dynamic_ncols=True):
|
2023-03-12 12:48:15 -06:00
|
|
|
config = self.image_configs[image]
|
2023-06-01 17:23:43 -06:00
|
|
|
#print(f" ********* shuffle: {config.shuffle_tags}")
|
2023-04-13 02:36:05 -06:00
|
|
|
|
2023-03-12 12:48:15 -06:00
|
|
|
if len(config.main_prompts) > 1:
|
|
|
|
logging.warning(f" *** Found multiple multiple main_prompts for image {image}, but only one will be applied: {config.main_prompts}")
|
2023-03-08 07:02:14 -07:00
|
|
|
|
2023-04-13 02:36:05 -06:00
|
|
|
if len(config.main_prompts) < 1:
|
|
|
|
logging.warning(f" *** No main_prompts for image {image}")
|
|
|
|
|
2023-03-08 07:02:14 -07:00
|
|
|
tags = []
|
|
|
|
tag_weights = []
|
2023-03-20 17:15:53 -06:00
|
|
|
for tag in sorted(config.tags, key=lambda x: x.weight or 1.0, reverse=True):
|
2023-03-08 07:02:14 -07:00
|
|
|
tags.append(tag.value)
|
2023-03-12 12:48:15 -06:00
|
|
|
tag_weights.append(tag.weight)
|
2023-03-08 07:02:14 -07:00
|
|
|
use_weights = len(set(tag_weights)) > 1
|
2023-03-18 20:27:09 -06:00
|
|
|
|
|
|
|
try:
|
|
|
|
caption = ImageCaption(
|
2023-03-20 17:15:53 -06:00
|
|
|
main_prompt=next(iter(config.main_prompts)),
|
2023-03-18 20:27:09 -06:00
|
|
|
rating=config.rating or 1.0,
|
|
|
|
tags=tags,
|
|
|
|
tag_weights=tag_weights,
|
|
|
|
max_target_length=config.max_caption_length or DEFAULT_MAX_CAPTION_LENGTH,
|
|
|
|
use_weights=use_weights)
|
|
|
|
|
|
|
|
item = ImageTrainItem(
|
|
|
|
image=None,
|
|
|
|
caption=caption,
|
|
|
|
aspects=aspects,
|
|
|
|
pathname=os.path.abspath(image),
|
|
|
|
flip_p=config.flip_p or 0.0,
|
|
|
|
multiplier=config.multiply or 1.0,
|
2023-06-01 14:18:21 -06:00
|
|
|
cond_dropout=config.cond_dropout,
|
|
|
|
shuffle_tags=config.shuffle_tags,
|
2023-06-04 17:01:59 -06:00
|
|
|
batch_id=config.batch_id
|
2023-03-18 20:27:09 -06:00
|
|
|
)
|
|
|
|
items.append(item)
|
|
|
|
except Exception as e:
|
|
|
|
logging.error(f" *** Error preloading image or caption for: {image}, error: {e}")
|
|
|
|
raise e
|
2023-03-18 20:24:03 -06:00
|
|
|
return items
|