File size: 10,229 Bytes
ca56d10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Batch vectorization script.
Reads images recursively from sample_inputs/simplified/<subdir>/<img>.png
and outputs to outputs/sampling/simplified/<subdir>/<img_basename>/

Reuses the core inference logic from test_vectorization.py but loads the model
ONCE and runs many images in the same TF session to amortize startup time.
"""
import os
import sys
import time
import argparse
import numpy as np

# Limit TF/numpy thread counts BEFORE importing TF, so they take effect.
# Each shard worker should only use a fraction of the CPU cores to avoid
# contention when running many shards in parallel.
_NUM_THREADS = os.environ.get('VS_NUM_THREADS', '')
if _NUM_THREADS:
    for _v in ['OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS',
               'NUMEXPR_NUM_THREADS', 'TF_NUM_INTRAOP_THREADS',
               'TF_NUM_INTEROP_THREADS']:
        os.environ.setdefault(_v, _NUM_THREADS)

import tensorflow as tf
from PIL import Image

import hyper_parameters as hparams
from model_common_test import DiffPastingV3, VirtualSketchingModel
from utils import (reset_graph, load_checkpoint, update_hyperparams,
                   save_seq_data, draw_strokes)
from dataset_utils import GeneralRawDataLoader, copy_hparams

# import sample() function from test_vectorization
from test_vectorization import sample as sample_vectorization

os.environ['CUDA_VISIBLE_DEVICES'] = os.environ.get('CUDA_VISIBLE_DEVICES', '0')


def collect_inputs(input_root):
    """Walk input_root and collect all PNG/JPG files, returning
    list of (relative_subdir, filename, full_path)."""
    items = []
    for dirpath, _, files in os.walk(input_root):
        rel_subdir = os.path.relpath(dirpath, input_root)
        for f in sorted(files):
            if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp')):
                items.append((rel_subdir, f, os.path.join(dirpath, f)))
    return items


def build_eval_hparams(model_base_dir, model_name):
    """Create the eval/sample hparams matching what the loaded checkpoint expects."""
    model_params_default = hparams.get_default_hparams_clean()
    # update_hyperparams reads the saved model_config.json under model_dir
    model_params = update_hyperparams(
        model_params_default, model_base_dir, model_name,
        infer_dataset='clean_line_drawings')

    eval_model_params = copy_hparams(model_params)
    eval_model_params.use_input_dropout = 0
    eval_model_params.use_recurrent_dropout = 0
    eval_model_params.use_output_dropout = 0
    eval_model_params.batch_size = 1
    eval_model_params.model_mode = 'sample'

    sample_model_params = copy_hparams(eval_model_params)
    sample_model_params.batch_size = 1
    sample_model_params.max_seq_len = 1

    return eval_model_params, sample_model_params


def process_one_image(sess, sampling_model, paste_v3_func,
                      image_path, eval_hps, sample_hps,
                      out_dir, image_basename,
                      longer_infer_lens, state_dependent,
                      round_stop_state_num, stroke_acc_threshold,
                      draw_seq=False, draw_color_order=True):
    """Run inference for one image and dump outputs into out_dir."""
    os.makedirs(out_dir, exist_ok=True)

    test_set = GeneralRawDataLoader(image_path, eval_hps.raster_size,
                                    test_dataset='clean_line_drawings')

    input_photos, init_cursors, test_image_size = test_set.get_test_image()
    # input_photos: (1, image_size, image_size), [0-stroke, 1-BG]

    if init_cursors.ndim == 3:
        init_cursors = np.expand_dims(init_cursors, axis=0)

    input_photos = input_photos[0:1, :, :]
    ori_img = (input_photos.copy()[0] * 255.0).astype(np.uint8)
    ori_img = np.stack([ori_img for _ in range(3)], axis=2)
    Image.fromarray(ori_img, 'RGB').save(
        os.path.join(out_dir, image_basename + '_input.png'), 'PNG')

    (strokes_raw_out_list, states_raw_out_list, states_soft_out_list,
     pred_imgs_out, window_size_out_list, round_new_cursors,
     round_new_lengths) = sample_vectorization(
        sess, sampling_model, input_photos, init_cursors, test_image_size,
        eval_hps.max_seq_len, longer_infer_lens, state_dependent,
        paste_v3_func, round_stop_state_num, stroke_acc_threshold)

    best_result_idx = 0
    strokes_raw_out = np.stack(strokes_raw_out_list[best_result_idx], axis=0)

    multi_cursors = [init_cursors[0, best_result_idx, 0]]
    for c_i in range(len(round_new_cursors)):
        multi_cursors.append(round_new_cursors[c_i][best_result_idx, 0])

    save_seq_data(out_dir, image_basename + '_0',
                  strokes_raw_out, multi_cursors,
                  test_image_size, round_new_lengths, eval_hps.min_width)

    draw_strokes(strokes_raw_out, out_dir, image_basename + '_0_pred.png',
                 ori_img, test_image_size,
                 multi_cursors, round_new_lengths,
                 eval_hps.min_width, eval_hps.cursor_type,
                 sample_hps.raster_size, sample_hps.min_window_size,
                 sess, pasting_func=paste_v3_func,
                 save_seq=draw_seq, draw_order=draw_color_order)

    return strokes_raw_out.shape[0]  # number of strokes


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--input_root', type=str,
                        default='sample_inputs/simplified',
                        help="Root directory of input images.")
    parser.add_argument('--output_root', type=str,
                        default='outputs/sampling/simplified',
                        help="Root directory for outputs.")
    parser.add_argument('--model', type=str,
                        default='pretrain_clean_line_drawings')
    parser.add_argument('--model_base_dir', type=str,
                        default='outputs/snapshot')
    parser.add_argument('--progress_log', type=str,
                        default='outputs/sampling/simplified/_progress.log')
    parser.add_argument('--skip_existing', action='store_true', default=True)
    parser.add_argument('--shard', type=str, default='0/1',
                        help="Shard spec 'i/N': this worker processes items "
                             "where index%%N == i (0-indexed).")
    args = parser.parse_args()

    # Parse shard
    try:
        shard_i, shard_n = (int(x) for x in args.shard.split('/'))
    except Exception:
        raise SystemExit("--shard must look like '0/8'")
    assert 0 <= shard_i < shard_n, "Bad shard"

    # Hyper-params equivalent to test_vectorization.main()
    state_dependent = False
    longer_infer_lens = [500 for _ in range(10)]
    round_stop_state_num = 12
    stroke_acc_threshold = 0.95

    np.set_printoptions(precision=8, edgeitems=6, linewidth=200, suppress=True)

    items = collect_inputs(args.input_root)
    print('Found {} images under {}'.format(len(items), args.input_root))

    # Apply shard filter
    items = [it for idx, it in enumerate(items) if idx % shard_n == shard_i]
    print('Shard {}/{} -> {} images'.format(shard_i, shard_n, len(items)))

    # Build hparams + model ONCE
    eval_hps, sample_hps = build_eval_hparams(args.model_base_dir, args.model)

    reset_graph()
    sampling_model = VirtualSketchingModel(sample_hps)
    paste_v3_func = DiffPastingV3(sample_hps.raster_size)

    tfconfig = tf.ConfigProto()
    tfconfig.gpu_options.allow_growth = True
    if _NUM_THREADS:
        n = int(_NUM_THREADS)
        tfconfig.intra_op_parallelism_threads = n
        tfconfig.inter_op_parallelism_threads = n
    sess = tf.InteractiveSession(config=tfconfig)
    sess.run(tf.global_variables_initializer())

    model_dir = os.path.join(args.model_base_dir, args.model)
    snapshot_step = load_checkpoint(sess, model_dir, gen_model_pretrain=True)
    print('Loaded snapshot_step:', snapshot_step)

    # Per-shard progress log
    progress_log = args.progress_log
    if shard_n > 1:
        base, ext = os.path.splitext(progress_log)
        progress_log = '{}.shard{}of{}{}'.format(base, shard_i, shard_n, ext)
    os.makedirs(os.path.dirname(progress_log), exist_ok=True)
    log_f = open(progress_log, 'a', buffering=1)
    log_f.write('=== run started at {} (shard {}/{}) ===\n'.format(
        time.strftime('%F %T'), shard_i, shard_n))
    log_f.write('total_images={}\n'.format(len(items)))

    total_time = 0.0
    done = 0
    failed = []

    for idx, (rel_subdir, fname, full_path) in enumerate(items, 1):
        basename = os.path.splitext(fname)[0]
        out_dir = os.path.join(args.output_root, rel_subdir, basename)

        # Skip if already done
        if args.skip_existing and os.path.exists(
                os.path.join(out_dir, basename + '_0_pred.png')):
            print('[{}/{}] SKIP (exists): {}'.format(idx, len(items), full_path))
            continue

        t0 = time.time()
        try:
            num_strokes = process_one_image(
                sess, sampling_model, paste_v3_func,
                full_path, eval_hps, sample_hps,
                out_dir, basename,
                longer_infer_lens, state_dependent,
                round_stop_state_num, stroke_acc_threshold)
            elapsed = time.time() - t0
            total_time += elapsed
            done += 1
            avg = total_time / done
            line = ('[{}/{}] OK  {:.1f}s  strokes={}  avg={:.1f}s  {}\n'
                    .format(idx, len(items), elapsed, num_strokes, avg, full_path))
            print(line, end='')
            log_f.write(line)
        except Exception as e:
            elapsed = time.time() - t0
            line = ('[{}/{}] FAIL {:.1f}s  {}  err={}\n'
                    .format(idx, len(items), elapsed, full_path, repr(e)))
            print(line, end='')
            log_f.write(line)
            failed.append(full_path)

    summary = ('\n=== Done. processed={}, failed={}, total_time={:.1f}s, '
               'avg={:.2f}s/img ===\n').format(
                done, len(failed), total_time,
                total_time / max(done, 1))
    print(summary)
    log_f.write(summary)
    if failed:
        log_f.write('Failed files:\n')
        for f in failed:
            log_f.write('  ' + f + '\n')
    log_f.close()


if __name__ == '__main__':
    main()