|
| 1 | +# python 3.7 |
| 2 | +"""Demo.""" |
| 3 | + |
| 4 | +import numpy as np |
| 5 | +import torch |
| 6 | +import streamlit as st |
| 7 | +import SessionState |
| 8 | + |
| 9 | +from models import parse_gan_type |
| 10 | +from utils import to_tensor |
| 11 | +from utils import postprocess |
| 12 | +from utils import load_generator |
| 13 | +from utils import factorize_weight |
| 14 | + |
| 15 | + |
| 16 | +@st.cache(allow_output_mutation=True, show_spinner=False) |
| 17 | +def get_model(model_name): |
| 18 | + """Gets model by name.""" |
| 19 | + return load_generator(model_name) |
| 20 | + |
| 21 | + |
| 22 | +@st.cache(allow_output_mutation=True, show_spinner=False) |
| 23 | +def factorize_model(model, layer_idx): |
| 24 | + """Factorizes semantics from target layers of the given model.""" |
| 25 | + return factorize_weight(model, layer_idx) |
| 26 | + |
| 27 | + |
| 28 | +def sample(model, gan_type, num=1): |
| 29 | + """Samples latent codes.""" |
| 30 | + codes = torch.randn(num, model.z_space_dim).cuda() |
| 31 | + if gan_type == 'pggan': |
| 32 | + codes = model.layer0.pixel_norm(codes) |
| 33 | + elif gan_type == 'stylegan': |
| 34 | + codes = model.mapping(codes)['w'] |
| 35 | + codes = model.truncation(codes, |
| 36 | + trunc_psi=0.7, |
| 37 | + trunc_layers=8) |
| 38 | + elif gan_type == 'stylegan2': |
| 39 | + codes = model.mapping(codes)['w'] |
| 40 | + codes = model.truncation(codes, |
| 41 | + trunc_psi=0.5, |
| 42 | + trunc_layers=18) |
| 43 | + codes = codes.detach().cpu().numpy() |
| 44 | + return codes |
| 45 | + |
| 46 | + |
| 47 | +@st.cache(allow_output_mutation=True, show_spinner=False) |
| 48 | +def synthesize(model, gan_type, code): |
| 49 | + """Synthesizes an image with the give code.""" |
| 50 | + if gan_type == 'pggan': |
| 51 | + image = model(to_tensor(code))['image'] |
| 52 | + elif gan_type in ['stylegan', 'stylegan2']: |
| 53 | + image = model.synthesis(to_tensor(code))['image'] |
| 54 | + image = postprocess(image)[0] |
| 55 | + return image |
| 56 | + |
| 57 | + |
| 58 | +def main(): |
| 59 | + """Main function (loop for StreamLit).""" |
| 60 | + st.title('Closed-Form Factorization of Latent Semantics in GANs') |
| 61 | + st.sidebar.title('Options') |
| 62 | + reset = st.sidebar.button('Reset') |
| 63 | + |
| 64 | + model_name = st.sidebar.selectbox( |
| 65 | + 'Model to Interpret', |
| 66 | + ['stylegan_animeface512', 'stylegan_car512', 'stylegan_cat512', |
| 67 | + 'pggan_celebahq1024']) |
| 68 | + |
| 69 | + model = get_model(model_name) |
| 70 | + gan_type = parse_gan_type(model) |
| 71 | + layer_idx = st.sidebar.selectbox( |
| 72 | + 'Layers to Interpret', |
| 73 | + ['all', '0-1', '2-5', '6-13']) |
| 74 | + layers, boundaries, eigen_values = factorize_model(model, layer_idx) |
| 75 | + |
| 76 | + num_semantics = st.sidebar.number_input( |
| 77 | + 'Number of semantics', value=10, min_value=0, max_value=None, step=1) |
| 78 | + steps = {sem_idx: 0 for sem_idx in range(num_semantics)} |
| 79 | + if gan_type == 'pggan': |
| 80 | + max_step = 5.0 |
| 81 | + elif gan_type == 'stylegan': |
| 82 | + max_step = 2.0 |
| 83 | + elif gan_type == 'stylegan2': |
| 84 | + max_step = 15.0 |
| 85 | + for sem_idx in steps: |
| 86 | + eigen_value = eigen_values[sem_idx] |
| 87 | + steps[sem_idx] = st.sidebar.slider( |
| 88 | + f'Semantic {sem_idx:03d} (eigen value: {eigen_value:.3f})', |
| 89 | + value=0.0, |
| 90 | + min_value=-max_step, |
| 91 | + max_value=max_step, |
| 92 | + step=0.04 * max_step if not reset else 0.0) |
| 93 | + |
| 94 | + image_placeholder = st.empty() |
| 95 | + button_placeholder = st.empty() |
| 96 | + |
| 97 | + try: |
| 98 | + base_codes = np.load(f'latent_codes/{model_name}_latents.npy') |
| 99 | + except FileNotFoundError: |
| 100 | + base_codes = sample(model, gan_type) |
| 101 | + |
| 102 | + state = SessionState.get(model_name=model_name, |
| 103 | + code_idx=0, |
| 104 | + codes=base_codes[0:1]) |
| 105 | + if state.model_name != model_name: |
| 106 | + state.model_name = model_name |
| 107 | + state.code_idx = 0 |
| 108 | + state.codes = base_codes[0:1] |
| 109 | + |
| 110 | + if button_placeholder.button('Random', key=0): |
| 111 | + state.code_idx += 1 |
| 112 | + if state.code_idx < base_codes.shape[0]: |
| 113 | + state.codes = base_codes[state.code_idx][np.newaxis] |
| 114 | + else: |
| 115 | + state.codes = sample(model, gan_type) |
| 116 | + |
| 117 | + code = state.codes.copy() |
| 118 | + for sem_idx, step in steps.items(): |
| 119 | + if gan_type == 'pggan': |
| 120 | + code += boundaries[sem_idx:sem_idx + 1] * step |
| 121 | + elif gan_type in ['stylegan', 'stylegan2']: |
| 122 | + code[:, layers, :] += boundaries[sem_idx:sem_idx + 1] * step |
| 123 | + image = synthesize(model, gan_type, code) |
| 124 | + image_placeholder.image(image / 255.0) |
| 125 | + |
| 126 | + |
| 127 | +if __name__ == '__main__': |
| 128 | + main() |
0 commit comments