forked from maria-korosteleva/GarmentCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpattern_sampler.py
336 lines (269 loc) · 12.5 KB
/
pattern_sampler.py
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
"""
Create a random sample of sewing pattern designs and fit each
to a neutral and a random body shape
"""
from datetime import datetime
from pathlib import Path
import yaml
import shutil
import time
import random
import string
import traceback
import argparse
# Custom
from pygarment.data_config import Properties
from assets.garment_programs.meta_garment import MetaGarment, IncorrectElementConfiguration
from assets.bodies.body_params import BodyParameters
import pygarment as pyg
import assets.garment_programs.stats_utils as stats_utils
def get_command_args():
"""command line arguments to control the run"""
# https://stackoverflow.com/questions/40001892/reading-named-command-arguments
parser = argparse.ArgumentParser()
parser.add_argument('--batch_id', '-b', help='id of a sampling batch', type=int, default=None)
parser.add_argument('--size', '-s', help='size of a sample', type=int, default=10)
parser.add_argument('--name', '-n', help='Name of the dataset', type=str, default='data')
parser.add_argument('--replicate', '-re', help='Name of the dataset to re-generate. If set, other arguments are ignored', type=str, default=None)
args = parser.parse_args()
print('Commandline arguments: ', args)
return args
# Utils
def _create_data_folder(properties, path=Path('')):
""" Create a new directory to put dataset in
& generate appropriate name & update dataset properties
"""
if 'data_folder' in properties: # will this work?
# => regenerating from existing data
properties['name'] = properties['data_folder'] + '_regen'
data_folder = properties['name']
else:
data_folder = properties['name']
# make unique
data_folder += '_' + datetime.now().strftime('%y%m%d-%H-%M-%S')
properties['data_folder'] = data_folder
path_with_dataset = path / data_folder
path_with_dataset.mkdir(parents=True)
default_folder = path_with_dataset / 'default_body'
body_folder = path_with_dataset / 'random_body'
default_folder.mkdir(parents=True, exist_ok=True)
body_folder.mkdir(parents=True, exist_ok=True)
return path_with_dataset, default_folder, body_folder
def gather_body_options(body_path: Path):
objs_path = body_path / 'measurements'
bodies = {}
for file in objs_path.iterdir():
# Get name
b_name = file.stem.split('_')[0]
bodies[b_name] = {}
# Get obj options
bodies[b_name]['objs'] = dict(
straight=f'meshes/{b_name}_straight.obj',
apart=f'meshes/{b_name}_apart.obj', )
# Get measurements
bodies[b_name]['mes'] = f'measurements/{b_name}.yaml'
return bodies
def _id_generator(size=10, chars=string.ascii_uppercase + string.digits):
"""Generate a random string of a given size, see
https://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits
"""
return ''.join(random.choices(chars, k=size))
def body_sample(bodies: dict, path: Path, straight=True):
rand_name = random.sample(list(bodies.keys()), k=1)
body_i = bodies[rand_name[0]]
mes_file = body_i['mes']
obj_file = body_i['objs']['straight'] if straight else body_i['objs']['apart']
body = BodyParameters(path / mes_file)
body.params['body_sample'] = (path / obj_file).stem
return body
def _save_sample(piece, body, new_design, folder, verbose=False):
pattern = piece.assembly()
# Save as json file
folder = pattern.serialize(
folder,
tag='',
to_subfolder=True,
with_3d=False, with_text=False, view_ids=False)
body.save(folder)
with open(Path(folder) / 'design_params.yaml', 'w') as f:
yaml.dump(
{'design': new_design},
f,
default_flow_style=False,
sort_keys=False
)
if verbose:
print(f'Saved {piece.name}')
return pattern
def has_pants(design):
return 'Pants' == design['meta']['bottom']['v']
def gather_visuals(path, verbose=False):
vis_path = Path(path) / 'patterns_vis'
vis_path.mkdir(parents=True, exist_ok=True)
for p in path.rglob("*.png"):
try:
shutil.copy(p, vis_path)
except shutil.SameFileError:
if verbose:
print('File {} already exists'.format(p.name))
pass
# Quality filter
def assert_param_combinations(design, filter_belts=True):
"""Check for some known invalid parameter combinations cases"""
upper_name = design['meta']['upper']['v']
lower_name = design['meta']['bottom']['v']
belt_name = design['meta']['wb']['v']
if upper_name: # No issues with garments that can hang on shoulders
return
# Empty patterns and singular belts
if not lower_name:
if filter_belts or not belt_name:
raise IncorrectElementConfiguration('ERROR::IncorrectParams::Empty pattern or singular belt')
return
# Cases when lower name is present (and maybe a belt):
# All pants and pencils are okay
if lower_name in ['Pants', 'PencilSkirt']:
return
# -- Sliding issues --
# NOTE: Checks are conservative, so some sliding issues might be present nontheless
# Skirt 2 & skirts of top of it -- uses ruffles and belt is too wide if even present
if (lower_name == 'Skirt2'
or lower_name == 'GodetSkirt' and design['godet-skirt']['base']['v'] == 'Skirt2'
or lower_name == 'SkirtLevels' and design['levels-skirt']['base']['v'] == 'Skirt2'
):
if (design['skirt']['ruffle']['v'] > 1 and (not belt_name or design['waistband']['waist']['v'] > 1.)):
raise IncorrectElementConfiguration('ERROR::IncorrectParams::Skirt2 ruffles + belt')
# Flare skirts & skirts on top of it -- no belt + too wide / too long
flare_skirts = ['SkirtCircle', 'AsymmSkirtCircle', 'SkirtManyPanels']
if (lower_name in flare_skirts
or lower_name == 'SkirtLevels' and design['levels-skirt']['base']['v'] in flare_skirts
):
# if Fitted belt of enough width not present -- check if "heavy"
if (not belt_name
or design['waistband']['waist']['v'] > 1.
or design['waistband']['width']['v'] <= 0.25
):
length_param = design['levels-skirt' if lower_name == 'SkirtLevels' else 'flare-skirt']['length']['v']
if length_param > 0.5 or design['flare-skirt']['suns']['v'] > 0.75:
raise IncorrectElementConfiguration('ERROR::IncorrectParams::Flare skirts + belt')
# Generation loop
def generate(path, properties, sys_paths, verbose=False):
"""Generates a synthetic dataset of patterns with given properties
Params:
path : path to folder to put a new dataset into
props : an instance of DatasetProperties class
requested properties of the dataset
"""
path = Path(path)
gen_config = properties['generator']['config']
gen_stats = properties['generator']['stats']
body_samples_path = Path(sys_paths['body_samples_path']) / properties['body_samples']
body_options = gather_body_options(body_samples_path)
# create data folder
data_folder, default_path, body_sample_path = _create_data_folder(properties, path)
default_sample_data = default_path / 'data'
body_sample_data = body_sample_path / 'data'
# init random seed
if 'random_seed' not in gen_config or gen_config['random_seed'] is None:
gen_config['random_seed'] = int(time.time())
print(f'Random seed is {gen_config["random_seed"]}')
random.seed(gen_config['random_seed'])
# generate data
start_time = time.time()
default_body = BodyParameters(Path(sys_paths['bodies_default_path']) / (properties['body_default'] + '.yaml'))
sampler = pyg.DesignSampler(properties['design_file'])
for i in range(properties['size']):
# log properties every time
properties.serialize(data_folder / 'dataset_properties.yaml')
# Redo sampling untill success
for _ in range(100): # Putting a limit on re-tries to avoid infinite loops
new_design = sampler.randomize()
name = f'rand_{_id_generator()}'
try:
if verbose:
print(f'{name} saving design params for debug')
with open(Path('./Logs') / f'{name}_design_params.yaml', 'w') as f:
yaml.dump(
{'design': new_design},
f,
default_flow_style=False,
sort_keys=False
)
# Preliminary checks
assert_param_combinations(new_design)
# On default body
piece_default = MetaGarment(name, default_body, new_design)
piece_default.assert_total_length() # Check final length correctnesss
# Straight/apart legs pose
def_obj_name = properties['body_default']
if has_pants(new_design):
def_obj_name += '_apart'
default_body.params['body_sample'] = def_obj_name
# On random body shape
rand_body = body_sample(
body_options,
body_samples_path,
straight=not has_pants(new_design))
piece_shaped = MetaGarment(name, rand_body, new_design)
piece_shaped.assert_total_length() # Check final length correctness
if piece_default.is_self_intersecting() or piece_shaped.is_self_intersecting():
if verbose:
print(f'{piece_default.name} is self-intersecting!!')
continue # Redo the randomization
# Save samples
pattern = _save_sample(piece_default, default_body, new_design, default_sample_data, verbose=verbose)
_save_sample(piece_shaped, rand_body, new_design, body_sample_data, verbose=verbose)
stats_utils.count_panels(pattern, props)
stats_utils.garment_type(name, new_design, props)
break # Stop generation
except KeyboardInterrupt: # Return immediately with whatever is ready
return default_path, body_sample_path
except BaseException as e:
print(f'{name} failed')
if verbose:
traceback.print_exc()
print(e)
# Check empty folder
if (default_sample_data / name).exists():
print('Generate::Info::Removed empty folder after unsuccessful sampling attempt', default_sample_data / name)
shutil.rmtree(default_sample_data / name, ignore_errors=True)
if (body_sample_data / name).exists():
print('Generate::Info::Removed empty folder after unsuccessful sampling attempt', body_sample_data / name)
shutil.rmtree(body_sample_data / name, ignore_errors=True)
continue
elapsed = time.time() - start_time
gen_stats['generation_time'] = f'{elapsed:.3f} s'
# log properties
props.stats_summary()
properties.serialize(data_folder / 'dataset_properties.yaml')
return default_path, body_sample_path
if __name__ == '__main__':
system_props = Properties('./system.json')
args = get_command_args()
if args.replicate is not None:
props = Properties(
Path(system_props['datasets_path']) / args.replicate / 'dataset_properties.yaml',
True)
else: # New sample
props = Properties()
props.set_basic(
design_file='./assets/design_params/default.yaml',
body_default='mean_all',
body_samples='5000_body_shapes_and_measures',
size=args.size,
name=f'{args.name}_{args.size}' if not args.batch_id else f'{args.name}_{args.size}_{args.batch_id}',
to_subfolders=True)
props.set_section_config('generator')
props.set_section_stats(
'generator',
panel_count={},
garment_types={},
garment_types_summary=dict(main={}, style={})
)
# Generator
default_path, body_sample_path = generate(
system_props['datasets_path'], props, system_props, verbose=False)
# Gather the pattern images separately
gather_visuals(default_path)
gather_visuals(body_sample_path)
print('Data generation completed!')