forked from Nerogar/OneTrainer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBaseImageCaptionModel.py
More file actions
189 lines (156 loc) · 6.84 KB
/
Copy pathBaseImageCaptionModel.py
File metadata and controls
189 lines (156 loc) · 6.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
import os
from abc import ABCMeta, abstractmethod
from typing import Callable
from PIL import Image
from tqdm import tqdm
from modules.util import path_util
class CaptionSample:
def __init__(self, filename: str):
self.image_filename = filename
self.caption_filename = os.path.splitext(filename)[0] + ".txt"
self.image = None
self.captions = None
self.height = 0
self.width = 0
def get_image(self) -> Image:
if self.image is None:
self.image = Image.open(self.image_filename).convert('RGB')
self.height = self.image.height
self.width = self.image.width
return self.image
def get_caption(self) -> str:
if self.captions is None and os.path.exists(self.caption_filename):
try:
with open(self.caption_filename, "r") as f:
self.captions = [line.strip() for line in f.readlines() if len(line.strip()) > 0]
except:
self.captions = []
return self.captions
def set_caption(self, caption: str):
self.captions = [caption]
def add_caption(self, caption: str):
self.captions.append(caption)
def save_caption(self):
if self.captions is not None:
try:
with open(self.caption_filename, "w", encoding='utf-8') as f:
f.write('\n'.join(self.captions))
except:
pass
class BaseImageCaptionModel(metaclass=ABCMeta):
@staticmethod
def __get_sample_filenames(sample_dir: str, include_subdirectories: bool = False) -> [str]:
def __is_supported_image_extension(filename: str) -> bool:
ext = os.path.splitext(filename)[1]
return path_util.is_supported_image_extension(ext) and '-masklabel.png' not in filename
filenames = []
if include_subdirectories:
for root, _, files in os.walk(sample_dir):
for filename in files:
if __is_supported_image_extension(filename):
filenames.append(os.path.join(root, filename))
else:
for filename in os.listdir(sample_dir):
if __is_supported_image_extension(filename):
filenames.append(os.path.join(sample_dir, filename))
return filenames
@abstractmethod
def generate_caption(
self,
caption_sample: CaptionSample,
initial_caption: str = "",
) -> str:
"""
Generates caption for a single CaptionSample
Args:
caption_sample (`CaptionSample`): the sample to caption
initial_caption (`str`): the initial caption
Returns: the generated caption
"""
pass
def caption_image(
self,
filename: str,
initial_caption: str = "",
mode: str = 'fill',
):
"""
Captions a sample
Parameters:
filename (`str`): a sample filename
initial_caption (`str`): an initial caption. the generated caption will start with this string
mode (`str`): can be one of
- replace: creates a new caption for all samples, even if a caption already exists
- fill: creates a new caption for all samples without a caption
- add: creates a new caption for all samples, appending if a caption already exists
"""
caption_sample = CaptionSample(filename)
existing_caption = caption_sample.get_caption()
if mode == 'fill' and existing_caption is not None and existing_caption != "":
return
predicted_caption = self.generate_caption(caption_sample, initial_caption)
if mode == 'replace' or mode == 'fill':
caption_sample.set_caption(predicted_caption)
if mode == 'add':
caption_sample.add_caption(predicted_caption)
caption_sample.save_caption()
def caption_images(
self,
filenames: [str],
initial_caption: str = "",
mode: str = 'fill',
progress_callback: Callable[[int, int], None] = None,
error_callback: Callable[[str], None] = None,
):
"""
Captions all samples in a list
Parameters:
filenames (`[str]`): a list of sample filenames
initial_caption (`str`): an initial caption. the generated caption will start with this string
mode (`str`): can be one of
- replace: creates a new caption for all samples, even if a caption already exists
- fill: creates a new caption for all samples without a caption
- add: creates a new caption for all samples, appending if a caption already exists
progress_callback (`Callable[[int, int], None]`): called after every processed image
error_callback (`Callable[[str], None]`): called for every exception
"""
if progress_callback is not None:
progress_callback(0, len(filenames))
for i, filename in enumerate(tqdm(filenames)):
try:
self.caption_image(filename, initial_caption, mode)
except Exception as e:
if error_callback is not None:
error_callback(filename)
if progress_callback is not None:
progress_callback(i + 1, len(filenames))
def caption_folder(
self,
sample_dir: str,
initial_caption: str = "",
mode: str = 'fill',
progress_callback: Callable[[int, int], None] = None,
error_callback: Callable[[str], None] = None,
include_subdirectories: bool = False,
):
"""
Captions all samples in a folder
Parameters:
sample_dir (`str`): directory where samples are located
initial_caption (`str`): an initial caption. the generated caption will start with this string
mode (`str`): can be one of
- replace: creates a new caption for all samples, even if a caption already exists
- fill: creates a new caption for all samples without a caption
- add: creates a new caption for all samples, appending if a caption already exists
progress_callback (`Callable[[int, int], None]`): called after every processed image
error_callback (`Callable[[str], None]`): called for every exception
include_subdirectories (`bool`): whether to include subfolders when processing samples
"""
filenames = self.__get_sample_filenames(sample_dir, include_subdirectories)
self.caption_images(
filenames=filenames,
initial_caption=initial_caption,
mode=mode,
progress_callback=progress_callback,
error_callback=error_callback,
)