<repo_name>BoSmallEar/Anime-Face-Generator<file_sep>/Style-GAN/README.txt
Code for Style-GAN

The code is adapted from a github repo https://github.com/NVlabs/stylegan

dataseet_tool.py is modified based on the code from the above repo
train.py is modified based on the code from the above repo
config.py is modified based on the code from the above repo

generate_figures.py is modified based on the code from https://github.com/atelier-ritz/AnimeStyleGAN
<file_sep>/README.txt
Code for FID

The code is adapted from a github repo https://github.com/mseitzer/pytorch-fid

fid_score.py is reused from the above repo
inception.py is reused from the above repo
<file_sep>/Style-GAN/generate_figures.py
import os
import pickle
import numpy as np
import PIL.Image
import dnnlib
import dnnlib.tflib as tflib
from metrics import metric_base
import config

def randomLatents(seed1,seed2,morphingFactor,shape):
    # 0 < morphingFactor < 1, 0->latents0, 1-> latents1
    latents0 = np.random.RandomState(seed1).randn(1, shape)
    latents1 = np.random.RandomState(seed2).randn(1, shape)
    latents = latents0+(latents1-latents0)*morphingFactor
    return latents

if __name__ == "__main__":
    # Initialize TensorFlow.
    tflib.init_tf()

    # Load pre-trained network.
    _G, _D, Gs = pickle.load(open("network-snapshot-003285.pkl", "rb"))

    # Print network details.
    Gs.print_layers()
    
    '''
    TRUNCATION = 0.7
    SEED1_1 = [4722,2111,3333,1357,2589]
    SEED1_2 = [5944,3111,3766,3421,4171]
    SEED2_1 = [3611,4111,1434,2267,4102]
    SEED2_2 = [4333,5111,3456,4588,4990]
    MORPH_FACTOR = 0.84615

    for i in range(5):
        # Pick latent vector.
        latents_1 = randomLatents(SEED1_1[i],SEED1_2[i],MORPH_FACTOR,Gs.input_shape[1])
        
        # Generate image.
        fmt = dict(func=tflib.convert_images_to_uint8, nchw_to_nhwc=True)
        images = Gs.run(latents_1, None, truncation_psi=TRUNCATION, randomize_noise=True, output_transform=fmt)
    
        # Save image.
        result_dir = 'results/'
        os.makedirs(result_dir, exist_ok=True)
        png_filename = os.path.join(result_dir, 'photo-'+str(i)+'-1.png')
        PIL.Image.fromarray(images[0], 'RGB').save(png_filename)

        latents_2 = randomLatents(SEED2_1[i],SEED2_2[i],MORPH_FACTOR,Gs.input_shape[1])
        
        # Generate image.
        fmt = dict(func=tflib.convert_images_to_uint8, nchw_to_nhwc=True)
        images = Gs.run(latents_2, None, truncation_psi=TRUNCATION, randomize_noise=True, output_transform=fmt)
    
        # Save image.
        result_dir = 'results/'
        os.makedirs(result_dir, exist_ok=True)
        png_filename = os.path.join(result_dir, 'photo-'+str(i)+'-2.png')
        PIL.Image.fromarray(images[0], 'RGB').save(png_filename)
        
        latents_3 = latents_1 + latents_2
        
        # Generate image.
        fmt = dict(func=tflib.convert_images_to_uint8, nchw_to_nhwc=True)
        images = Gs.run(latents_3, None, truncation_psi=TRUNCATION, randomize_noise=True, output_transform=fmt)
    
        # Save image.
        result_dir = 'results/'
        os.makedirs(result_dir, exist_ok=True)
        png_filename = os.path.join(result_dir, 'photo-'+str(i)+'-3.png')
        PIL.Image.fromarray(images[0], 'RGB').save(png_filename)
    '''
    
    for i in range(100):
        # Pick latent vector.
        TRUNCATION = 0.7
        SEED1 = 1200 + 40 * i;
        SEED2 = 1000 + 50 * i;
        MORPH_FACTOR = 0.84615
        latents_1 = randomLatents(SEED1,SEED2,MORPH_FACTOR,Gs.input_shape[1])
        
        # Generate image.
        fmt = dict(func=tflib.convert_images_to_uint8, nchw_to_nhwc=True)
        images = Gs.run(latents_1, None, truncation_psi=TRUNCATION, randomize_noise=True, output_transform=fmt)
    
        # Save image.
        result_dir = 'results/'
        os.makedirs(result_dir, exist_ok=True)
        png_filename = os.path.join(result_dir, 'photo-'+str(i)+'-1.jpg')
        PIL.Image.fromarray(images[0], 'RGB').save(png_filename)<file_sep>/DC-GAN/model.py
import torch
import torch.nn as nn
import torch.nn.parallel



def weights_init(m):
    classname = m.__class__.__name__
    if classname.find('Conv') != -1:
        m.weight.data.normal_(0.0, 0.02)
    elif classname.find('BatchNorm') != -1:
        m.weight.data.normal_(1.0, 0.02)
        m.bias.data.fill_(0)

class _netG_1(nn.Module):
    def __init__(self, ngpu, nz, nc , ngf, n_extra_layers_g):
        super(_netG_1, self).__init__()
        self.ngpu = ngpu
        main = nn.Sequential(
            nn.ConvTranspose2d(     nz, ngf * 8, 4, 1, 0, bias=False),
            nn.BatchNorm2d(ngf * 8),
            nn.LeakyReLU(0.2, inplace=True),
            nn.ConvTranspose2d(ngf * 8, ngf * 4, 4, 2, 1, bias=False),
            nn.BatchNorm2d(ngf * 4),
            nn.LeakyReLU(0.2, inplace=True),
            nn.ConvTranspose2d(ngf * 4, ngf * 2, 4, 2, 1, bias=False),
            nn.BatchNorm2d(ngf * 2),
            nn.LeakyReLU(0.2, inplace=True),
            nn.ConvTranspose2d(ngf * 2,     ngf, 4, 2, 1, bias=False),
            nn.BatchNorm2d(ngf),
            nn.LeakyReLU(0.2, inplace=True),
        )
        for t in range(n_extra_layers_g):
            main.add_module('extra-layers-{0}-{1}-conv'.format(t, ngf),
                            nn.Conv2d(ngf, ngf, 3, 1, 1, bias=False))
            main.add_module('extra-layers-{0}-{1}-batchnorm'.format(t, ngf),
                            nn.BatchNorm2d(ngf))
            main.add_module('extra-layers-{0}-{1}-relu'.format(t, ngf),
                            nn.LeakyReLU(0.2, inplace=True))

        main.add_module('final_layer_deconv', 
        	             nn.ConvTranspose2d(ngf, nc, 4, 2, 1, bias=False)) # 5,3,1 for 96x96
        main.add_module('final_layer_tanh', 
        	             nn.Tanh())

        self.main = main


    def forward(self, input):
        gpu_ids = None
        if isinstance(input.data, torch.cuda.FloatTensor) and self.ngpu > 1:
            gpu_ids = range(self.ngpu)
        return nn.parallel.data_parallel(self.main, input, gpu_ids), 0

class _netD_1(nn.Module):
    def __init__(self, ngpu, nz, nc, ndf,  n_extra_layers_d):
        super(_netD_1, self).__init__()
        self.ngpu = ngpu
        main = nn.Sequential(
            nn.Conv2d(nc, ndf, 4, 2, 1, bias=False),
            nn.LeakyReLU(0.2, inplace=True),
            nn.Conv2d(ndf, ndf * 2, 4, 2, 1, bias=False),
            nn.BatchNorm2d(ndf * 2),
            nn.LeakyReLU(0.2, inplace=True),
            nn.Conv2d(ndf * 2, ndf * 4, 4, 2, 1, bias=False),
            nn.BatchNorm2d(ndf * 4),
            nn.LeakyReLU(0.2, inplace=True),
            nn.Conv2d(ndf * 4, ndf * 8, 4, 2, 1, bias=False),
            nn.BatchNorm2d(ndf * 8),
            nn.LeakyReLU(0.2, inplace=True),
        )

        for t in range(n_extra_layers_d):
            main.add_module('extra-layers-{0}.{1}.conv'.format(t, ndf * 8),
                            nn.Conv2d(ndf * 8, ndf * 8, 3, 1, 1, bias=False))
            main.add_module('extra-layers-{0}.{1}.batchnorm'.format(t, ndf * 8),
                            nn.BatchNorm2d(ndf * 8))
            main.add_module('extra-layers-{0}.{1}.relu'.format(t, ndf * 8),
                            nn.LeakyReLU(0.2, inplace=True))


        main.add_module('final_layers_conv', nn.Conv2d(ndf * 8, 1, 4, 1, 0, bias=False))
        main.add_module('final_layers_sigmoid', nn.Sigmoid())
        self.main = main

    def forward(self, input):
        gpu_ids = None
        if isinstance(input.data, torch.cuda.FloatTensor) and self.ngpu > 1:
            gpu_ids = range(self.ngpu)
        output = nn.parallel.data_parallel(self.main, input, gpu_ids)
        return output.view(-1, 1)<file_sep>/DC-GAN/generate_figures.py
from __future__ import print_function
from PIL import Image
import random
import torch
import torchvision.utils as vutils
from torch.autograd import Variable
import torchvision.transforms
import matplotlib.pyplot as plt

import models

model_path = 'results/netG_epoch_50.pth'
#model_path = 'results/netG_epoch_99.pth'
netG = models._netG_1(2, 100, 3,64, 1) # ngpu, nz, nc, ngf, n_extra_layers
netG.cuda()
netG.load_state_dict(torch.load(model_path, map_location=lambda storage, loc: storage))

for i in range(1144):
    noise_batch = torch.FloatTensor(1, 100, 1, 1).normal_(0,1)
    noise_batch = Variable(noise_batch)
    fake_batch,_ = netG(noise_batch)
    img_tensor = fake_batch.data.cpu()
    grid = vutils.make_grid(img_tensor, nrow=1, padding=2)
    ndarr = grid.mul(0.5).add(0.5).mul(255).byte().transpose(0, 2).transpose(0, 1).numpy()
    im = Image.fromarray(ndarr,'RGB')
    im.save('results/dcgan-generate-'+str(i)+'.jpg')<file_sep>/DC-GAN/README.txt
Code for DC-GAN

The code is adapted from a github repo https://github.com/jayleicn/animeGAN

build_face_dataset.py is reused from the above repo
model.py is modified based on the code from the above repo
generate_figures.py is modified based on the code from the above repo
interpretation.ipynb is modified based on the code from the above repo
main.py contains the training schedule and it is modified based on the above repo
