2022-12-17 20:32:48 -07:00
|
|
|
"""
|
|
|
|
Copyright [2022] Victor C Hall
|
|
|
|
|
|
|
|
Licensed under the GNU Affero General Public License;
|
|
|
|
You may not use this code except in compliance with the License.
|
|
|
|
You may obtain a copy of the License at
|
|
|
|
|
|
|
|
https://www.gnu.org/licenses/agpl-3.0.en.html
|
|
|
|
|
|
|
|
Unless required by applicable law or agreed to in writing, software
|
|
|
|
distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
See the License for the specific language governing permissions and
|
|
|
|
limitations under the License.
|
|
|
|
"""
|
2023-01-07 09:29:09 -07:00
|
|
|
import bisect
|
|
|
|
import logging
|
2022-12-17 20:32:48 -07:00
|
|
|
import math
|
|
|
|
import os
|
2023-01-07 09:29:09 -07:00
|
|
|
import random
|
2023-01-22 17:13:50 -07:00
|
|
|
import typing
|
|
|
|
import yaml
|
2023-01-07 09:29:09 -07:00
|
|
|
|
|
|
|
import PIL
|
2023-01-23 13:00:42 -07:00
|
|
|
import PIL.Image as Image
|
2023-03-15 09:12:59 -06:00
|
|
|
import PIL.ImageOps as ImageOps
|
2023-01-07 09:29:09 -07:00
|
|
|
import numpy as np
|
|
|
|
from torchvision import transforms
|
2022-12-17 20:32:48 -07:00
|
|
|
|
|
|
|
_RANDOM_TRIM = 0.04
|
|
|
|
|
2023-01-22 17:13:50 -07:00
|
|
|
|
|
|
|
OptionalImageCaption = typing.Optional['ImageCaption']
|
2023-01-07 09:29:09 -07:00
|
|
|
|
|
|
|
class ImageCaption:
|
|
|
|
"""
|
|
|
|
Represents the various parts of an image caption
|
|
|
|
"""
|
2023-02-28 19:14:19 -07:00
|
|
|
def __init__(self, main_prompt: str, rating: float, tags: list[str], tag_weights: list[float], max_target_length: int, use_weights: bool):
|
2023-01-07 09:29:09 -07:00
|
|
|
"""
|
|
|
|
:param main_prompt: The part of the caption which should always be included
|
|
|
|
:param tags: list of tags to pick from to fill the caption
|
|
|
|
:param tag_weights: weights to indicate which tags are more desired and should be picked preferably
|
2023-01-07 14:59:51 -07:00
|
|
|
:param max_target_length: The desired maximum length of a generated caption
|
|
|
|
:param use_weights: if ture, weights are considered when shuffling tags
|
2023-01-07 09:29:09 -07:00
|
|
|
"""
|
2023-02-28 19:14:19 -07:00
|
|
|
self.__main_prompt = main_prompt
|
2023-01-14 06:00:30 -07:00
|
|
|
self.__rating = rating
|
2023-01-07 09:29:09 -07:00
|
|
|
self.__tags = tags
|
|
|
|
self.__tag_weights = tag_weights
|
2023-03-26 09:52:49 -06:00
|
|
|
self.__max_target_length = max_target_length or 2048
|
2023-01-07 14:59:51 -07:00
|
|
|
self.__use_weights = use_weights
|
|
|
|
if use_weights and len(tags) > len(tag_weights):
|
2023-01-07 09:29:09 -07:00
|
|
|
self.__tag_weights.extend([1.0] * (len(tags) - len(tag_weights)))
|
|
|
|
|
2023-01-07 14:59:51 -07:00
|
|
|
if use_weights and len(tag_weights) > len(tags):
|
|
|
|
self.__tag_weights = tag_weights[:len(tags)]
|
|
|
|
|
2023-01-14 06:00:30 -07:00
|
|
|
def rating(self) -> float:
|
|
|
|
return self.__rating
|
|
|
|
|
2023-01-07 14:59:51 -07:00
|
|
|
def get_shuffled_caption(self, seed: int) -> str:
|
2023-01-07 09:29:09 -07:00
|
|
|
"""
|
|
|
|
returns the caption a string with a random selection of the tags in random order
|
|
|
|
:param seed used to initialize the randomizer
|
|
|
|
:return: generated caption string
|
|
|
|
"""
|
2023-01-22 17:13:50 -07:00
|
|
|
if self.__tags:
|
2023-03-26 09:52:49 -06:00
|
|
|
try:
|
|
|
|
max_target_tag_length = self.__max_target_length - len(self.__main_prompt or 0)
|
|
|
|
except Exception as e:
|
|
|
|
print()
|
|
|
|
logging.error(f"Error determining length for: {e} on {self.__main_prompt}")
|
|
|
|
print()
|
|
|
|
max_target_tag_length = 2048
|
2023-01-07 14:59:51 -07:00
|
|
|
|
2023-01-22 17:13:50 -07:00
|
|
|
if self.__use_weights:
|
|
|
|
tags_caption = self.__get_weighted_shuffled_tags(seed, self.__tags, self.__tag_weights, max_target_tag_length)
|
|
|
|
else:
|
|
|
|
tags_caption = self.__get_shuffled_tags(seed, self.__tags)
|
2023-01-07 09:29:09 -07:00
|
|
|
|
2023-02-28 19:14:19 -07:00
|
|
|
return self.__main_prompt + ", " + tags_caption
|
|
|
|
return self.__main_prompt
|
2023-01-07 09:29:09 -07:00
|
|
|
|
2023-02-28 19:14:19 -07:00
|
|
|
def get_caption(self) -> str:
|
|
|
|
if self.__tags:
|
|
|
|
return self.__main_prompt + ", " + ", ".join(self.__tags)
|
|
|
|
return self.__main_prompt
|
2023-01-07 09:29:09 -07:00
|
|
|
|
|
|
|
@staticmethod
|
2023-01-07 14:59:51 -07:00
|
|
|
def __get_weighted_shuffled_tags(seed: int, tags: list[str], weights: list[float], max_target_tag_length: int) -> str:
|
2023-01-07 09:29:09 -07:00
|
|
|
picker = random.Random(seed)
|
|
|
|
tags_copy = tags.copy()
|
|
|
|
weights_copy = weights.copy()
|
|
|
|
|
2023-01-07 14:59:51 -07:00
|
|
|
caption = ""
|
|
|
|
while len(tags_copy) != 0 and len(caption) < max_target_tag_length:
|
2023-01-07 09:29:09 -07:00
|
|
|
cum_weights = []
|
|
|
|
weight_sum = 0.0
|
|
|
|
for weight in weights_copy:
|
|
|
|
weight_sum += weight
|
|
|
|
cum_weights.append(weight_sum)
|
|
|
|
|
|
|
|
point = picker.uniform(0, weight_sum)
|
|
|
|
pos = bisect.bisect_left(cum_weights, point)
|
|
|
|
|
|
|
|
weights_copy.pop(pos)
|
|
|
|
tag = tags_copy.pop(pos)
|
2023-04-14 13:59:28 -06:00
|
|
|
|
2023-01-22 17:13:50 -07:00
|
|
|
if caption:
|
|
|
|
caption += ", "
|
|
|
|
caption += tag
|
2023-01-07 09:29:09 -07:00
|
|
|
|
|
|
|
return caption
|
|
|
|
|
2023-01-07 14:59:51 -07:00
|
|
|
@staticmethod
|
|
|
|
def __get_shuffled_tags(seed: int, tags: list[str]) -> str:
|
|
|
|
random.Random(seed).shuffle(tags)
|
|
|
|
return ", ".join(tags)
|
|
|
|
|
2023-01-14 06:00:30 -07:00
|
|
|
class ImageTrainItem:
|
2022-12-17 20:32:48 -07:00
|
|
|
"""
|
|
|
|
image: PIL.Image
|
|
|
|
identifier: caption,
|
2023-04-14 13:59:28 -06:00
|
|
|
target_aspect: (width, height),
|
2022-12-17 20:32:48 -07:00
|
|
|
pathname: path to image file
|
|
|
|
flip_p: probability of flipping image (0.0 to 1.0)
|
2023-01-14 06:00:30 -07:00
|
|
|
rating: the relative rating of the images. The rating is measured in comparison to the other images.
|
2023-01-07 09:29:09 -07:00
|
|
|
"""
|
2023-03-08 07:02:14 -07:00
|
|
|
def __init__(self, image: PIL.Image, caption: ImageCaption, aspects: list[float], pathname: str, flip_p=0.0, multiplier: float=1.0, cond_dropout=None):
|
2022-12-17 20:32:48 -07:00
|
|
|
self.caption = caption
|
2023-01-23 13:00:42 -07:00
|
|
|
self.aspects = aspects
|
2022-12-17 20:32:48 -07:00
|
|
|
self.pathname = pathname
|
|
|
|
self.flip = transforms.RandomHorizontalFlip(p=flip_p)
|
|
|
|
self.cropped_img = None
|
2023-01-01 08:45:18 -07:00
|
|
|
self.runt_size = 0
|
2023-01-21 23:15:50 -07:00
|
|
|
self.multiplier = multiplier
|
2023-03-08 07:02:14 -07:00
|
|
|
self.cond_dropout = cond_dropout
|
2022-12-17 20:32:48 -07:00
|
|
|
|
2023-01-23 17:57:02 -07:00
|
|
|
self.image_size = None
|
2023-02-08 03:28:45 -07:00
|
|
|
if image is None or len(image) == 0:
|
2022-12-17 20:32:48 -07:00
|
|
|
self.image = []
|
|
|
|
else:
|
|
|
|
self.image = image
|
2023-01-23 17:57:02 -07:00
|
|
|
self.image_size = image.size
|
|
|
|
self.target_size = None
|
2023-04-14 13:59:28 -06:00
|
|
|
|
2023-01-23 13:44:48 -07:00
|
|
|
self.is_undersized = False
|
2023-01-23 13:00:42 -07:00
|
|
|
self.error = None
|
|
|
|
self.__compute_target_width_height()
|
2022-12-17 20:32:48 -07:00
|
|
|
|
2023-04-14 19:21:48 -06:00
|
|
|
def load_image(self):
|
2023-03-28 11:19:08 -06:00
|
|
|
try:
|
2023-04-14 19:21:48 -06:00
|
|
|
image = PIL.Image.open(self.pathname).convert('RGB')
|
|
|
|
image = ImageOps.exif_transpose(image)
|
2023-03-28 11:19:08 -06:00
|
|
|
except SyntaxError as e:
|
|
|
|
pass
|
|
|
|
return image
|
|
|
|
|
2023-02-28 19:14:19 -07:00
|
|
|
def hydrate(self, crop=False, save=False, crop_jitter=20):
|
2022-12-17 20:32:48 -07:00
|
|
|
"""
|
|
|
|
crop: hard center crop to 512x512
|
|
|
|
save: save the cropped image to disk, for manual inspection of resize/crop
|
|
|
|
crop_jitter: randomly shift cropp by N pixels when using multiple aspect ratios to improve training quality
|
|
|
|
"""
|
2023-01-07 09:29:09 -07:00
|
|
|
# print(self.pathname, self.image)
|
2022-12-20 01:30:42 -07:00
|
|
|
try:
|
2023-01-07 09:29:09 -07:00
|
|
|
# if not hasattr(self, 'image'):
|
2023-03-28 11:19:08 -06:00
|
|
|
self.image = self.load_image()
|
2022-12-17 20:32:48 -07:00
|
|
|
|
|
|
|
width, height = self.image.size
|
2023-01-07 09:29:09 -07:00
|
|
|
if crop:
|
2022-12-17 20:32:48 -07:00
|
|
|
cropped_img = self.__autocrop(self.image)
|
2023-01-07 09:29:09 -07:00
|
|
|
self.image = cropped_img.resize((512, 512), resample=PIL.Image.BICUBIC)
|
2022-12-17 20:32:48 -07:00
|
|
|
else:
|
|
|
|
width, height = self.image.size
|
2023-01-07 09:29:09 -07:00
|
|
|
jitter_amount = random.randint(0, crop_jitter)
|
2022-12-17 20:32:48 -07:00
|
|
|
|
|
|
|
if self.target_wh[0] == self.target_wh[1]:
|
|
|
|
if width > height:
|
|
|
|
left = random.randint(0, width - height)
|
2023-01-07 09:29:09 -07:00
|
|
|
self.image = self.image.crop((left, 0, height + left, height))
|
2022-12-17 20:32:48 -07:00
|
|
|
width = height
|
|
|
|
elif height > width:
|
|
|
|
top = random.randint(0, height - width)
|
2023-01-07 09:29:09 -07:00
|
|
|
self.image = self.image.crop((0, top, width, width + top))
|
2022-12-17 20:32:48 -07:00
|
|
|
height = width
|
|
|
|
elif width > self.target_wh[0]:
|
2023-01-07 09:29:09 -07:00
|
|
|
slice = min(int(self.target_wh[0] * _RANDOM_TRIM), width - self.target_wh[0])
|
2022-12-17 20:32:48 -07:00
|
|
|
slicew_ratio = random.random()
|
2023-01-07 09:29:09 -07:00
|
|
|
left = int(slice * slicew_ratio)
|
|
|
|
right = width - int(slice * (1 - slicew_ratio))
|
2022-12-17 20:32:48 -07:00
|
|
|
sliceh_ratio = random.random()
|
2023-01-07 09:29:09 -07:00
|
|
|
top = int(slice * sliceh_ratio)
|
|
|
|
bottom = height - int(slice * (1 - sliceh_ratio))
|
2022-12-17 20:32:48 -07:00
|
|
|
|
|
|
|
self.image = self.image.crop((left, top, right, bottom))
|
2023-01-07 09:29:09 -07:00
|
|
|
else:
|
|
|
|
image_aspect = width / height
|
2022-12-17 20:32:48 -07:00
|
|
|
target_aspect = self.target_wh[0] / self.target_wh[1]
|
|
|
|
if image_aspect > target_aspect:
|
|
|
|
new_width = int(height * target_aspect)
|
2023-01-07 09:29:09 -07:00
|
|
|
jitter_amount = max(min(jitter_amount, int(abs(width - new_width) / 2)), 0)
|
2022-12-17 20:32:48 -07:00
|
|
|
left = jitter_amount
|
|
|
|
right = left + new_width
|
|
|
|
self.image = self.image.crop((left, 0, right, height))
|
|
|
|
else:
|
|
|
|
new_height = int(width / target_aspect)
|
2023-01-07 09:29:09 -07:00
|
|
|
jitter_amount = max(min(jitter_amount, int(abs(height - new_height) / 2)), 0)
|
2022-12-17 20:32:48 -07:00
|
|
|
top = jitter_amount
|
|
|
|
bottom = top + new_height
|
|
|
|
self.image = self.image.crop((0, top, width, bottom))
|
|
|
|
self.image = self.image.resize(self.target_wh, resample=PIL.Image.BICUBIC)
|
|
|
|
|
|
|
|
self.image = self.flip(self.image)
|
2022-12-20 01:30:42 -07:00
|
|
|
except Exception as e:
|
2022-12-27 12:25:32 -07:00
|
|
|
logging.error(f"Fatal Error loading image: {self.pathname}:")
|
|
|
|
logging.error(e)
|
2022-12-20 01:30:42 -07:00
|
|
|
exit()
|
2022-12-17 20:32:48 -07:00
|
|
|
|
|
|
|
if type(self.image) is not np.ndarray:
|
2023-02-28 19:14:19 -07:00
|
|
|
if save:
|
|
|
|
base_name = os.path.basename(self.pathname)
|
|
|
|
if not os.path.exists("test/output"):
|
|
|
|
os.makedirs("test/output")
|
|
|
|
self.image.save(f"test/output/{base_name}")
|
|
|
|
|
2022-12-17 20:32:48 -07:00
|
|
|
self.image = np.array(self.image).astype(np.uint8)
|
|
|
|
|
2023-02-28 19:14:19 -07:00
|
|
|
# self.image = (self.image / 127.5 - 1.0).astype(np.float32)
|
|
|
|
|
|
|
|
# print(self.image.shape)
|
|
|
|
|
2022-12-17 20:32:48 -07:00
|
|
|
return self
|
2023-04-14 13:59:28 -06:00
|
|
|
|
2023-01-23 13:00:42 -07:00
|
|
|
def __compute_target_width_height(self):
|
2023-01-24 09:33:40 -07:00
|
|
|
self.target_wh = None
|
2023-01-23 13:00:42 -07:00
|
|
|
try:
|
2023-04-14 19:21:48 -06:00
|
|
|
with PIL.Image.open(self.pathname) as image:
|
2023-04-16 00:19:27 -06:00
|
|
|
image = ImageOps.exif_transpose(image)
|
2023-01-23 13:00:42 -07:00
|
|
|
width, height = image.size
|
|
|
|
image_aspect = width / height
|
|
|
|
target_wh = min(self.aspects, key=lambda aspects:abs(aspects[0]/aspects[1] - image_aspect))
|
2023-04-14 13:59:28 -06:00
|
|
|
|
2023-02-06 11:11:24 -07:00
|
|
|
self.is_undersized = (width * height) < (target_wh[0] * target_wh[1])
|
2023-01-23 13:00:42 -07:00
|
|
|
self.target_wh = target_wh
|
|
|
|
except Exception as e:
|
|
|
|
self.error = e
|
2022-12-17 20:32:48 -07:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def __autocrop(image: PIL.Image, q=.404):
|
|
|
|
"""
|
|
|
|
crops image to a random square inside small axis using a truncated gaussian distribution across the long axis
|
|
|
|
"""
|
|
|
|
x, y = image.size
|
|
|
|
|
|
|
|
if x != y:
|
2023-01-07 09:29:09 -07:00
|
|
|
if (x > y):
|
|
|
|
rand_x = x - y
|
|
|
|
sigma = max(rand_x * q, 1)
|
2022-12-17 20:32:48 -07:00
|
|
|
else:
|
2023-01-07 09:29:09 -07:00
|
|
|
rand_y = y - x
|
|
|
|
sigma = max(rand_y * q, 1)
|
2022-12-17 20:32:48 -07:00
|
|
|
|
2023-01-07 09:29:09 -07:00
|
|
|
if (x > y):
|
2022-12-17 20:32:48 -07:00
|
|
|
x_crop_gauss = abs(random.gauss(0, sigma))
|
2023-01-07 09:29:09 -07:00
|
|
|
x_crop = min(x_crop_gauss, (x - y) / 2)
|
2022-12-17 20:32:48 -07:00
|
|
|
x_crop = math.trunc(x_crop)
|
|
|
|
y_crop = 0
|
|
|
|
else:
|
|
|
|
y_crop_gauss = abs(random.gauss(0, sigma))
|
|
|
|
x_crop = 0
|
2023-01-07 09:29:09 -07:00
|
|
|
y_crop = min(y_crop_gauss, (y - x) / 2)
|
2022-12-17 20:32:48 -07:00
|
|
|
y_crop = math.trunc(y_crop)
|
2023-01-07 09:29:09 -07:00
|
|
|
|
2022-12-17 20:32:48 -07:00
|
|
|
min_xy = min(x, y)
|
|
|
|
image = image.crop((x_crop, y_crop, x_crop + min_xy, y_crop + min_xy))
|
|
|
|
|
2023-01-24 08:02:12 -07:00
|
|
|
return image
|