summaryrefslogtreecommitdiff
path: root/cli/app/search/live.py
blob: 14f1ad35ceb1f0ea44c5d3ecb757bd166aa3df2b (plain)
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import sys
import glob
import h5py
import numpy as np
import json
import tensorflow as tf
import tensorflow_probability as tfp
import tensorflow_hub as hub
import time
import random
from scipy.stats import truncnorm
from PIL import Image
from urllib.parse import parse_qs
import app.search.visualize as vs
from app.search.json import params_dense_dict
from app.utils.file_utils import load_pickle
from app.settings import app_cfg
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../../../live-cortex/rpc/'))
from rpc import CortexRPC
from app.search.params import timestamp
from app.utils.tf_utils import read_checkpoint

FPS = 25

params = params_dense_dict('live')

# --------------------------
# Make directories.
# --------------------------
tag = "test"
OUTPUT_DIR = os.path.join('output', tag)
if not os.path.exists(OUTPUT_DIR):
  os.makedirs(OUTPUT_DIR)

# --------------------------
# Load Graph.
# --------------------------
print("Loading module...")
generator = hub.Module(str(params.generator_path))
print("Loaded!")

gen_signature = 'generator'
if 'generator' not in generator.get_signature_names():
  gen_signature = 'default'

input_info = generator.get_input_info_dict(gen_signature)

BATCH_SIZE = 1
Z_DIM = input_info['z'].get_shape().as_list()[1]
N_CLASS = input_info['y'].get_shape().as_list()[1]

# --------------------------
# Utils
# --------------------------

def clamp(n, a=0, b=1):
  if n < a:
    return a
  if n > b:
    return b
  return n

# --------------------------
# Initializers
# --------------------------

def label_sampler(num_classes=1, shape=(BATCH_SIZE, N_CLASS,)):
  label = np.zeros(shape)
  for i in range(shape[0]):
    for _ in range(int(num_classes)):
      j = random.randint(0, shape[1]-1)
      label[i, j] = random.random()
    label[i] /= label[i].sum()
  return label

def truncated_z_sample(shape=(BATCH_SIZE, Z_DIM,), truncation=1.0):
  values = truncnorm.rvs(-2, 2, size=shape)
  return truncation * values

def normal_z_sample(shape=(BATCH_SIZE, Z_DIM,)):
  return np.random.normal(size=shape)

# --------------------------
# Disentangled Latents
# --------------------------

disentangled = {
  'zoom': read_checkpoint(os.path.join(app_cfg.DISENTANGLED, 'zoom/model.ckpt'), 'walk')[0],
  'shiftx': read_checkpoint(os.path.join(app_cfg.DISENTANGLED, 'shiftx/model.ckpt'), 'walk')[0],
  'shifty': read_checkpoint(os.path.join(app_cfg.DISENTANGLED, 'shifty/model.ckpt'), 'walk')[0],
  'rotate2d': read_checkpoint(os.path.join(app_cfg.DISENTANGLED, 'rotate2d/model.ckpt'), 'walk')[0],
  'rotate3d': read_checkpoint(os.path.join(app_cfg.DISENTANGLED, 'rotate3d/model.ckpt'), 'walk')[0],
}
disentangled_color = read_checkpoint(os.path.join(app_cfg.DISENTANGLED, 'rotate2d/model.ckpt'), 'walk')[0]
disentangled['r'] = disentangled_color[:, 0]
disentangled['g'] = disentangled_color[:, 1]
disentangled['b'] = disentangled_color[:, 2]
disentangled['luminance'] = np.sum(disentangled_color, axis=1)

# --------------------------
# More complex ops
# --------------------------

class SinParam:
  def __init__(self, name, shape, datatype="noise"):
    noise = LerpParam(name + '_noise', shape=shape, datatype=datatype)
    orbit_radius = InterpolatorParam(name=name + '_radius', value=0.25)
    orbit_speed = InterpolatorParam(name=name + '_speed', value=FPS)
    orbit_time = InterpolatorParam(name=name + '_time', value=0.0)
    output = tf.math.sin(orbit_time.variable + noise.output) * orbit_radius.variable
    interpolator.sin_params[name] = self
    self.name = name
    self.orbit_speed = orbit_speed
    self.orbit_time = orbit_time
    self.output = output

  def update(self, dt):
    self.orbit_time.value += self.orbit_speed.value / FPS * dt

class LerpParam:
  def __init__(self, name, shape, a_in=None, b_in=None, datatype="noise"):
    if a_in is not None and b_in is not None:
      a = InterpolatorVariable(variable=a_in)
      b = InterpolatorVariable(variable=b_in)
    else:
      a = InterpolatorParam(name=name + '_a', shape=shape, datatype=datatype)
      b = InterpolatorParam(name=name + '_b', shape=shape, datatype=datatype)
    n = InterpolatorParam(name=name + '_n', value=0.0)
    speed = InterpolatorParam(name=name + '_speed', value=FPS)
    output = a.variable * (1 - n.variable) + b.variable * n.variable
    interpolator.lerp_params[name] = self
    self.name = name
    self.a = a
    self.b = b
    self.n = n
    self.speed = speed
    self.output = output
    self.direction = 0

  def switch(self, target_value=None):
    if self.n.value > 0.5:
      target_param = self.a
      self.direction = -1
    else:
      target_param = self.b
      self.direction = 1
    if target_value is None:
      target_param.randomize()
    else:
      target_param.assign(target_value)

  def update(self, dt):
    if self.direction != 0:
      self.n.value = clamp(self.n.value + self.direction * self.speed.value / FPS * dt)
      print("set_opt: {}_n {}".format(self.name, self.n.value))
      if self.n.value == 0 or self.n.value == 1:
        self.direction = 0

# --------------------------
# Placeholder params
# --------------------------

class InterpolatorParam:
  def __init__(self, name, dtype=tf.float32, shape=(), value=None, datatype="float"):
    self.scalar = shape == ()
    self.shape = shape
    self.datatype = datatype
    if datatype == "float":
      self.assign(value or 0.0)
    else:
      self.randomize()
    self.variable = tf.placeholder(dtype=dtype, shape=shape)
    interpolator.opts[name] = self

  def assign(self, value):
    if self.datatype == 'float':
      self.value = float(value)
    else:
      self.value = value

  def randomize(self):
    if self.datatype == 'noise':
      val = truncated_z_sample(shape=self.shape, truncation=interpolator.opts['truncation'].value)
    elif self.datatype == 'label':
      val = label_sampler(shape=self.shape, num_classes=interpolator.opts['num_classes'].value)
    elif self.datatype == 'encoding':
      val = np.zeros(self.shape)
    else:
      val = 0.0
    self.assign(val)

class InterpolatorVariable:
  def __init__(self, variable):
    self.scalar = False
    self.variable = variable

  def assign(self):
    pass

  def randomize(self):
    pass

# --------------------------
# Interpolator graph
# --------------------------

class Interpolator:
  def __init__(self):
    self.opts = {}
    self.sin_params = {}
    self.lerp_params = {}

  def build(self):
    InterpolatorParam(name='truncation', value=1.0)
    InterpolatorParam(name='num_classes', value=1.0)

    # Latent - initial lerp and wobble
    lerp_z = LerpParam('latent', shape=[BATCH_SIZE, Z_DIM], datatype="noise")
    sin_z = SinParam('orbit', shape=[BATCH_SIZE, Z_DIM], datatype="noise")
    z_sum = lerp_z.output + sin_z.output

    # Latent - saturation
    abs_zoom = InterpolatorParam(name='abs_zoom', value=1.0)
    z_abs = z_sum / tf.abs(z_sum) * abs_zoom.variable
    z_mix = LerpParam('abs_mix', a_in=z_sum, b_in=z_abs, shape=[BATCH_SIZE, Z_DIM], datatype="input")

    # Latent - disentangled vectors
    zoom = InterpolatorParam(name='zoom', value=0.0).variable * disentangled['zoom']
    shiftx = InterpolatorParam(name='shiftx', value=0.0).variable * disentangled['shiftx']
    shifty = InterpolatorParam(name='shifty', value=0.0).variable * disentangled['shifty']
    luminance = InterpolatorParam(name='luminance', value=0.0).variable * disentangled['luminance']
    disentangled = z_mix.output + zoom + shiftx + shifty + luminance

    # Latent - stored vector
    latent_stored = LerpParam(name='latent_stored', shape=[BATCH_SIZE, Z_DIM], datatype="noise")
    latent_stored_mix = LerpParam('latent_stored_mix', a_in=disentangled, b_in=latent_stored.output, shape=[BATCH_SIZE, Z_DIM], datatype="input")

    # Label
    lerp_label = LerpParam('label', shape=[BATCH_SIZE, N_CLASS], datatype="label")

    # Latent - stored vector
    label_stored = LerpParam(name='label_stored', shape=[BATCH_SIZE, N_CLASS], datatype="label")
    label_stored_mix = LerpParam('label_stored_mix', a_in=lerp_label.output, b_in=label_stored.output, shape=[BATCH_SIZE, Z_DIM], datatype="input")

    # Generator
    gen_in = {}
    gen_in['truncation'] = 1.0 # self.opts['truncation'].variable
    gen_in['z'] = latent_stored_mix.output
    gen_in['y'] = label_stored_mix.output
    self.gen_img = generator(gen_in, signature=gen_signature)

    # Encoding - first hidden layer
    gen_layer_name = 'module_apply_' + gen_signature + '/' + params.inv_layer
    encoding_latent = tf.get_default_graph().get_tensor_by_name(gen_layer_name)

    encoding_shape = encoding_latent.get_shape().as_list()
    encoding_shape_np = tuple([1,] + encoding_shape[1:])

    encoding_shape_placeholder = tf.constant(np.zeros(encoding_shape_np, dtype=np.float32))
    encoding_stored = LerpParam('encoding_stored', shape=encoding_shape_np, datatype="encoding")
    encoding_stored_mix = LerpParam('encoding_stored_mix', a_in=encoding_shape_placeholder, b_in=encoding_stored.output, shape=encoding_shape_np, datatype="encoding")

    # Use the placeholder to redirect parts of the graph.
    # - computed encoding goes into the encoding_mix
    # - encoding mix output goes into the main biggan graph
    # We do it this way so the encoding_latent won't be going into two places at once.
    tf.contrib.graph_editor.swap_ts(encoding_shape_placeholder, encoding_latent)
    tf.contrib.graph_editor.swap_ts(encoding_stored_mix.output, encoding_shape_placeholder)

    # Make all the stored lerps use the same interpolation amount.
    tf.contrib.graph_editor.reroute_ts(encoding_stored.n.variable, latent_stored.n.variable)
    tf.contrib.graph_editor.reroute_ts(encoding_stored.n.variable, label_stored.n.variable)
    tf.contrib.graph_editor.reroute_ts(encoding_stored_mix.n.variable, latent_stored_mix.n.variable)
    tf.contrib.graph_editor.reroute_ts(encoding_stored_mix.n.variable, label_stored_mix.n.variable)

    sys.stderr.write("Sin params: {}\n".format(", ".join(self.sin_params.keys())))
    sys.stderr.write("Lerp params: {}\n".format(", ".join(self.lerp_params.keys())))
    sys.stderr.write("Opts: {}\n".format(", ".join(self.opts.keys())))

  def get_feed_dict(self):
    opt = {}
    for param in self.opts.values():
      opt[param.variable] = param.value
    return opt

  def get_state(self):
    opt = {}
    for key, param in self.opts.items():
      if param.scalar:
        if type(param.value) is np.ndarray:
          sys.stderr.write('{} is ndarray\n'.format(key))
          opt[key] = param.value.tolist()
        else:
          opt[key] = param.value
    return opt

  def set_value(self, key, value):
    if key in self.opts:
      self.opts[key].assign(float(value))
    else:
      sys.stderr.write('{} not a valid option\n'.format(key))

  def set_category(self, category):
    print("Set category: {}".format(category))
    categories = category.split(" ")
    label = np.zeros((BATCH_SIZE, N_CLASS,))
    for category in categories:
      index = int(category)
      if index > 0 and index < N_CLASS:
        label[0, index] = 1.0
    label[0] /= label[0].sum()
    self.lerp_params['label'].switch(target_value=label)

  def set_encoding(self, opt):
    next_id = opt['id']
    data = load_pickle(os.path.join(app_cfg.DIR_VECTORS, "file_{}.pkl".format(next_id)))
    
    new_encoding = np.expand_dims(data['encoding'], axis=0)
    new_label = np.expand_dims(data['label'], axis=0)
    new_latent = np.expand_dims(data['latent'], axis=0)

    latent_stored = self.lerp_params['latent_stored']
    label_stored = self.lerp_params['label_stored']
    encoding_stored = self.lerp_params['encoding_stored']
    encoding_stored_mix = self.lerp_params['encoding_stored_mix']

    # if we're showing an encoding already, lerp to the next one
    if encoding_stored_mix.n.value > 0:
      encoding_stored.switch(target_value=new_encoding)
      label_stored.switch(target_value=new_label)
      latent_stored.switch(target_value=new_latent)
    # otherwise (we're showing the latent)...
    else:
      # jump to the stored encoding, then switch
      if encoding_stored.n.value < 0.5:
        encoding_stored.n.assign(0)
        encoding_stored.a.assign(new_encoding)
        latent_stored.a.assign(new_latent)
        label_stored.a.assign(new_label)
      else:
        encoding_stored.n.assign(1)
        encoding_stored.b.assign(new_encoding)
        latent_stored.b.assign(new_latent)
        label_stored.b.assign(new_label)
      encoding_stored_mix.switch()

  def on_step(self, i, dt, sess):
    for param in self.sin_params.values():
      param.update(dt)
    for param in self.lerp_params.values():
      param.update(dt)
    gen_images = sess.run(self.gen_img, feed_dict=self.get_feed_dict())
    return gen_images

  def run(self, cmd, payload):
    print("Command: {} {}".format(cmd, payload))
    if cmd == 'switch' and payload in self.lerp_params:
      self.lerp_params[payload].switch()
    if cmd == 'setCategory':
      self.set_category(payload)
    if cmd == 'setEncoding':
      self.set_encoding(json.loads(payload))
    pass

# --------------------------
# RPC Listener
# --------------------------

interpolator = Interpolator()

class Listener:
  def connect(self):
    self.rpc_client = CortexRPC(self.on_get, self.on_set, self.on_ready, self.on_cmd)

  def on_set(self, key, value):
    print("{}: {} {}".format(key, str(type(value)), value))
    interpolator.set_value(key, value)

  def on_get(self):
    state = interpolator.get_state()
    sys.stderr.write(json.dumps(state) + "\n")
    sys.stderr.flush()
    return state

  def on_cmd(self, cmd, payload):
    print("got command {}".format(cmd))
    interpolator.run(cmd, payload)

  def on_ready(self, rpc_client):
    self.rpc_client = rpc_client
    print("Starting session...")
    self.sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))
    self.sess.run(tf.global_variables_initializer())
    self.sess.run(tf.tables_initializer())
    print("Building interpolator...")
    interpolator.build()
    self.rpc_client.send_status('processing', True)
    tag = "biggan_" + timestamp()
    path_out = os.path.join(app_cfg.DIR_RESULTS, tag)
    os.makedirs(path_out, exist_ok=True)
    dt = 1 / FPS
    for i in range(99999):
      if i == 0:
        print("Loading network...")
      elif i == 1:
        print("Processing!")
      gen_time = time.time()
      gen_images = interpolator.on_step(i, dt, self.sess)
      if gen_images is None:
        print("Exiting...")
        break
      if (i % 100) == 0 or i == 1:
        print("Step {}. Generation time: {:.2f}s".format(i, time.time() - gen_time))
      out_img = vs.data2pil(gen_images[0])
      if out_img is not None:
        out_img.save(os.path.join(path_out, "frame_{:05d}.png".format(i)), format='png')
        img_to_send = out_img.resize((256, 256), Image.BICUBIC)
        meta = {
          'i': i,
          'sequence_i': i,
          'skip_i': 0,
          'sequence_len': 99999,
        }
        self.rpc_client.send_pil_image("frame_{:05d}.png".format(i+1), meta, img_to_send, 'jpg')
    self.rpc_client.send_status('processing', False)
    self.sess.close()