import matplotlib
matplotlib.use('Agg')
import torch
from torch import nn
from Generator import Generator
import psp_encoders as psp_enc

# modified from https://github.com/eladrich/pixel2style2pixel/blob/master/models/psp.py

def get_keys(d, name):
    if 'state_dict' in d:
        d = d['state_dict']
    d_filt = {k[len(name) + 1:]:v for k, v in d.items() if k[:len(name)] == name}
    return d_filt


class MypSp(nn.Module):

    def __init__(self, opts):
        super(MypSp, self).__init__()
        self.set_opts(opts)
        self.encoder = psp_enc.MyHairEncoderGradualStyleWPlus(50, 'ir_se', self.opts)
        self.decoder = Generator(1024, 512, 8).to(self.opts.device)
        self.face_pool = torch.nn.AdaptiveAvgPool2d((256, 256))
        self.load_weights()

    def load_weights(self):
        print('Loading pSp from checkpoint: {}'.format(self.opts.checkpoint_path))
        ckpt = torch.load((self.opts.checkpoint_path), map_location='cpu')
        enc = get_keys(ckpt, 'encoder')
        self.encoder.load_state_dict(enc, strict=True)
        self.decoder.load_state_dict((get_keys(ckpt, 'decoder')), strict=True)

    def forward(self, face, hair, resize=True, randomize_noise=True, inject_latent=None, return_latents=False):
        codes = self.encoder(face, hair)
        input_is_latent = True
        images, result_latent = self.decoder([codes], input_is_latent=input_is_latent,
          randomize_noise=randomize_noise,
          return_latents=return_latents)
        if resize:
            images = self.face_pool(images)
        if return_latents:
            return (images, result_latent)
        else:
            return images

    def set_opts(self, opts):
        self.opts = opts

    def forw_from_codes(self, codes, resize=True, randomize_noise=True, inject_latent=None, return_latents=False):
        input_is_latent = True
        images, result_latent = self.decoder([codes], input_is_latent=input_is_latent,
          randomize_noise=randomize_noise,
          return_latents=return_latents)
        if resize:
            images = self.face_pool(images)
        if return_latents:
            return (images, result_latent)
        else:
            return images

    def forward_v_i(self, face_vec, hair_im, resize=False, randomize_noise=True, inject_latent=None, return_latents=False):
        codes = self.encoder.forward_vec_im(face_vec, hair_im)
        return self.forw_from_codes(codes, resize, randomize_noise, inject_latent, return_latents)

    def forward_i_v(self, face_im, hair_vec, resize=False, randomize_noise=True, inject_latent=None, return_latents=False):
        codes = self.encoder.forward_im_vec(face_im, hair_vec)
        return self.forw_from_codes(codes, resize, randomize_noise, inject_latent, return_latents)

    def forward_v_v(self, face_vec, hair_vec, resize=False, randomize_noise=True, inject_latent=None, return_latents=False):
        codes = self.encoder.forward_vec_vec(face_vec, hair_vec)
        return self.forw_from_codes(codes, resize, randomize_noise, inject_latent, return_latents)

    def get_embedding(self, input_im, is_face):
        return self.encoder.get_embedding(input_im, is_face)

import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from collections import namedtuple
from torch.nn import Linear, Conv2d, BatchNorm2d, PReLU, ReLU, Sigmoid, MaxPool2d, AdaptiveAvgPool2d, Sequential, Module

# code borrowed from https://github.com/eladrich/pixel2style2pixel

from Generator import EqualLinear

class Flatten(Module):
	def forward(self, input):
		return input.view(input.size(0), -1)


class Bottleneck(namedtuple('Block', ['in_channel', 'depth', 'stride'])):
	""" A named tuple describing a ResNet block. """


def get_block(in_channel, depth, num_units, stride=2):
	return [Bottleneck(in_channel, depth, stride)] + [Bottleneck(depth, depth, 1) for i in range(num_units - 1)]

def get_blocks(num_layers):
	if num_layers == 50:
		blocks = [
			get_block(in_channel=64, depth=64, num_units=3),
			get_block(in_channel=64, depth=128, num_units=4),
			get_block(in_channel=128, depth=256, num_units=14),
			get_block(in_channel=256, depth=512, num_units=3)
		]
	elif num_layers == 100:
		blocks = [
			get_block(in_channel=64, depth=64, num_units=3),
			get_block(in_channel=64, depth=128, num_units=13),
			get_block(in_channel=128, depth=256, num_units=30),
			get_block(in_channel=256, depth=512, num_units=3)
		]
	elif num_layers == 152:
		blocks = [
			get_block(in_channel=64, depth=64, num_units=3),
			get_block(in_channel=64, depth=128, num_units=8),
			get_block(in_channel=128, depth=256, num_units=36),
			get_block(in_channel=256, depth=512, num_units=3)
		]
	else:
		raise ValueError("Invalid number of layers: {}. Must be one of [50, 100, 152]".format(num_layers))
	return blocks



class SEModule(Module):
	def __init__(self, channels, reduction):
		super(SEModule, self).__init__()
		self.avg_pool = AdaptiveAvgPool2d(1)
		self.fc1 = Conv2d(channels, channels // reduction, kernel_size=1, padding=0, bias=False)
		self.relu = ReLU(inplace=True)
		self.fc2 = Conv2d(channels // reduction, channels, kernel_size=1, padding=0, bias=False)
		self.sigmoid = Sigmoid()

	def forward(self, x):
		module_input = x
		x = self.avg_pool(x)
		x = self.fc1(x)
		x = self.relu(x)
		x = self.fc2(x)
		x = self.sigmoid(x)
		return module_input * x


class bottleneck_IR(Module):
	def __init__(self, in_channel, depth, stride):
		super(bottleneck_IR, self).__init__()
		if in_channel == depth:
			self.shortcut_layer = MaxPool2d(1, stride)
		else:
			self.shortcut_layer = Sequential(
				Conv2d(in_channel, depth, (1, 1), stride, bias=False),
				BatchNorm2d(depth)
			)
		self.res_layer = Sequential(
			BatchNorm2d(in_channel),
			Conv2d(in_channel, depth, (3, 3), (1, 1), 1, bias=False), PReLU(depth),
			Conv2d(depth, depth, (3, 3), stride, 1, bias=False), BatchNorm2d(depth)
		)

	def forward(self, x):
		shortcut = self.shortcut_layer(x)
		res = self.res_layer(x)
		return res + shortcut

class bottleneck_IR_SE(Module):
	def __init__(self, in_channel, depth, stride):
		super(bottleneck_IR_SE, self).__init__()
		if in_channel == depth:
			self.shortcut_layer = MaxPool2d(1, stride)
		else:
			self.shortcut_layer = Sequential(
				Conv2d(in_channel, depth, (1, 1), stride, bias=False),
				BatchNorm2d(depth)
			)
		self.res_layer = Sequential(
			BatchNorm2d(in_channel),
			Conv2d(in_channel, depth, (3, 3), (1, 1), 1, bias=False),
			PReLU(depth),
			Conv2d(depth, depth, (3, 3), stride, 1, bias=False),
			BatchNorm2d(depth),
			SEModule(depth, 16)
		)

	def forward(self, x):
		shortcut = self.shortcut_layer(x)
		res = self.res_layer(x)
		return res + shortcut




class BackboneEncoderUsingLastLayerIntoWPlus(Module):
    def __init__(self, num_layers, mode='ir', opts=None):
        super(BackboneEncoderUsingLastLayerIntoWPlus, self).__init__()
        print('Using BackboneEncoderUsingLastLayerIntoWPlus')
        assert num_layers in [50, 100, 152], 'num_layers should be 50,100, or 152'
        assert mode in ['ir', 'ir_se'], 'mode should be ir or ir_se'
        blocks = get_blocks(num_layers)
        if mode == 'ir':
            unit_module = bottleneck_IR
        elif mode == 'ir_se':
            unit_module = bottleneck_IR_SE
        self.input_layer = Sequential(Conv2d(opts.input_nc, 64, (3, 3), 1, 1, bias=False),
                                      BatchNorm2d(64),
                                      PReLU(64))
        self.output_layer_2 = Sequential(BatchNorm2d(512),
                                         torch.nn.AdaptiveAvgPool2d((7, 7)),
                                         Flatten(),
                                         Linear(512 * 7 * 7, 512))
        self.linear = EqualLinear(512, 512 * 18, lr_mul=1)
        modules = []
        for block in blocks:
            for bottleneck in block:
                modules.append(unit_module(bottleneck.in_channel,
                                           bottleneck.depth,
                                           bottleneck.stride))
        self.body = Sequential(*modules)

    def forward(self, x):
        x = self.input_layer(x)
        x = self.body(x)
        x = self.output_layer_2(x)
        x = self.linear(x)
        x = x.view(-1, 18, 512)
        return x

# =============================================================================================




class MyHairEncoderGradualStyleWPlus(Module):
    def __init__(self, num_layers, mode='ir', opts=None):
        super(MyHairEncoderGradualStyleWPlus, self).__init__()
        assert num_layers in [50, 100, 152], 'num_layers should be 50,100, or 152'
        assert mode in ['ir', 'ir_se'], 'mode should be ir or ir_se'
        self.encoder_hair = BackboneEncoderUsingLastLayerIntoWPlus(num_layers, mode=mode, opts=opts)
        self.encoder_face = BackboneEncoderUsingLastLayerIntoWPlus(num_layers, mode=mode, opts=opts)
        self.opts = opts

        out_features = 18 * 512
        in_features = out_features * 2
        self.flat = Flatten()
        self.map = Sequential(
            Linear(in_features=in_features, out_features=out_features),
            nn.LeakyReLU(negative_slope=0.2,inplace=True),
            )


    def forward(self, face, hair):
        e_face = self.encoder_face(face)
        e_hair = self.encoder_hair(hair)

        e_face_flat = self.flat(e_face)
        e_hair_flat = self.flat(e_hair)

        e = torch.cat((e_face_flat, e_hair_flat), dim=1)


        x = self.map(e)
        x = x.view(-1, 18, 512)
        return x

    def forward_im_vec(self, face_im, hair_vec):
        e_face = self.encoder_face(face_im)
        e_hair = hair_vec

        e_face_flat = self.flat(e_face)
        e_hair_flat = self.flat(e_hair)

        e = torch.cat((e_face_flat, e_hair_flat), dim=1)


        x = self.map(e)
        x = x.view(-1, 18, 512)
        return x

    def forward_vec_im(self, face_vec, hair_im):
        e_face = face_vec
        e_hair = self.encoder_hair(hair_im)

        e_face_flat = self.flat(e_face)
        e_hair_flat = self.flat(e_hair)

        e = torch.cat((e_face_flat, e_hair_flat), dim=1)


        x = self.map(e)
        x = x.view(-1, 18, 512)
        return x

    def forward_vec_vec(self, face_vec, hair_vec):
        e_face = face_vec
        e_hair = hair_vec

        e_face_flat = self.flat(e_face)
        e_hair_flat = self.flat(e_hair)

        e = torch.cat((e_face_flat, e_hair_flat), dim=1)


        x = self.map(e)
        x = x.view(-1, 18, 512)
        return x

    def get_embedding(self, input_im, is_face):
        if is_face:
            e_out = self.encoder_face(input_im)
        else:
            e_out = self.encoder_hair(input_im)
        return e_out

import math
import random
import torch
from torch import nn
from torch.nn import functional as F

# taken and modified from https://github.com/eladrich/pixel2style2pixel/blob/master/models/stylegan2/model.py
# from demo.op import FusedLeakyReLU, fused_leaky_relu, upfirdn2d
from op import FusedLeakyReLU, fused_leaky_relu, upfirdn2d


class PixelNorm(nn.Module):
    def __init__(self):
        super().__init__()

    def forward(self, input):
        return input * torch.rsqrt(torch.mean(input ** 2, dim=1, keepdim=True) + 1e-8)


def make_kernel(k):
    k = torch.tensor(k, dtype=torch.float32)

    if k.ndim == 1:
        k = k[None, :] * k[:, None]

    k /= k.sum()

    return k


class Upsample(nn.Module):
    def __init__(self, kernel, factor=2):
        super().__init__()

        self.factor = factor
        kernel = make_kernel(kernel) * (factor ** 2)
        self.register_buffer('kernel', kernel)

        p = kernel.shape[0] - factor

        pad0 = (p + 1) // 2 + factor - 1
        pad1 = p // 2

        self.pad = (pad0, pad1)

    def forward(self, input):
        out = upfirdn2d(input, self.kernel, up=self.factor, down=1, pad=self.pad)

        return out


class Downsample(nn.Module):
    def __init__(self, kernel, factor=2):
        super().__init__()

        self.factor = factor
        kernel = make_kernel(kernel)
        self.register_buffer('kernel', kernel)

        p = kernel.shape[0] - factor

        pad0 = (p + 1) // 2
        pad1 = p // 2

        self.pad = (pad0, pad1)

    def forward(self, input):
        out = upfirdn2d(input, self.kernel, up=1, down=self.factor, pad=self.pad)

        return out


class Blur(nn.Module):
    def __init__(self, kernel, pad, upsample_factor=1):
        super().__init__()

        kernel = make_kernel(kernel)

        if upsample_factor > 1:
            kernel = kernel * (upsample_factor ** 2)

        self.register_buffer('kernel', kernel)

        self.pad = pad

    def forward(self, input):
        out = upfirdn2d(input, self.kernel, pad=self.pad)

        return out


class EqualConv2d(nn.Module):
    def __init__(
            self, in_channel, out_channel, kernel_size, stride=1, padding=0, bias=True
    ):
        super().__init__()

        self.weight = nn.Parameter(
            torch.randn(out_channel, in_channel, kernel_size, kernel_size)
        )
        self.scale = 1 / math.sqrt(in_channel * kernel_size ** 2)

        self.stride = stride
        self.padding = padding

        if bias:
            self.bias = nn.Parameter(torch.zeros(out_channel))

        else:
            self.bias = None

    def forward(self, input):
        out = F.conv2d(
            input,
            self.weight * self.scale,
            bias=self.bias,
            stride=self.stride,
            padding=self.padding,
        )

        return out

    def __repr__(self):
        return (
            f'{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]},'
            f' {self.weight.shape[2]}, stride={self.stride}, padding={self.padding})'
        )


class EqualLinear(nn.Module):
    def __init__(
            self, in_dim, out_dim, bias=True, bias_init=0, lr_mul=1, activation=None
    ):
        super().__init__()

        self.weight = nn.Parameter(torch.randn(out_dim, in_dim).div_(lr_mul))

        if bias:
            self.bias = nn.Parameter(torch.zeros(out_dim).fill_(bias_init))

        else:
            self.bias = None

        self.activation = activation

        self.scale = (1 / math.sqrt(in_dim)) * lr_mul
        self.lr_mul = lr_mul

    def forward(self, input):
        if self.activation:
            out = F.linear(input, self.weight * self.scale)
            out = fused_leaky_relu(out, self.bias * self.lr_mul)

        else:
            out = F.linear(
                input, self.weight * self.scale, bias=self.bias * self.lr_mul
            )

        return out

    def __repr__(self):
        return (
            f'{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]})'
        )


class ScaledLeakyReLU(nn.Module):
    def __init__(self, negative_slope=0.2):
        super().__init__()

        self.negative_slope = negative_slope

    def forward(self, input):
        out = F.leaky_relu(input, negative_slope=self.negative_slope)

        return out * math.sqrt(2)


class ModulatedConv2d(nn.Module):
    def __init__(
            self,
            in_channel,
            out_channel,
            kernel_size,
            style_dim,
            demodulate=True,
            upsample=False,
            downsample=False,
            blur_kernel=[1, 3, 3, 1],
    ):
        super().__init__()

        self.eps = 1e-8
        self.kernel_size = kernel_size
        self.in_channel = in_channel
        self.out_channel = out_channel
        self.upsample = upsample
        self.downsample = downsample

        if upsample:
            factor = 2
            p = (len(blur_kernel) - factor) - (kernel_size - 1)
            pad0 = (p + 1) // 2 + factor - 1
            pad1 = p // 2 + 1

            self.blur = Blur(blur_kernel, pad=(pad0, pad1), upsample_factor=factor)

        if downsample:
            factor = 2
            p = (len(blur_kernel) - factor) + (kernel_size - 1)
            pad0 = (p + 1) // 2
            pad1 = p // 2

            self.blur = Blur(blur_kernel, pad=(pad0, pad1))

        fan_in = in_channel * kernel_size ** 2
        self.scale = 1 / math.sqrt(fan_in)
        self.padding = kernel_size // 2

        self.weight = nn.Parameter(
            torch.randn(1, out_channel, in_channel, kernel_size, kernel_size)
        )

        self.modulation = EqualLinear(style_dim, in_channel, bias_init=1)

        self.demodulate = demodulate

    def __repr__(self):
        return (
            f'{self.__class__.__name__}({self.in_channel}, {self.out_channel}, {self.kernel_size}, '
            f'upsample={self.upsample}, downsample={self.downsample})'
        )

    def forward(self, input, style):
        batch, in_channel, height, width = input.shape

        style = self.modulation(style).view(batch, 1, in_channel, 1, 1)
        weight = self.scale * self.weight * style

        if self.demodulate:
            demod = torch.rsqrt(weight.pow(2).sum([2, 3, 4]) + 1e-8)
            weight = weight * demod.view(batch, self.out_channel, 1, 1, 1)

        weight = weight.view(
            batch * self.out_channel, in_channel, self.kernel_size, self.kernel_size
        )

        if self.upsample:
            input = input.view(1, batch * in_channel, height, width)
            weight = weight.view(
                batch, self.out_channel, in_channel, self.kernel_size, self.kernel_size
            )
            weight = weight.transpose(1, 2).reshape(
                batch * in_channel, self.out_channel, self.kernel_size, self.kernel_size
            )
            out = F.conv_transpose2d(input, weight, padding=0, stride=2, groups=batch)
            _, _, height, width = out.shape
            out = out.view(batch, self.out_channel, height, width)
            out = self.blur(out)

        elif self.downsample:
            input = self.blur(input)
            _, _, height, width = input.shape
            input = input.view(1, batch * in_channel, height, width)
            out = F.conv2d(input, weight, padding=0, stride=2, groups=batch)
            _, _, height, width = out.shape
            out = out.view(batch, self.out_channel, height, width)

        else:
            input = input.view(1, batch * in_channel, height, width)
            out = F.conv2d(input, weight, padding=self.padding, groups=batch)
            _, _, height, width = out.shape
            out = out.view(batch, self.out_channel, height, width)

        return out


class NoiseInjection(nn.Module):
    def __init__(self):
        super().__init__()

        self.weight = nn.Parameter(torch.zeros(1))

    def forward(self, image, noise=None):
        if noise is None:
            batch, _, height, width = image.shape
            noise = image.new_empty(batch, 1, height, width).normal_()

        return image + self.weight * noise


class ConstantInput(nn.Module):
    def __init__(self, channel, size=4):
        super().__init__()

        self.input = nn.Parameter(torch.randn(1, channel, size, size))

    def forward(self, input):
        batch = input.shape[0]
        out = self.input.repeat(batch, 1, 1, 1)

        return out


class StyledConv(nn.Module):
    def __init__(
            self,
            in_channel,
            out_channel,
            kernel_size,
            style_dim,
            upsample=False,
            blur_kernel=[1, 3, 3, 1],
            demodulate=True,
    ):
        super().__init__()

        self.conv = ModulatedConv2d(
            in_channel,
            out_channel,
            kernel_size,
            style_dim,
            upsample=upsample,
            blur_kernel=blur_kernel,
            demodulate=demodulate,
        )

        self.noise = NoiseInjection()
        # self.bias = nn.Parameter(torch.zeros(1, out_channel, 1, 1))
        # self.activate = ScaledLeakyReLU(0.2)
        self.activate = FusedLeakyReLU(out_channel)

    def forward(self, input, style, noise=None):
        out = self.conv(input, style)
        out = self.noise(out, noise=noise)
        # out = out + self.bias
        out = self.activate(out)

        return out


class ToRGB(nn.Module):
    def __init__(self, in_channel, style_dim, upsample=True, blur_kernel=[1, 3, 3, 1]):
        super().__init__()

        if upsample:
            self.upsample = Upsample(blur_kernel)

        self.conv = ModulatedConv2d(in_channel, 3, 1, style_dim, demodulate=False)
        self.bias = nn.Parameter(torch.zeros(1, 3, 1, 1))

    def forward(self, input, style, skip=None):
        out = self.conv(input, style)
        out = out + self.bias

        if skip is not None:
            skip = self.upsample(skip)

            out = out + skip

        return out


class Generator(nn.Module):
    def __init__(
            self,
            size,
            style_dim,
            n_mlp,
            channel_multiplier=2,
            blur_kernel=[1, 3, 3, 1],
            lr_mlp=0.01,
    ):
        super().__init__()

        self.size = size

        self.style_dim = style_dim

        layers = [PixelNorm()]

        for i in range(n_mlp):
            layers.append(
                EqualLinear(
                    style_dim, style_dim, lr_mul=lr_mlp, activation='fused_lrelu'
                )
            )

        self.style = nn.Sequential(*layers)

        self.channels = {
            4: 512,
            8: 512,
            16: 512,
            32: 512,
            64: 256 * channel_multiplier,
            128: 128 * channel_multiplier,
            256: 64 * channel_multiplier,
            512: 32 * channel_multiplier,
            1024: 16 * channel_multiplier,
        }

        self.input = ConstantInput(self.channels[4])
        self.conv1 = StyledConv(
            self.channels[4], self.channels[4], 3, style_dim, blur_kernel=blur_kernel
        )
        self.to_rgb1 = ToRGB(self.channels[4], style_dim, upsample=False)

        self.log_size = int(math.log(size, 2))
        self.num_layers = (self.log_size - 2) * 2 + 1

        self.convs = nn.ModuleList()
        self.upsamples = nn.ModuleList()
        self.to_rgbs = nn.ModuleList()
        self.noises = nn.Module()

        in_channel = self.channels[4]

        for layer_idx in range(self.num_layers):
            res = (layer_idx + 5) // 2
            shape = [1, 1, 2 ** res, 2 ** res]
            self.noises.register_buffer(f'noise_{layer_idx}', torch.randn(*shape))

        for i in range(3, self.log_size + 1):
            out_channel = self.channels[2 ** i]

            self.convs.append(
                StyledConv(
                    in_channel,
                    out_channel,
                    3,
                    style_dim,
                    upsample=True,
                    blur_kernel=blur_kernel,
                )
            )

            self.convs.append(
                StyledConv(
                    out_channel, out_channel, 3, style_dim, blur_kernel=blur_kernel
                )
            )

            self.to_rgbs.append(ToRGB(out_channel, style_dim))

            in_channel = out_channel

        self.n_latent = self.log_size * 2 - 2

    def make_noise(self):
        device = self.input.input.device

        noises = [torch.randn(1, 1, 2 ** 2, 2 ** 2, device=device)]

        for i in range(3, self.log_size + 1):
            for _ in range(2):
                noises.append(torch.randn(1, 1, 2 ** i, 2 ** i, device=device))

        return noises

    def mean_latent(self, n_latent):
        latent_in = torch.randn(
            n_latent, self.style_dim, device=self.input.input.device
        )
        latent = self.style(latent_in).mean(0, keepdim=True)

        return latent

    def get_latent(self, input):
        return self.style(input)

    def forward(
            self,
            styles,
            return_latents=False,
            return_features=False,
            inject_index=None,
            truncation=1,
            truncation_latent=None,
            input_is_latent=False,
            noise=None,
            randomize_noise=True,
    ):
        if not input_is_latent:
            styles = [self.style(s) for s in styles]

        if noise is None:
            if randomize_noise:
                noise = [None] * self.num_layers
            else:
                noise = [
                    getattr(self.noises, f'noise_{i}') for i in range(self.num_layers)
                ]

        if truncation < 1:
            style_t = []

            for style in styles:
                style_t.append(
                    truncation_latent + truncation * (style - truncation_latent)
                )

            styles = style_t

        if len(styles) < 2:
            inject_index = self.n_latent

            if styles[0].ndim < 3:
                latent = styles[0].unsqueeze(1).repeat(1, inject_index, 1)
            else:
                latent = styles[0]

        else:
            if inject_index is None:
                inject_index = random.randint(1, self.n_latent - 1)

            latent = styles[0].unsqueeze(1).repeat(1, inject_index, 1)
            latent2 = styles[1].unsqueeze(1).repeat(1, self.n_latent - inject_index, 1)

            latent = torch.cat([latent, latent2], 1)

        out = self.input(latent)
        out = self.conv1(out, latent[:, 0], noise=noise[0])

        skip = self.to_rgb1(out, latent[:, 1])

        i = 1
        for conv1, conv2, noise1, noise2, to_rgb in zip(
                self.convs[::2], self.convs[1::2], noise[1::2], noise[2::2], self.to_rgbs
        ):
            out = conv1(out, latent[:, i], noise=noise1)
            out = conv2(out, latent[:, i + 1], noise=noise2)
            skip = to_rgb(out, latent[:, i + 2], skip)

            i += 2

        image = skip

        if return_latents:
            return image, latent
        elif return_features:
            return image, out
        else:
            return image, None


class ConvLayer(nn.Sequential):
    def __init__(
            self,
            in_channel,
            out_channel,
            kernel_size,
            downsample=False,
            blur_kernel=[1, 3, 3, 1],
            bias=True,
            activate=True,
    ):
        layers = []

        if downsample:
            factor = 2
            p = (len(blur_kernel) - factor) + (kernel_size - 1)
            pad0 = (p + 1) // 2
            pad1 = p // 2

            layers.append(Blur(blur_kernel, pad=(pad0, pad1)))

            stride = 2
            self.padding = 0

        else:
            stride = 1
            self.padding = kernel_size // 2

        layers.append(
            EqualConv2d(
                in_channel,
                out_channel,
                kernel_size,
                padding=self.padding,
                stride=stride,
                bias=bias and not activate,
            )
        )

        if activate:
            if bias:
                layers.append(FusedLeakyReLU(out_channel))

            else:
                layers.append(ScaledLeakyReLU(0.2))

        super().__init__(*layers)


class ResBlock(nn.Module):
    def __init__(self, in_channel, out_channel, blur_kernel=[1, 3, 3, 1]):
        super().__init__()

        self.conv1 = ConvLayer(in_channel, in_channel, 3)
        self.conv2 = ConvLayer(in_channel, out_channel, 3, downsample=True)

        self.skip = ConvLayer(
            in_channel, out_channel, 1, downsample=True, activate=False, bias=False
        )

    def forward(self, input):
        out = self.conv1(input)
        out = self.conv2(out)

        skip = self.skip(input)
        out = (out + skip) / math.sqrt(2)

        return out


class Discriminator(nn.Module):
    def __init__(self, size, channel_multiplier=2, blur_kernel=[1, 3, 3, 1]):
        super().__init__()

        channels = {
            4: 512,
            8: 512,
            16: 512,
            32: 512,
            64: 256 * channel_multiplier,
            128: 128 * channel_multiplier,
            256: 64 * channel_multiplier,
            512: 32 * channel_multiplier,
            1024: 16 * channel_multiplier,
        }

        convs = [ConvLayer(3, channels[size], 1)]

        log_size = int(math.log(size, 2))

        in_channel = channels[size]

        for i in range(log_size, 2, -1):
            out_channel = channels[2 ** (i - 1)]

            convs.append(ResBlock(in_channel, out_channel, blur_kernel))

            in_channel = out_channel

        self.convs = nn.Sequential(*convs)

        self.stddev_group = 4
        self.stddev_feat = 1

        self.final_conv = ConvLayer(in_channel + 1, channels[4], 3)
        self.final_linear = nn.Sequential(
            EqualLinear(channels[4] * 4 * 4, channels[4], activation='fused_lrelu'),
            EqualLinear(channels[4], 1),
        )

    def forward(self, input):
        out = self.convs(input)

        batch, channel, height, width = out.shape
        group = min(batch, self.stddev_group)
        stddev = out.view(
            group, -1, self.stddev_feat, channel // self.stddev_feat, height, width
        )
        stddev = torch.sqrt(stddev.var(0, unbiased=False) + 1e-8)
        stddev = stddev.mean([2, 3, 4], keepdims=True).squeeze(2)
        stddev = stddev.repeat(group, 1, height, width)
        out = torch.cat([out, stddev], 1)

        out = self.final_conv(out)

        out = out.view(batch, -1)
        out = self.final_linear(out)

        return out

class Tool:

    def __init__(self, opts=None, result_path='./data/results/', checkpoint_path='./best_model.pt'):
        if opts is None:
            self.opts = Namespace()
            self.opts.input_nc = 3
            self.opts.device = 'cuda:0'
            self.opts.test_batch_size = 2
            self.opts.checkpoint_path = checkpoint_path
            self.opts.result_path = result_path
        else:
            self.opts = opts
            self.opts.result_path = result_path
            os.makedirs(result_path, exist_ok=True)
        self.net = self.load_network()
        self.uploaded_images_path = './data/uploaded_images/'
        self.predefined_images_path = './data/'
        os.makedirs((self.uploaded_images_path), exist_ok=True)
        os.makedirs((result_path), exist_ok=True)
        self.chars = np.array((list(string.ascii_letters + string.digits + '_')), dtype=str)
        self.char_inds = np.arange(len(self.chars))
        self.alpha_blend_sigma = 5.0

    def get_predefined_images(self):
        image_files_ = os.listdir(self.predefined_images_path)
        image_files = []
        for suff in ('jpg', 'jpeg', 'png'):
            image_files += filter(image_files_, f"*.{suff}")

        return image_files

    def get_previously_uploaded_images(self):
        image_files_ = os.listdir(self.uploaded_images_path)
        image_files = []
        for suff in ('jpg', 'jpeg', 'png'):
            image_files += filter(image_files_, f"*.{suff}")

        return image_files

    def get_new_filename(self):
        fname_len = 20

        def get_rand_fname():
            ids = np.random.choice((self.char_inds), size=fname_len, replace=True)
            return ''.join(self.chars[ids])

        fname_ = get_rand_fname()
        print(f"generated name: {fname_}")
        while os.path.exists(os.path.join(self.uploaded_images_path, f"u{fname_}.png")):
            fname_ = get_rand_fname()

        return f"u{fname_}.png"

    def get_all_images(self):
        predefined_images = self.get_predefined_images()
        uploaded = self.get_previously_uploaded_images()
        return predefined_images + uploaded

    def load_network(self):
        net = MypSp(self.opts)
        return net

    def get_absolute_path(self, fname):
        fname = fname.split('/')[(-1)]
        if fname.startswith('u'):
            return os.path.join(self.uploaded_images_path, fname)
        else:
            return os.path.join(self.predefined_images_path, fname)

    def __prepare_filename(self, nm1, nm2, blend, kwargs={'phase': 'ht'}):
        fname1_ws = nm1.split('/')[(-1)]
        fname1_wos = fname1_ws.split('.')[0]
        if nm2 is not None:
            fname2_ws = nm2.split('/')[(-1)]
            fname2_wos = fname2_ws.split('.')[0]
        if 'ht' in kwargs['phase']:
            new_filename = os.path.join(self.opts.result_path, f"{fname1_wos}_{fname2_wos}_blend_{blend}.jpg")
        else:
            if 'interp' in kwargs['phase']:
                os.makedirs((os.path.join(self.opts.result_path, 'interp')), exist_ok=True)
                new_filename = os.path.join(self.opts.result_path, 'interp', f"{fname1_wos}_{fname2_wos}_{kwargs['curr_step']}_{kwargs['max_step']}_blend_{blend}_hair_{kwargs['hair']}.jpg")
            else:
                if 'manip' in kwargs['phase']:
                    os.makedirs((os.path.join(self.opts.result_path, 'manip')), exist_ok=True)
                    new_filename = os.path.join(self.opts.result_path, 'manip', f"{fname1_wos}_{kwargs['dir']}_{kwargs['strength']}_blend_{blend}.jpg")
        return new_filename

    def hairstyle_transfer(self, im1_path, im2_path, alpha_blend=True):
        nonblended_name = self.__prepare_filename(im1_path, im2_path, False)
        blended_name = self.__prepare_filename(im1_path, im2_path, True)
        thefilename = blended_name if alpha_blend else nonblended_name
        if os.path.exists(thefilename):
            return thefilename
        else:
            if self.net is None:
                print('Model was not loaded. Loading default model')
                self.load_network()
            else:
                self.net.to(self.opts.device)
                if alpha_blend:
                    inner_face1, hair1, mask1 = utils.load_and_split_image(im1_path, return_mask=True)
                    inner_face2, hair2, mask2 = utils.load_and_split_image(im2_path, return_mask=True)
                else:
                    inner_face1, hair1 = utils.load_and_split_image(im1_path)
                inner_face2, hair2 = utils.load_and_split_image(im2_path)
            # print(f"Range of inner face: [{inner_face2.min()}, {inner_face2.max()}]")
            im2_orig = inner_face2 + hair2
            input_face = utils.numpy_uint8_to_torch(inner_face2.astype(np.uint8))
            input_hair = utils.numpy_uint8_to_torch(hair1.astype(np.uint8))
            if alpha_blend:
                masks = [
                 mask2]
                im_orig = [im2_orig]
            output = self.net.forward(input_face, input_hair, resize=False)
            output_images = output.cpu()
            for ii in range(output_images.shape[0]):
                img_generated = utils.torch_to_numpy_uint8(output_images[ii:ii + 1])
                if alpha_blend:
                    img_original = im_orig[ii]
                    im_mask = utils.gaussian_filter((masks[ii]), sigma=(self.alpha_blend_sigma))
                    # print(f"Range of image mask: [{im_mask.min()}, {im_mask.max()}]")
                    if img_original.shape[0] < 1024:
                        img_original = cv2.resize(img_original, (1024, 1024))
                    if im_mask.shape[0] < 1024:
                        im_mask = cv2.resize(im_mask, (1024, 1024))
                    masked_output = utils.alpha_blend_images(img_generated, img_original, im_mask)
                    # print(f"Range of masked output: [{masked_output.min()}, {masked_output.max()}]")
                    imageio.imwrite(blended_name, masked_output)
                imageio.imwrite(nonblended_name, img_generated)

            return thefilename

get,me,the,code,to,finetuning,the,model