#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Program name: Get the Weather from API
Author: Yuanzizi
Github: https://github.com/Yuanzizi/
Edition：v 0.2
Edit date: 2017.08.21
Descrition:
    ------------------------------------------------
    输入城市名，返回该城市的天气数据；
    输入指令，打印帮助文档（一般使用 h 或 help）；
    输入指令，退出程序的交互（一般使用 quit 或 exit）；
    在退出程序之前，打印查询过的所有城市。

    PS: 天气数据来自网络API
    -------------------------------------------------
"""
import sys
import time
import requests
import json
import const_value

# from .const_value import API_OWM, API_Yahoo
from helper import json2list

class WeatherAPI(object):
    """Summary of class here.

    Longer class information....
    Longer class information....

    Attributes:
        likes_spam: A boolean indicating if we like SPAM or not.
        eggs: An integer count of the eggs we have laid.
    """

    __formatWeather = ["天气：","温度：","最后更新时间："]
    def __init__(self):
        self.result = {} # 存放有意义的结果
        self.cityEnName = [] # 初始化字典
        self.loadCityList('cityEnName.txt')

    def getWeather(self,location):
        self.fetch_XZ_weather(location)
        self.fetch_OWM_weather(location)
        self.fetch_Yahoo_weather(location)

    def loadCityList(self,input_file_path=''):
        """从文件中读取字符串 进行分割 存入list 中并返回
        """
        try:
            with open(input_file_path, encoding='utf-8') as f:
                for line in f:
                    self.cityEnName.append(line.strip('\n').lower())
        except FileNotFoundError:
            print("文件无法找到，请确认路径和文件名正确.......")

        # print(cityCnName, cityEnName)
        # return cityEnName

    def fetch_XZ_weather(self,location):
        r = requests.get(API_XZ, params={
                                            'key': KEY_XZ,
                                            'location': location,
                                            'language': LANGUAGE_XZ,
                                            'unit': UNIT_XZ
                                        }, timeout=10)
        d ={}
        json2list(d,json.loads(r.text),str_key="XZ")
        temp = str(d['XZ_results_now_temperature']) + " C"
        self.result["XZ"] =  dict(zip(self.__formatWeather,
            [d['XZ_results_now_text'], temp,
                                       d['XZ_results_last_update']]
                                      )
                                 )
        # print(self.result)

    def fetch_OWM_weather(self,location):

        r = requests.get(API_OWM, params={
                                            'appid': APPID_OWM,
                                            'q': location,
                                            'units':UNIT_OWM
                                          }, timeout=10)
        d ={}
        json2list(d,json.loads(r.text),str_key="OWP")
        # print(d)
        temp = str(d['OWP_main_temp']) + " C"
        self.result["OWP"] = dict(zip(self.__formatWeather,[d['OWP_weather_main'], temp, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())]))
        # print(self.result)

    def fetch_Yahoo_weather(self,location):
        ysl = "select * from weather.forecast where woeid in (select woeid from geo.places(1) where text='" + location + "')"
        r = requests.get(API_Yahoo, params={
                                            'format':'json',
                                            'q': ysl,
                                          }, timeout=10)
        # print(result.text)
        d ={}
        json2list(d,json.loads(r.text),str_key="Yahoo")
        # print(d)
        temp =  str(float('%.2f' %((int(d['Yahoo_query_results_channel_item_condition_temp'])-32)*5/9))) + ' C' # 华摄度转换为摄氏度
        self.result["Yahoo"] = dict(zip(self.__formatWeather,
                                        [d['Yahoo_query_results_channel_item_condition_text'],
                                        temp, d['Yahoo_query_results_channel_item_condition_date']]))
        # print(self.result)

if __name__ == '__main__':
    w = WeatherAPI()
    w.getWeather('beijing')
    print(w.result)


from keras.preprocessing.image import ImageDataGenerator
from keras.layers import Dense, Dropout, Flatten, Input
from keras.layers import Conv2D, MaxPooling2D, Activation
from keras.callbacks import TensorBoard
import h5py
from keras.models import Model
from augmentation import load_occluders,occlude_with_objects
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True

file_path = 'VOC2011'
occluders = load_occluders(pascal_voc_root_path=file_path)
def random_synthetic_occlusion(image):
    """"
    take image and apply random synthetic occlusion
    return occluded image
    """
    occluded_image = occlude_with_objects(image, occluders)
    return occluded_image

train_datagen = ImageDataGenerator(rescale=1./255, preprocessing_function=random_synthetic_occlusion)
val_datagen = ImageDataGenerator(rescale=1./255)

train_generator = train_datagen.flow_from_directory(
    directory="E:\\thesis_work\\AffectNet\\train",
    target_size=(100, 100),
    color_mode="rgb",
    batch_size=500,
    class_mode="categorical",
    shuffle=True,
    seed=42)
valid_generator = val_datagen.flow_from_directory(
    directory="E:\\thesis_work\\AffectNet\\object_occluded_val\\two_40",
    target_size=(100, 100),
    color_mode="rgb",
    batch_size=500,
    class_mode="categorical",
    shuffle=False,
    seed=42)

input_main = Input(shape=(100, 100, 3))
x = Conv2D(16, kernel_size=(3, 3), activation='relu')(input_main)
x = Conv2D(32, (3, 3), activation='relu')(x)
x = MaxPooling2D(pool_size=(2, 2))(x)
x = Conv2D(64, (3, 3), activation='relu')(x)
x = MaxPooling2D(pool_size=(2, 2))(x)
x = Conv2D(128, (3, 3), activation='relu')(x)
x = MaxPooling2D(pool_size=(2, 2))(x)
x = Conv2D(256, (3, 3), activation='relu')(x)
x = MaxPooling2D(pool_size=(2, 2))(x)
x = Conv2D(512, (3, 3), activation='relu')(x)
x = MaxPooling2D(pool_size=(2, 2))(x)
x = Flatten()(x)
x = Dropout(0.2)(x)
out = Dense(6)(x)
out_last = Activation('softmax')(out)
model = Model(inputs=input_main, outputs=out_last)

#tensorboard callback
tensorboard = TensorBoard(log_dir="E:\\thesis_results\\fixed_val_occluded\\affectnet\\logs\\two_object_40")

model.compile(optimizer='adam',
              loss='categorical_crossentropy', metrics=['accuracy'])

STEP_SIZE_TRAIN=train_generator.n//train_generator.batch_size
STEP_SIZE_VALID=valid_generator.n//valid_generator.batch_size
model.fit_generator(generator=train_generator,
                    steps_per_epoch=STEP_SIZE_TRAIN,
                    validation_data=valid_generator,
                    validation_steps=STEP_SIZE_VALID,
                    epochs=10, verbose=2, callbacks=[tensorboard])

model.save("E:\\thesis_results\\fixed_val_occluded\\affectnet\\models\\two_object_40.h5")


from PyQt4.QtGui import QLabel, QSpinBox, QWidget, QVBoxLayout

class Widget(QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)

        self.spinInput = QSpinBox()
        self.spinInput.setRange(1, 100)
        self.spinInput.setValue(5)

        vboxLayout = QVBoxLayout()
        vboxLayout.addWidget(QLabel('Select the number of inputs'))
        vboxLayout.addWidget(QLabel('In this application you will examine some "larger" neurons.\n' +
                                    'They will have an arbitrary number of inputs.\n\n' +
                                    'First, you need to select the number of inputs.\n' +
                                    'The more inputs the neuron will have, the more numbers\n' +
                                    'you will need to supply for the weigth coefficients and\n' +
                                    'the input signal values.\n\n' +
                                    'If you don\'t know what to do, just accept the default value and click "Next".\n' +
                                    'After performing some experiments, you always can go back and\n' +
                                    'select a different number of inputs.'))
        vboxLayout.addWidget(QLabel('Number of inputs:'))
        vboxLayout.addWidget(self.spinInput)
        self.setLayout(vboxLayout)


from fns_scrape import *

def get_last_page_num(base_link):
    all_links = request_and_find_type(base_link, "a")
    return int(search_for_text(all_links, "href=\".*audio.books.*?(\d+).*\".*title=\"Last")[0])

if __name__ == '__main__':
    sysargs = get_arguments()
    base_link = "http://audiobookbay.me/audio-books/type/{}/".format(sysargs['tag'])
    total_pages = get_last_page_num(base_link); p = 1
    book_file_name = "abb_booklist_{}.txt".format(sysargs['tag'])
    with open(book_file_name, 'w') as f: pass

    all_abb_books = []
    for p in range(1, total_pages + 1):
        print("Searching through Page {}...".format(p))
        page_id = '' if p == 1 else "page/" + str(p) + "/"
        current_link = base_link + page_id

        all_links = request_and_find_type(current_link, "a")
        book_names = search_for_text(all_links, "audio-books.*bookmark.*title=\"(.*)\"")
        print("Adding the following books to the list:\n\t{}".format("\n\t".join(book_names)))
        all_abb_books = all_abb_books + book_names
        with open(book_file_name, 'a') as f:
            [f.write("{}\n".format(x)) for x in book_names]


import logging
import json
import zlib
import traceback
import struct
import random
import socket
from logging.handlers import DatagramHandler

WAN_CHUNK, LAN_CHUNK = 1420, 8154

class GELFHandler(DatagramHandler):
    def __init__(self, host, port, chunk_size=WAN_CHUNK):
        self.chunk_size = chunk_size
        DatagramHandler.__init__(self, host, port)

    def send(self, s):
        if len(s) < self.chunk_size:
            DatagramHandler.send(self, s)
        else:
            for chunk in ChunkedGELF(s, self.chunk_size):
                DatagramHandler.send(self, chunk)

    def makePickle(self, record):
        message_dict = self.make_message_dict(record)
        return zlib.compress(json.dumps(message_dict))

    def convert_level_to_syslog(self, level):
        return {
            logging.CRITICAL: 2,
            logging.ERROR: 3,
            logging.WARNING: 4,
            logging.INFO: 6,
            logging.DEBUG: 7,
        }.get(level, level)

    def get_full_message(self, exc_info):
        return traceback.format_exc(exc_info) if exc_info else ''

    def make_message_dict(self, record):
        d = {
            'version': "1.0",
            'host': socket.gethostname(),
            'short_message': record.getMessage(),
            'full_message': self.get_full_message(record.exc_info),
            'timestamp': record.created,
            'level': self.convert_level_to_syslog(record.levelno),
            'facility': record.name,
            'file': record.pathname,
            'line': record.lineno,
            '_function': record.funcName,
            '_pid': record.process,
            '_thread_name': record.threadName,
        }
        # record.processName was added in Python 2.6.2
        if hasattr(record, 'processName'):
            d['_process_name'] = record.processName
        return d

class ChunkedGELF(object):
    def __init__(self, message, size):
        self.message = message
        self.size = size
        self.pieces = struct.pack('>H', (len(message) / size) + 1)
        self.id = struct.pack('Q', random.randint(0, 0xFFFFFFFFFFFFFFFF)) * 4

    def message_chunks(self):
        return (self.message[i:i+self.size] for i
                    in range(0, len(self.message), self.size))

    def encode(self, sequence, chunk):
        return ''.join([
            '\x1e\x0f',
            self.id,
            struct.pack('>H', sequence),
            self.pieces,
            chunk
        ])

    def __iter__(self):
        for sequence, chunk in enumerate(self.message_chunks()):
            yield self.encode(sequence, chunk)


# -*- coding: utf-8 -*-

"""
    StyleGAN2 pytorch

    @author: samuel ko
    @date:   2019.12.13

    @notice: 1) fused_conv: unsupport
             2) 4x4 upfirdn kernel: (transfer to 3x3 upfirdn kernel)

    @date:   2019.12.18

    @update: 1) fix upfirdn2d [1, 3, 1] to original [1, 3, 3, 1] in D_stylegan2 and Upsample2d.
             2) use_wscale = True (default), gain = 1 (default).
             3) update he_std calculation method to coordinate with the original repo.
             4)
"""

import os
import torch.nn.functional as F
import torch.nn as nn
import numpy as np
import torch
from collections import OrderedDict

from utils.libs import _setup_kernel, _approximate_size
from opts.opts import TrainOptions

# =========================================================================
#   Define components for G_mapping & G_synthesis_stylegan2 & D_stylegan2
# =========================================================================

class PixelNorm(nn.Module):
    def __init__(self, epsilon=1e-8):
        """
            @notice: avoid in-place ops.
            https://discuss.pytorch.org/t/encounter-the-runtimeerror-one-of-the-variables-needed-for-gradient-computation-has-been-modified-by-an-inplace-operation/836/3
        """
        super(PixelNorm, self).__init__()
        self.epsilon = epsilon

    def forward(self, x):
        tmp = torch.mul(x, x)  # or x ** 2
        tmp1 = torch.rsqrt(torch.mean(tmp, dim=1, keepdim=True) + self.epsilon)

        return x * tmp1

class BiasAdd(nn.Module):

    def __init__(self,
                 channels,
                 opts,
                 act='linear', alpha=None, gain=None, lrmul=1):
        """
            BiasAdd
        """
        super(BiasAdd, self).__init__()

        self.opts = opts
        self.bias = (torch.nn.Parameter(torch.zeros(channels, 1, 1)) * lrmul).to(self.opts.device)

        self.act = act
        self.alpha = alpha if alpha is not None else 0.2
        self.gain = gain if gain is not None else 1.0

    def forward(self, x):
        # Pass Add bias.
        x = x + self.bias

        # Evaluate activation function.
        if self.act == "linear":
            pass
        elif self.act == 'lrelu':
            x = F.leaky_relu(x, self.alpha, inplace=True)
            x = x * np.sqrt(2)  # original repo def_gain=np.sqrt(2).

        # Scale by gain.
        if self.gain != 1:
            x = x * self.gain

        return x

class FC(nn.Module):
    def __init__(self,
                 in_channels,
                 out_channels,
                 gain=1,
                 use_wscale=True,
                 lrmul=1.0,
                 bias=True,
                 act='lrelu',
                 mode='normal'):
        """
            The complete conversion of Dense/FC/Linear Layer of original Tensorflow version.
        """
        super(FC, self).__init__()
        he_std = gain / ((in_channels * out_channels) ** (0.5))  # He init
        if use_wscale:
            init_std = 1.0 / lrmul
            self.w_lrmul = he_std * lrmul
        else:
            init_std = he_std / lrmul
            self.w_lrmul = lrmul

        self.weight = torch.nn.Parameter(torch.randn(out_channels, in_channels) * init_std)
        if bias:
            self.bias = torch.nn.Parameter(torch.zeros(out_channels))
            self.b_lrmul = lrmul
        else:
            self.bias = None

        self.act = act
        self.mode = mode

    def forward(self, x):
        if self.bias is not None and self.mode != 'modulate':
            out = F.linear(x, self.weight * self.w_lrmul, self.bias * self.b_lrmul)
        elif self.bias is not None and self.mode == 'modulate':
            out = F.linear(x, self.weight * self.w_lrmul, self.bias * self.b_lrmul) + 1
        else:
            out = F.linear(x, self.weight * self.w_lrmul)

        if self.act == 'lrelu':
            out = F.leaky_relu(out, 0.2, inplace=True)
            out = out * np.sqrt(2)  # original repo def_gain=np.sqrt(2).
            return out
        elif self.act == 'linear':
            return out

        return out

class Conv2d(nn.Module):
    def __init__(self,
                 input_channels,
                 output_channels,
                 kernel_size,
                 gain=1,
                 use_wscale=False,
                 lrmul=1,
                 bias=True):
        super().__init__()

        assert kernel_size >= 1 and kernel_size % 2 == 1
        he_std = gain / ((input_channels * output_channels * kernel_size * kernel_size) ** (0.5))  # He init
        self.kernel_size = kernel_size
        if use_wscale:
            init_std = 1.0 / lrmul
            self.w_lrmul = he_std * lrmul
        else:
            init_std = he_std / lrmul
            self.w_lrmul = lrmul

        self.weight = torch.nn.Parameter(
            torch.randn(output_channels, input_channels, kernel_size, kernel_size) * init_std)
        if bias:
            self.bias = torch.nn.Parameter(torch.zeros(output_channels))
            self.b_lrmul = lrmul
        else:
            self.bias = None

    def forward(self, x):
        if self.bias is not None:
            return F.conv2d(x, self.weight * self.w_lrmul, self.bias * self.b_lrmul, padding=self.kernel_size // 2)
        else:
            return F.conv2d(x, self.weight * self.w_lrmul, padding=self.kernel_size // 2)

class FromRGB(nn.Module):
    """
        default non_linearity: LeakyReLU(0.2), def_gain= np.sqrt(2).
    """

    def __init__(self, input_channels, output_channels, use_wscale=True, lrmul=1):
        super().__init__()
        self.conv = Conv2d(input_channels=input_channels,
                           output_channels=output_channels,
                           kernel_size=1, use_wscale=use_wscale, lrmul=lrmul)

    def forward(self, x):
        x, y = x
        y1 = self.conv(y)
        out = F.leaky_relu(y1, 0.2, inplace=True)
        out = out * np.sqrt(2)  # original repo def_gain=np.sqrt(2).
        return out if x is None else out + x

class ModulatedConv2d(nn.Module):
    """
        Modulated convolution layer for G_synthesis_stylegan2.

        @date: 2019.12.19
        @update: 1) initialization update (He init).
                 2) refact ModulatedConv2d.
    """

    def __init__(self, input_channels, output_channels,
                 kernel_size,
                 opts,
                 k=[1, 3, 3, 1],
                 dlatent_size=512,
                 up=False,
                 down=False,
                 demodulate=True,
                 gain=1,
                 use_wscale=True,
                 lrmul=1,
                 fused_modconv=True):
        super().__init__()
        assert kernel_size >= 1 and kernel_size % 2 == 1

        self.demodulate = demodulate
        self.fused_modconv = fused_modconv
        self.up, self.down = up, down
        self.fmaps = output_channels
        self.opts = opts

        self.conv = Conv2d(input_channels=input_channels,
                           output_channels=output_channels,
                           kernel_size=1, use_wscale=use_wscale, lrmul=lrmul)

        he_std = gain / ((input_channels * output_channels * kernel_size * kernel_size) ** (0.5))  # He init
        self.kernel_size = kernel_size
        if use_wscale:
            init_std = 1.0 / lrmul
            self.w_lrmul = he_std * lrmul
        else:
            init_std = he_std / lrmul
            self.w_lrmul = lrmul

        self.w = torch.nn.Parameter(
            torch.randn(output_channels, input_channels, kernel_size, kernel_size) * init_std).to(self.opts.device)
        self.convH, self.convW = self.w.shape[2:]

        self.dense = FC(dlatent_size, input_channels, gain, lrmul=lrmul, use_wscale=use_wscale, mode='modulate')

        self.upsample = UpConvsample2d(kernel_size=kernel_size, k=k, opts=opts)

    def forward(self, x):
        x, y = x
        if len(y.shape) > 2:
            # y is dlatent in ToRGB.
            y = y.squeeze(1)
        # x Input: N, C, H, W (NxCx4x4, NxCx8x8, NxCx16x16, ...)
        # y Input: Disentangled latents(W) [minibatch, 1, dlatent_size].

        # Modulate.
        s = self.dense(y)  # [BI] Transform incoming W to style.

        # BOIkk ---> BkkOI  ---> BkkIO
        self.ww = self.w.unsqueeze(0)
        self.ww = self.ww.repeat(s.shape[0], 1, 1, 1, 1)
        self.ww = self.ww.permute(0, 3, 4, 1, 2)
        self.ww = self.ww * s.unsqueeze(1).unsqueeze(1).unsqueeze(1).to(self.opts.device)  # [BkkOI] Scale input feature maps.
        self.ww = self.ww.permute(0, 1, 2, 4, 3)    # [BkkIO]

        # Demodulate.
        if self.demodulate:
            d = torch.mul(self.ww, self.ww)
            d = torch.rsqrt(torch.mean(d, dim=[1, 2, 3]) + 1e-8)                # [BO] Scaling factor.
            self.ww = self.ww * d.unsqueeze(1).unsqueeze(1).unsqueeze(1)        # [BkkIO] Scale output feature maps.

        # Reshape/scale input.
        if self.fused_modconv:
            x = x.view(1, -1, x.shape[2], x.shape[3])                           # Fused => reshape minibatch to convolution groups.
            self.w_new = torch.reshape(self.ww.permute(0, 4, 3, 1, 2), (-1, x.shape[1], self.ww.shape[1], self.ww.shape[2]))
        else:
            x = x * s.unsqueeze(-1).unsqueeze(-1).to(self.opts.device)          # [BIhw] Not fused => scale input activations.
            self.w_new = self.w.unsqueeze(0).repeat(s.shape[0], 1, 1, 1, 1)

        # Convolution with optional up/downsampling.
        if self.up:
            x = self.upsample([x, self.w_new])
        elif self.down:
            pass
        else:
            x = F.conv2d(x,
                         self.w_new * self.w_lrmul,
                         padding=self.w_new.shape[2] // 2)
        # Reshape/scale output.
        if self.fused_modconv:
            x = x.view(-1, self.fmaps, x.shape[2], x.shape[3])                 # Fused => reshape convolution groups back to minibatch.
        elif self.demodulate:
            x = x * d.unsqueeze(1).unsqueeze(1)                                # [BOhw] Not fused => scale output activations.

        return x

class ToRGB(nn.Module):
    """
        default non_linearity: LeakyReLU(0.2), def_gain= np.sqrt(2).

        2019.12.18 fix.
    """

    def __init__(self, input_channels, output_channels,
                 res,
                 opts,
                 use_wscale=True,
                 lrmul=1,
                 gain=1,
                 fused_modconv=True):
        super().__init__()
        assert res >= 2

        self.modulated_conv2d = ModulatedConv2d(input_channels=input_channels,
                                                output_channels=output_channels,
                                                kernel_size=1,
                                                use_wscale=use_wscale,
                                                lrmul=lrmul,
                                                gain=gain,
                                                demodulate=False,
                                                fused_modconv=fused_modconv,
                                                opts=opts)
        self.biasAdd = BiasAdd(opts=opts,
                               act='linear',
                               channels=output_channels)

        self.res = res
        self.opts = opts

    def forward(self, x):
        x, y, dlatent = x
        dlatent = dlatent[:, self.res * 2 - 3]

        x = self.modulated_conv2d([x, dlatent])
        x = self.biasAdd(x)

        if y is None:
            return x
        else:
            return x + y

class GLayer(nn.Module):
    """
        GLayer.
    """

    def __init__(self, input_channels, output_channels,
                 layer_idx,
                 opts,
                 k=[1, 3, 3, 1],
                 randomize_noise=True,
                 up=False,
                 use_wscale=True,
                 lrmul=1,
                 fused_modconv=True,
                 act='lrelu'):
        super().__init__()

        self.randomize_noise = randomize_noise
        self.opts = opts
        self.up = up
        self.layer_idx = layer_idx

        self.modulated_conv2d = ModulatedConv2d(input_channels=input_channels,
                                                output_channels=output_channels,
                                                kernel_size=3,
                                                k=k,
                                                use_wscale=use_wscale,
                                                lrmul=lrmul,
                                                demodulate=True,
                                                fused_modconv=fused_modconv,
                                                up=up,
                                                opts=opts)

        self.noise_strength = torch.nn.Parameter(torch.zeros(1)).to(self.opts.device)
        self.biasAdd = BiasAdd(act=act, channels=output_channels, opts=opts)

    def forward(self, x):
        x, dlatent = x
        if len(dlatent.shape) > 2:
            dlatent = dlatent[:, self.layer_idx]

        x = self.modulated_conv2d([x, dlatent])

        noise = 0
        if self.randomize_noise:
            noise = torch.randn(x.shape[0], 1, x.shape[2], x.shape[3]).to(self.opts.device)

        x = x + noise * self.noise_strength
        x = self.biasAdd(x)

        return x

class Upsample2d(nn.Module):
    def __init__(self,
                 opts,
                 k=[1, 3, 3, 1],
                 factor=2,
                 down=1,
                 gain=1):
        """
            Upsample2d method in G_synthesis_stylegan2.
        :param k: FIR filter of the shape `[firH, firW]` or `[firN]` (separable).
                  The default is `[1] * factor`, which corresponds to average pooling.
        :param factor: Integer downsampling factor (default: 2).
        :param gain:   Scaling factor for signal magnitude (default: 1.0).

            Returns: Tensor of the shape `[N, C, H // factor, W // factor]`
        """
        super().__init__()
        assert isinstance(factor, int) and factor >= 1, "factor must be larger than 1! (default: 2)"

        self.gain = gain
        self.factor = factor
        self.opts = opts

        self.k = _setup_kernel(k) * (self.gain * (factor ** 2))  # 4 x 4
        self.k = torch.FloatTensor(self.k).unsqueeze(0).unsqueeze(0)
        self.k = nn.Parameter(self.k, requires_grad=False).to(self.opts.device)

        self.p = self.k.shape[0] - self.factor

        self.padx0, self.pady0 = (self.p + 1) // 2 + factor - 1, (self.p + 1) // 2 + factor - 1
        self.padx1, self.pady1 = self.p // 2, self.p // 2

        self.kernelH, self.kernelW = self.k.shape[2:]
        self.down = down

    def forward(self, x):

        y = x.clone()
        y = y.reshape([-1, x.shape[2], x.shape[3], 1])  # N C H W ---> N*C H W 1

        inC, inH, inW = x.shape[1:]
        # step 1: upfirdn2d

        # 1) Upsample
        y = torch.reshape(y, (-1, inH, 1, inW, 1, 1))
        y = F.pad(y, (0, 0, self.factor - 1, 0, 0, 0, self.factor - 1, 0, 0, 0, 0, 0))
        y = torch.reshape(y, (-1, 1, inH * self.factor, inW * self.factor))

        # 2) Pad (crop if negative).
        y = F.pad(y, (0, 0,
                      max(self.pady0, 0), max(self.pady1, 0),
                      max(self.padx0, 0), max(self.padx1, 0),
                      0, 0
                      ))
        y = y[:,
              max(-self.pady0, 0): y.shape[1] - max(-self.pady1, 0),
              max(-self.padx0, 0): y.shape[2] - max(-self.padx1, 0),
              :]
        # 3) Convolve with filter.

        y = y.permute(0, 3, 1, 2)  # N*C H W 1 --> N*C 1 H W
        y = y.reshape(-1, 1, inH * self.factor + self.pady0 + self.pady1, inW * self.factor + self.padx0 + self.padx1)
        y = F.conv2d(y, self.k)
        y = y.view(-1, 1,
                   inH * self.factor + self.pady0 + self.pady1 - self.kernelH + 1,
                   inW * self.factor + self.padx0 + self.padx1 - self.kernelW + 1)

        # 4) Downsample (throw away pixels).
        if inH * self.factor != y.shape[1]:
            y = F.interpolate(y, size=(inH * self.factor, inW * self.factor))
        y = y.permute(0, 2, 3, 1)
        y = y.reshape(-1, inC, inH * self.factor, inW * self.factor)

        return y

class UpConvsample2d(nn.Module):
    """
        @date: 2019.12.19
        @update: revise UpConvsample2d to coord with the original tf version.
    """
    def __init__(self,
                 opts,
                 kernel_size=3,
                 k=[1, 3, 3, 1],
                 factor=2,
                 gain=1,
                 down=1,
                 use_wscale=True,
                 lrmul=1,
                 bias=True):
        """
            UpConvsample2D method in G_synthesis_stylegan2.
        :param k: FIR filter of the shape `[firH, firW]` or `[firN]` (separable).
                  The default is `[1] * factor`, which corresponds to average pooling.
        :param factor: Integer downsampling factor (default: 2).
        :param gain:   Scaling factor for signal magnitude (default: 1.0).

            Returns: Tensor of the shape `[N, C, H * factor, W * factor]`
        """
        super().__init__()
        assert isinstance(factor, int) and factor >= 1, "factor must be larger than 1! (default: 2)"

        self.gain = gain
        self.factor = factor

        self.k = _setup_kernel(k) * (self.gain * (factor ** 2))  # 4 x 4
        self.k = torch.FloatTensor(self.k).unsqueeze(0).unsqueeze(0)
        # todo: must wrap self.k into nn.Parameter, or the VRAM exceeds the limits.
        self.k = nn.Parameter(self.k, requires_grad=False).to(opts.device)

        self.p = self.k.shape[0] - self.factor - (kernel_size - 1)

        self.padx0, self.pady0 = (self.p + 1) // 2 + factor - 1, (self.p + 1) // 2 + factor - 1
        self.padx1, self.pady1 = self.p // 2 + 1, self.p // 2 + 1

        self.kernelH, self.kernelW = self.k.shape[2:]
        self.down = down

    def forward(self, x):
        x, w = x
        inC, outC, convH, convW = w.shape[0], w.shape[1], w.shape[2], w.shape[3]

        w = w.reshape(outC, inC, convH, convW)
        x = F.conv_transpose2d(x, w, stride=self.factor)

        # step 2: upfirdn2d
        y = x.clone()
        y = y.reshape([-1, x.shape[2], x.shape[3], 1])  # N C H W ---> N*C H W 1

        inC, inH, inW = x.shape[1:]
        # 1) Upsample
        y = torch.reshape(y, (-1, inH, inW, 1))

        # 2) Pad (crop if negative).
        y = F.pad(y, (0, 0,
                      max(self.pady0, 0), max(self.pady1, 0),
                      max(self.padx0, 0), max(self.padx1, 0),
                      0, 0
                      ))
        y = y[:,
              max(-self.pady0, 0): y.shape[1] - max(-self.pady1, 0),
              max(-self.padx0, 0): y.shape[2] - max(-self.padx1, 0),
              :]

        # 3) Convolve with filter.
        y = y.permute(0, 3, 1, 2)  # N*C H W 1 --> N*C 1 H W
        y = y.reshape(-1, 1, inH + self.pady0 + self.pady1, inW + self.padx0 + self.padx1)
        y = F.conv2d(y, self.k)
        y = y.view(-1, 1, inH + self.pady0 + self.pady1 - self.kernelH + 1,
                   inW + self.padx0 + self.padx1 - self.kernelW + 1)

        # 4) Downsample (throw away pixels).
        if inH != y.shape[1] or inH % 2 != 0:
            inH = inW = _approximate_size(inH)
            y = F.interpolate(y, size=(inH, inW))
        y = y.permute(0, 2, 3, 1)
        y = y.reshape(-1, inC, inH, inW)

        return y

class ConvDownsample2d(nn.Module):
    def __init__(self,
                 kernel_size,
                 input_channels,
                 output_channels,
                 k=[1, 3, 3, 1],
                 factor=2,
                 gain=1,
                 use_wscale=True,
                 lrmul=1,
                 bias=True):
        """
            ConvDownsample2D method in D_stylegan2.
        :param k: FIR filter of the shape `[firH, firW]` or `[firN]` (separable).
                  The default is `[1] * factor`, which corresponds to average pooling.
        :param factor: Integer downsampling factor (default: 2).
        :param gain:   Scaling factor for signal magnitude (default: 1.0).

            Returns: Tensor of the shape `[N, C, H // factor, W // factor]`
        """
        super().__init__()
        assert isinstance(factor, int) and factor >= 1, "factor must be larger than 1! (default: 2)"
        assert kernel_size >= 1 and kernel_size % 2 == 1

        he_std = gain / ((input_channels * output_channels * kernel_size * kernel_size) ** (0.5))  # He init
        self.kernel_size = kernel_size
        if use_wscale:
            init_std = 1.0 / lrmul
            self.w_lrmul = he_std * lrmul
        else:
            init_std = he_std / lrmul
            self.w_lrmul = lrmul

        # https://discuss.pytorch.org/t/gaussian-distribution/35031
        self.weight = torch.nn.Parameter(
            torch.randn(output_channels, input_channels, kernel_size, kernel_size) * init_std)
        self.convH, self.convW = self.weight.shape[2:]

        if bias:
            self.bias = torch.nn.Parameter(torch.zeros(output_channels))
            self.b_lrmul = lrmul
        else:
            self.bias = None

        self.gain = gain
        self.factor = factor

        self.k = _setup_kernel(k) * self.gain  # 3 x 3. (original 4 x 4).
        self.k = torch.FloatTensor(self.k).unsqueeze(0).unsqueeze(0).to('cuda')
        # todo: must wrap self.k into nn.Parameter, or the VRAM exceeds the limits.
        # self.k = nn.Parameter(self.k, requires_grad=False)
        self.k = nn.Parameter(self.k, requires_grad=False)

        self.p = (self.k.shape[-1] - self.factor) + (self.convW - 1)

        self.padx0, self.pady0 = (self.p + 1) // 2, (self.p + 1) // 2
        self.padx1, self.pady1 = self.p // 2, self.p // 2

        self.kernelH, self.kernelW = self.k.shape[2:]

    def forward(self, x):

        y = x.clone()
        y = y.reshape([-1, x.shape[2], x.shape[3], 1])  # N C H W ---> N*C H W 1

        inC, inH, inW = x.shape[1:]
        # step 1: upfirdn2d
        # 1) Upsample
        y = torch.reshape(y, (-1, inH, inW, 1))

        # 2) Pad (crop if negative).
        y = F.pad(y, (0, 0,
                      max(self.pady0, 0), max(self.pady1, 0),
                      max(self.padx0, 0), max(self.padx1, 0),
                      0, 0
                      ))
        y = y[:,
            max(-self.pady0, 0): y.shape[1] - max(-self.pady1, 0),
            max(-self.padx0, 0): y.shape[2] - max(-self.padx1, 0),
            :]

        # 3) Convolve with filter.
        y = y.permute(0, 3, 1, 2)  # N*C H W 1 --> N*C 1 H W
        y = y.reshape(-1, 1, inH + self.pady0 + self.pady1, inW + self.padx0 + self.padx1)
        # x1 = F.conv2d(x1, self.k, padding=self.kernelH // 2)
        y = F.conv2d(y, self.k)
        y = y.view(-1, 1, inH + self.pady0 + self.pady1 - self.kernelH + 1,
                   inW + self.padx0 + self.padx1 - self.kernelW + 1)

        # 4) Downsample (throw away pixels).
        if inH != y.shape[1]:
            y = F.interpolate(y, size=(inH, inW))
        y = y.permute(0, 2, 3, 1)
        y = y.reshape(-1, inC, inH, inW)

        # step 2: downsample (in general, stride = self.factor = 2)
        x1 = F.conv2d(y,
                      self.weight * self.w_lrmul,
                      self.bias * self.b_lrmul,
                      stride=self.factor,
                      padding=self.convW // 2)
        # step 3: non-linearity.
        out = F.leaky_relu(x1, 0.2, inplace=True)
        out = out * np.sqrt(2)  # original repo def_gain=np.sqrt(2).

        return out

class GBlock(nn.Module):
    """
        G_stylegan2 Basic Block.
    """

    def __init__(self,
                 input_channels,
                 output_channels,
                 layer_idx,
                 opts,
                 k=[1, 3, 3, 1],
                 use_wscale=True,
                 lrmul=1,
                 architecture='skip'):
        super().__init__()

        self.arch = architecture

        self.conv0up = GLayer(input_channels, output_channels,
                              layer_idx,
                              up=True,
                              k=k,
                              use_wscale=use_wscale,
                              lrmul=lrmul,
                              opts=opts)
        self.conv1 = GLayer(output_channels, output_channels,
                            layer_idx + 1,
                            up=False,
                            k=k,
                            use_wscale=use_wscale,
                            lrmul=lrmul,
                            opts=opts)

    def forward(self, x):
        x, dlatent = x
        x = self.conv0up([x, dlatent])
        x = self.conv1([x, dlatent])

        if self.arch == 'resnet':
            raise Exception("unsupported resnet architecture yet~")

        return x

class DBlock(nn.Module):
    """
        D_stylegan2 Basic Block.
    """

    def __init__(self, in1, in2, out3,
                 use_wscale=True,
                 lrmul=1,
                 resample_kernel=[1, 3, 3, 1],
                 architecture='resnet'):
        super().__init__()

        self.arch = architecture

        self.conv0 = Conv2d(input_channels=in1,
                            output_channels=in2,
                            kernel_size=3, use_wscale=use_wscale, lrmul=lrmul,
                            bias=True)

        self.conv1_down = ConvDownsample2d(kernel_size=3,
                                           input_channels=in2,
                                           output_channels=out3,
                                           k=resample_kernel)

        self.res_conv2_down = ConvDownsample2d(kernel_size=1,
                                               input_channels=in1,
                                               output_channels=out3,
                                               k=resample_kernel)

    def forward(self, x):
        t = x.clone()

        x = self.conv0(x)
        x = self.conv1_down(x)

        if self.arch == 'resnet':
            t = self.res_conv2_down(t)
            x = (x + t) * (1 / np.sqrt(2))
        return x

# =========================================================================
#   Minibatch standard deviation layer. (D_stylegan2)
# =========================================================================

class Minibatch_stddev_layer(nn.Module):
    """
        Minibatch standard deviation layer. (D_stylegan2)
    """

    def __init__(self, group_size=4, num_new_features=1):
        super().__init__()

        self.group_size = group_size
        self.num_new_features = num_new_features

    def forward(self, x):
        n, c, h, w = x.shape

        group_size = min(n, self.group_size)  # Minibatch must be divisible by (or smaller than) group_size.
        y = x.view(group_size, -1,
                   self.num_new_features,
                   c // self.num_new_features,
                   h, w)  # [GMncHW] Split minibatch into M groups of size G. Split channels into n channel groups c.
        y = y - torch.mean(y, dim=0, keepdim=True)  # [GMncHW] Subtract mean over group.
        y = torch.mean(y ** 2, dim=0)  # [MncHW]  Calc variance over group.
        y = torch.sqrt(y + 1e-8)  # [MncHW]  Calc stddev over group.
        y = torch.mean(y, dim=[2, 3, 4], keepdim=True)  # [Mn111]  Take average over fmaps and pixels.
        y = torch.mean(y, dim=2)  # [Mn11]   Split channels into c channel groups
        # How to tile a tensor? https://discuss.pytorch.org/t/how-to-tile-a-tensor/13853
        y = y.repeat(group_size, 1, h, w)  # [NnHW]  Replicate over group and pixels.

        return torch.cat([x, y], 1)  # [NCHW]  Append as new fmap.

# =========================================================================
#   Define G_mapping
#   1) support variant mapping_fmaps in G_mapping.
# =========================================================================

class G_mapping(nn.Module):
    def __init__(self,
                 mapping_fmaps=512,
                 dlatent_size=512,
                 resolution=1024,
                 label_size=0,  # Label dimensionality, 0 if no labels. (non-support)
                 mapping_layers=8,  # Number of mapping layers.
                 normalize_latents=True,  # Normalize latent vectors (Z) before feeding them to the mapping layers?
                 use_wscale=True,  # Enable equalized learning rate?
                 lrmul=0.01,  # Learning rate multiplier for the mapping layers.
                 gain=1  # original gain in tensorflow.
                 ):
        super(G_mapping, self).__init__()
        self.mapping_fmaps = mapping_fmaps
        self.mapping_layers = mapping_layers

        self.fc1 = FC(self.mapping_fmaps, dlatent_size, gain=gain, lrmul=lrmul, use_wscale=use_wscale)
        self.fc2 = FC(dlatent_size, dlatent_size, gain=gain, lrmul=lrmul, use_wscale=use_wscale)
        self.fc3 = FC(dlatent_size, dlatent_size, gain=gain, lrmul=lrmul, use_wscale=use_wscale)
        self.fc4 = FC(dlatent_size, dlatent_size, gain=gain, lrmul=lrmul, use_wscale=use_wscale)
        self.fc5 = FC(dlatent_size, dlatent_size, gain=gain, lrmul=lrmul, use_wscale=use_wscale)
        self.fc6 = FC(dlatent_size, dlatent_size, gain=gain, lrmul=lrmul, use_wscale=use_wscale)
        self.fc7 = FC(dlatent_size, dlatent_size, gain=gain, lrmul=lrmul, use_wscale=use_wscale)
        self.fc8 = FC(dlatent_size, dlatent_size, gain=gain, lrmul=lrmul, use_wscale=use_wscale)

        self.normalize_latents = normalize_latents
        self.resolution_log2 = int(np.log2(resolution))
        self.num_layers = self.resolution_log2 * 2 - 2
        self.pixel_norm = PixelNorm()

    def forward(self, x):
        if self.normalize_latents:
            x = self.pixel_norm(x)

        out = self.fc1(x)
        for _ in range(2, self.mapping_layers + 1):
            out = getattr(self, 'fc{}'.format(_))(out)

        out = out.unsqueeze(1)
        out = out.repeat(1, self.num_layers, 1)

        return out

# =========================================================================
#   Define G_synthesis_stylegan2
# =========================================================================

class G_synthesis_stylegan2(nn.Module):
    def __init__(self,
                 opts,
                 fmap_base=8 << 10,  # stylegan1 8192 (8 << 10), stylegan2 16384 (16 << 10)
                 num_channels=3,  # Number of output color channels.
                 dlatent_size=512,  # Disentangled latent (W) dimensionality.
                 resolution=1024,  # Output resolution.
                 randomize_noise=True,
                 # True = randomize noise inputs every time (non-deterministic), False = read noise inputs from variables.
                 fmap_decay=1.0,  # log2 feature map reduction when doubling the resolution.
                 fmap_min=1,  # Minimum number of feature maps in any layer.
                 fmap_max=512,  # Maximum number of feature maps in any layer.
                 architecture='skip',  # Architecture: 'orig', 'skip', 'resnet'.
                 use_wscale=True,  # Enable equalized learning rate?
                 lrmul=0.01,  # Learning rate multiplier for the mapping layers.
                 gain=1,  # original gain in tensorflow.
                 act='lrelu',  # Activation function: 'linear', 'lrelu'.
                 resample_kernel=[1, 3, 3, 1],
                 # Low-pass filter to apply when resampling activations. None = no filtering.
                 fused_modconv=True,  # Implement modulated_conv2d_layer() as a single fused op?
                 ):
        super(G_synthesis_stylegan2, self).__init__()

        resolution_log2 = int(np.log2(resolution))
        assert resolution == 2 ** resolution_log2 and resolution >= 4
        self.nf = lambda stage: np.clip(int(fmap_base / (2.0 ** (stage * fmap_decay))), fmap_min, fmap_max)
        assert architecture in ['orig', 'skip', 'resnet']
        num_layers = resolution_log2 * 2 - 2

        self.arch = architecture
        self.act = act
        self.resolution_log2 = resolution_log2
        self.opts = opts

        # Primary inputs.
        self.x = nn.Parameter(torch.randn(1, self.nf(1), 4, 4), requires_grad=False).to(self.opts.device)

        # layer0
        self.rgb0 = ToRGB(input_channels=self.nf(1),
                          output_channels=num_channels,
                          res=2,
                          opts=opts)
        self.glayer0 = GLayer(input_channels=self.nf(1),
                              output_channels=self.nf(1),
                              layer_idx=0,
                              k=resample_kernel,
                              randomize_noise=randomize_noise,
                              act=self.act,
                              up=False,
                              opts=opts)

        # rgb layer
        self.rgb3 = ToRGB(input_channels=self.nf(3),
                          output_channels=num_channels,
                          res=3,
                          opts=opts,
                          fused_modconv=fused_modconv)
        self.rgb4 = ToRGB(input_channels=self.nf(4),
                          output_channels=num_channels,
                          res=4,
                          opts=opts,
                          fused_modconv=fused_modconv)
        self.rgb5 = ToRGB(input_channels=self.nf(5),
                          output_channels=num_channels,
                          res=5,
                          opts=opts,
                          fused_modconv=fused_modconv)
        self.rgb6 = ToRGB(input_channels=self.nf(6),
                          output_channels=num_channels,
                          res=6,
                          opts=opts,
                          fused_modconv=fused_modconv)
        self.rgb7 = ToRGB(input_channels=self.nf(7),
                          output_channels=num_channels,
                          res=7,
                          opts=opts,
                          fused_modconv=fused_modconv)
        self.rgb8 = ToRGB(input_channels=self.nf(8),
                          output_channels=num_channels,
                          res=8,
                          opts=opts,
                          fused_modconv=fused_modconv)
        self.rgb9 = ToRGB(input_channels=self.nf(9),
                          output_channels=num_channels,
                          res=9,
                          opts=opts,
                          fused_modconv=fused_modconv)
        self.rgb10 = ToRGB(input_channels=self.nf(10),
                           output_channels=num_channels,
                           res=10,
                           opts=opts,
                           fused_modconv=fused_modconv)

        # block layer
        self.block3 = GBlock(input_channels=self.nf(2),
                             output_channels=self.nf(3),
                             layer_idx=1,
                             opts=opts)
        self.block4 = GBlock(input_channels=self.nf(3),
                             output_channels=self.nf(4),
                             layer_idx=3,
                             opts=opts)
        self.block5 = GBlock(input_channels=self.nf(4),
                             output_channels=self.nf(5),
                             layer_idx=5,
                             opts=opts)
        self.block6 = GBlock(input_channels=self.nf(5),
                             output_channels=self.nf(6),
                             layer_idx=7,
                             opts=opts)
        self.block7 = GBlock(input_channels=self.nf(6),
                             output_channels=self.nf(7),
                             layer_idx=9,
                             opts=opts)
        self.block8 = GBlock(input_channels=self.nf(7),
                             output_channels=self.nf(8),
                             layer_idx=11,
                             opts=opts)
        self.block9 = GBlock(input_channels=self.nf(8),
                             output_channels=self.nf(9),
                             layer_idx=13,
                             opts=opts)
        self.block10 = GBlock(input_channels=self.nf(9),
                              output_channels=self.nf(10),
                              layer_idx=15,
                              opts=opts)
        # upsample layer
        self.upsample2d = Upsample2d(opts=opts)

    def forward(self, dlatent):
        # Early Layers
        y = None
        x = self.x.repeat(dlatent.shape[0], 1, 1, 1)
        x = self.glayer0([x, dlatent[:, 0]])

        if self.arch == 'skip':
            y = self.rgb0([x, y, dlatent])

        # Main layers.
        # for res in range(3, self.resolution_log2 + 1):
        for res in range(3, self.resolution_log2 + 1):
            x = getattr(self, 'block{}'.format(res))([x, dlatent])
            if self.arch == 'skip':
                y = self.upsample2d(y)
            if self.arch == 'skip' or res == self.resolution_log2:
                y = getattr(self, 'rgb{}'.format(res))([x, y, dlatent])

        # [-1, 1]
        # y = y / torch.max(torch.abs(y))
        return y

# =========================================================================
#   Combine G_mapping & G_synthesis_stylegan2 in G_stylegan2
# =========================================================================

class G_stylegan2(nn.Module):
    def __init__(self,
                 opts,
                 return_dlatents=True,
                 fmap_base=8 << 10,  # stylegan1 8192 (8 << 10), stylegan2 16384 (16 << 10)
                 num_channels=3,  # Number of output color channels.
                 mapping_fmaps=512,
                 dlatent_size=512,  # Disentangled latent (W) dimensionality.
                 resolution=1024,  # Output resolution.
                 mapping_layers=8,  # Number of mapping layers.
                 randomize_noise=True,
                 fmap_decay=1.0,  # log2 feature map reduction when doubling the resolution.
                 fmap_min=1,  # Minimum number of feature maps in any layer.
                 fmap_max=512,  # Maximum number of feature maps in any layer.
                 architecture='skip',  # Architecture: 'orig', 'skip'.
                 act='lrelu',  # Activation function: 'linear', 'lrelu'.
                 lrmul=0.01,  # Learning rate multiplier for the mapping layers.
                 gain=1       # original gain in tensorflow.
                 ):
        super().__init__()
        assert architecture in ['orig', 'skip']

        self.return_dlatents = return_dlatents

        self.g_mapping = G_mapping(mapping_fmaps=mapping_fmaps,
                                   dlatent_size=dlatent_size,
                                   resolution=resolution,
                                   mapping_layers=mapping_layers,
                                   lrmul=lrmul,
                                   gain=gain)

        self.g_synthesis = G_synthesis_stylegan2(resolution=resolution,
                                                 architecture=architecture,
                                                 randomize_noise=randomize_noise,
                                                 fmap_base=fmap_base,
                                                 fmap_min=fmap_min,
                                                 fmap_max=fmap_max,
                                                 fmap_decay=fmap_decay,
                                                 act=act,
                                                 opts=opts)

    def forward(self, x):
        dlatent = self.g_mapping(x)
        x = self.g_synthesis(dlatent)

        if self.return_dlatents:
            return x, dlatent
        else:
            return x

# =========================================================================
#   Define D_stylegan2
#   1) support structure == origin & resnet. (skip is unsupport here.)
#   2) multi-label unsupport.
#   3) Almost coord with the original! (2019.12.18)
# =========================================================================

class D_stylegan2(nn.Module):
    def __init__(self,
                 resolution=1024,
                 fmap_base=8 << 10,  # stylegan1 8192 (8 << 10), stylegan2 16384 (16 << 10)
                 num_channels=3,
                 label_size=0,  # Dimensionality of the labels, 1 if no labels. Overridden based on dataset.
                 structure='resnet',  # Architecture: 'orig', 'resnet' (skip unsupported).
                 fmap_max=512,
                 fmap_min=1,
                 fmap_decay=1.0,
                 mbstd_group_size=4,  # Group size for the minibatch standard deviation layer, 0 = disable.
                 mbstd_num_features=1,  # Number of features for the minibatch standard deviation layer.
                 resample_kernel=[1, 3, 3, 1]
                 # Low-pass filter to apply when resampling activations. None = no filtering.
                 ):
        """
            Noitce: we only support input pic with height == width.

            if H or W >= 128, we use avgpooling2d to do feature map shrinkage.
            else: we use ordinary conv2d.
        """
        super().__init__()
        self.resolution_log2 = int(np.log2(resolution))
        assert resolution == 2 ** self.resolution_log2 and resolution >= 4
        self.nf = lambda stage: np.clip(int(fmap_base / (2.0 ** (stage * fmap_decay))), fmap_min, fmap_max)
        # fromrgb: fixed mode
        self.fromrgb = Conv2d(num_channels, self.nf(self.resolution_log2 - 1), kernel_size=1)

        assert structure in ['orig', 'skip', 'resnet']

        if structure == 'skip':
            raise Exception("skip in Discriminator is unsupported yet~")

        self.structure = structure
        self.label_size = label_size
        self.mbstd_group_size = mbstd_group_size

        # sub network
        self.fromrgb = FromRGB(input_channels=3,
                               output_channels=self.nf(self.resolution_log2 - 1),
                               use_wscale=True)

        self.dblock10 = DBlock(in1=self.nf(9), in2=self.nf(9), out3=self.nf(8), resample_kernel=resample_kernel)
        self.dblock9 = DBlock(in1=self.nf(8), in2=self.nf(8), out3=self.nf(7), resample_kernel=resample_kernel)
        self.dblock8 = DBlock(in1=self.nf(7), in2=self.nf(7), out3=self.nf(6), resample_kernel=resample_kernel)
        self.dblock7 = DBlock(in1=self.nf(6), in2=self.nf(6), out3=self.nf(5), resample_kernel=resample_kernel)
        self.dblock6 = DBlock(in1=self.nf(5), in2=self.nf(5), out3=self.nf(4), resample_kernel=resample_kernel)
        self.dblock5 = DBlock(in1=self.nf(4), in2=self.nf(4), out3=self.nf(3), resample_kernel=resample_kernel)
        self.dblock4 = DBlock(in1=self.nf(4), in2=self.nf(3), out3=self.nf(2), resample_kernel=resample_kernel)
        self.dblock3 = DBlock(in1=self.nf(3), in2=self.nf(2), out3=self.nf(1), resample_kernel=resample_kernel)
        self.dblock2 = DBlock(in1=self.nf(2), in2=self.nf(1), out3=self.nf(0), resample_kernel=resample_kernel)

        # 4x4
        self.minibatch_stddev = Minibatch_stddev_layer(mbstd_group_size, mbstd_num_features)
        self.conv_last = Conv2d(input_channels=self.nf(2) + mbstd_num_features,
                                output_channels=self.nf(1),
                                kernel_size=3)
        self.fc_last1 = FC(in_channels=fmap_base,
                           out_channels=self.nf(0))
        self.fc_last2 = FC(in_channels=self.nf(0),
                           out_channels=1,
                           act='linear')

    def forward(self, input):

        x_origin = None
        y = input
        # 1) Main Layers.
        x = self.fromrgb([x_origin, y])
        for res in range(self.resolution_log2, 2, -1):
            x = getattr(self, 'dblock{}'.format(res))(x)

        # 2) Final layers (4 x 4).
        if self.mbstd_group_size > 1:
            x = self.minibatch_stddev(x)
        x = self.conv_last(x)

        out = F.leaky_relu(x, 0.2, inplace=True)
        out = out * np.sqrt(2)

        _, c, h, w = out.shape
        out = out.view(-1, h * w * c)
        out = self.fc_last1(out)

        # 3) Output
        if self.label_size == 0:
            out = self.fc_last2(out)
            return out
        else:
            raise Exception("Sorry, multi-label unsupported right now.")

if __name__ == "__main__":
    # 1) G_mapping ok.
    # data = torch.randn([1, 512])
    # g = G_mapping()
    # print(g(data).shape)

    # 2) D_stylegan2 ok (upfirdn).
    from loss.loss import D_logistic_r1

    data = torch.randn(1, 3, 256, 256).cuda()
    print(torch.max(data))
    print(torch.min(data))
    # fake = torch.randn(1, 3, 256, 256).cuda()
    d = D_stylegan2(resolution=256,
                    structure='resnet',
                    resample_kernel=[1, 3, 3, 1]).cuda()
    print(d(data))
    # https://discuss.pytorch.org/t/one-of-the-differentiated-tensors-does-not-require-grad/54694
    # D_logistic_r1(fake, data, d)

    # 3) G_synthesis_stylegan2 Early Layers
    # data = torch.randn([5, 18, 512])
    # g_syn = G_synthesis_stylegan2(resolution=128)
    # print(g_syn(data).shape)

    # 3.1) ModulatedConv2d(up=True) UpConvsample2d
    # y = torch.randn([1, 512])
    # x = torch.randn(1, 3, 128, 128)
    # up1 = ModulatedConv2d(up=True,
    #                       input_channels=3,
    #                       output_channels=6,
    #                       kernel_size=3)
    # print(up1([x, y]).shape)

    # 3.2) Upsample2d
    # data = torch.randn(1, 3, 128, 128)
    # up = Upsample2d()
    # print(up(data).shape)

    # 4) G_combination
    # opts = TrainOptions().parse()
    # data = torch.randn([5, 512])
    # g = G_stylegan2(resolution=256,
    #                 mapping_layers=5,
    #                 opts=opts)
    # print(g(data).shape)
    # print(g(data).shape)
    # torch.Size([5, 3, 256, 256])


#!/usr/bin/env python3

from sklearn.feature_extraction.text import TfidfVectorizer
import sys
import csv
import numpy as np

def stringToWordVector(dataset, word_vocabulary):
    vectorizer = TfidfVectorizer(
        stop_words=None,
        tokenizer=None,
        token_pattern=r"(?u)\b\w+\b",
        ngram_range=(1, 3),
        min_df=1,
        lowercase=True,
        vocabulary=word_vocabulary)
    tfidf = vectorizer.fit_transform(dataset)
    tfidf_array = tfidf.toarray()
    tfidf_attribute = vectorizer.get_feature_names()
    write_file(tfidf_array, tfidf_attribute)

def load_file(file_path, file_type):
    if file_type == "csv":
        with open(file=file_path, mode="rt", encoding="utf-8") as fp:
            lines = list(csv.reader(fp))[0:]
            return lines
    elif file_type == "txt":
        with open(file=file_path, mode="rt", encoding="utf-8") as file_stream:
            lines = list(file_stream.read())[1:]
            return lines

def write_file(vector, header):
    header_str = ','.join(header)
    #  np.set_printoptions(suppress=True)
    np.savetxt(
        "vector.csv",
        vector,
        delimiter=",",
        fmt='%.16f',
        header=header_str,
        comments="")

def compress(labels):
    with open(file='vector.csv', mode='rt', encoding='utf-8') as csv_f:
        with open('./vector-compress.txt', 'w') as txt_f:
            lines = list(csv.reader(csv_f))[1:]
            writer = ''
            for line, label in zip(lines, labels):
                i = 0
                writer += '{'
                for w in line:
                    if float(w) == 0:
                        i += 1
                    else:
                        writer += str(i) + ' ' + w + ','
                        #  txt_f.write(str(i) + ' ' + w + ',')
                        i += 1
                if label[0] == "'":
                    label = label[1:]
                    label = label[:-1]
                writer += str(i) + ' ' + label
                #  if writer[-1] == ',':
                #      writer = writer[:-1]
                writer += '}' + '\n'
            txt_f.write(writer)

if __name__ == "__main__":
    dataset = sys.argv[1]
    vocabulary = sys.argv[2]
    vac = load_file(vocabulary, 'csv')
    train = load_file(dataset, 'csv')
    train_sents = [item[0] for item in train]
    word_vocabulary = [item[0] for item in vac]
    label = [item[1] for item in train]
    stringToWordVector(train_sents, word_vocabulary)
    compress(label)


#!/usr/bin/python

import os

def cls():
    os.system(['clear','cls'][os.name == 'nt'])

# now, to clear the screen
cls()

# for ploting
import matplotlib.pyplot as plt

# for integrating
from scipy.integrate import ode

import numpy

from numpy import *

from VectorThrustController import Vector_Thrust_Controller

from numpy import cos as c
from numpy import sin as s

# initial states

# initial position
x0 = numpy.array([-1.4,3.4,5.0])
# initial velocity
v0 = numpy.array([-4.0,-2.0,3.0])
# initial unit vector
n0 = numpy.array([0.0,s(0.3),c(0.3)])
# initial angular velocity
w0 = numpy.array([0.1,0.2,-0.1])

# collecting all initial states
states0  = concatenate([x0,v0,n0,w0])

g0  = numpy.array([-0.2,0.1,9.81])
g1  = numpy.array([0.3,0.2,0.1])
g2  = numpy.array([0.1,0.2,0.3])
gravity = concatenate([g0,g1,g2])

t0 = 0
y0 = states0

Controller = Vector_Thrust_Controller()
out = Controller.output(states0,gravity)
numpy.set_printoptions(precision=15)
for i in range(6):
    print(out[i])


import requests
from bs4 import BeautifulSoup
import os

header = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36'}

def download_each_image(url):
	html = requests.get(url, headers = header)
	soup = BeautifulSoup(html.text, 'lxml')
	img_url = soup.select(".m_i_f img")
	if(len(img_url)==0):
		return
	global path
	image = requests.get(img_url[0]['src'],headers = header).content
	fname = "{}.jpg".format(os.getpid()-main_id)
	with open(path+fname,"wb") as f:
		f.write(image)
		print("第{}张图片下载成功".format(os.getpid()-main_id))

keyword = input("请输入关键字（请输入英文）：")
path = '/Users/macbookpro/Desktop/{}/'.format(keyword)
os.mkdir(path)
main_id = os.getpid()
url = 'https://www.shutterstock.com/zh/search/{}?irgwc=1&utm_medium=Affiliate&utm_campaign=el-plfi&utm_source=489458'.format(keyword)
html = requests.get(url, headers = header)
soup = BeautifulSoup(html.text, 'lxml')
total_page_num = soup.select(".b_ay_g")[0].get_text()
print("{}，每页约有105张图片，请输入要下载前几页的图片：".format(total_page_num))
depth = int(input())
if(depth>0):
	urls = soup.select(".z_g_c a")
	os.fork()
	for url in urls:
		if(os.getpid()!=main_id):
			download_each_image("https://www.shutterstock.com"+url['href'])
			exit()
		else:
			os.fork()
for page in range(2,depth+1):
	url = 'https://www.shutterstock.com/zh/search/{}?irgwc=1&utm_medium=Affiliate&utm_campaign=el-plfi&utm_source=489458&page={}'.format(keyword,page)
	html = requests.get(url, headers = header)
	soup = BeautifulSoup(html.text, 'lxml')
	urls = soup.select(".z_g_c a")
	os.fork()
	for url in urls:
		if(os.getpid()!=main_id):
			download_each_image("https://www.shutterstock.com"+url['href'])
			exit()
		else:
			os.fork()


from concurrent.futures import ThreadPoolExecutor, as_completed
from pprint import pprint
from datetime import datetime
import time
from itertools import repeat

import yaml
from netmiko import ConnectHandler

start_msg = '===> {} Connection to device: {}'
received_msg = '<=== {} Received result from device: {}'

class CiscoSSH:
    def __init__(self, **device_dict):
        self.device_dict = device_dict

    def __call__(self, command):
        print(start_msg.format(datetime.now().time(), self.device_dict['ip']))
        self.ssh = ConnectHandler(**self.device_dict)
        self.ssh.enable()
        result = self.ssh.send_command(command)
        print(received_msg.format(datetime.now().time(), self.device_dict['ip']))
        return result

def threads_conn(devices, command, limit=2):
    all_results = []
    with ThreadPoolExecutor(max_workers=limit) as executor:
        future_ssh = [
            executor.submit(device, command) for device in devices
        ]
        for f in as_completed(future_ssh):
            all_results.append(f.result())
    return all_results

if __name__ == '__main__':
    devices = yaml.load(open('devices.yaml'))
    dev_instances = [CiscoSSH(**params) for params in devices['routers']]
    all_done = threads_conn(dev_instances, command='sh clock')
    pprint(all_done)


##### Visual Search Demo - Image similarity with Inception.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os.path
import sys
import math
import numpy as np
import tensorflow as tf
from flask import Flask, request, render_template, jsonify
import json

app = Flask(__name__)
working_dir = os.getcwd()

# Returns a dictionary of feature representations for an input list of JPEG images,
# which is the next-to-last layer of the Inception network (trained on the
# ImageNet 2012 Challenge dataset). Tensorflow's Inception reference:
# https://tensorflow.org/tutorials/image_recognition/
def get_features():
  img_features = {}

  # Creates graph from saved graph_def.pb.
  graph_file = working_dir + '/inception/classify_image_graph_def.pb'
  with tf.gfile.FastGFile(graph_file, 'rb') as f:
    graph_def = tf.GraphDef()
    graph_def.ParseFromString(f.read())
    _ = tf.import_graph_def(graph_def, name='')

  with tf.Session() as sess:
    # Runs the softmax tensor by feeding the image_data as input to the graph.
    # 'pool_3:0': A tensor containing the next-to-last layer containing 2048
    #  float description of the image.
    last_layer = sess.graph.get_tensor_by_name('pool_3:0')

    for file in os.listdir(working_dir + '/static/img'):
      if file.endswith(".jpg"):
        img_path = working_dir + '/static/img/' + file
        image_data = tf.gfile.FastGFile(img_path, 'rb').read()
        # 'DecodeJpeg/contents:0': A tensor containing a string providing JPEG
        #   encoding of the image.
        features = sess.run(last_layer, {'DecodeJpeg/contents:0': image_data})
        img_features[file] = list([float(x) for x in features[0][0][0]])
  return img_features

# Serve the homepage, a static file
@app.route("/")
def index():
  return render_template('index.html')

@app.route('/get_img_features')
def get_img_features():
  img_features = get_features()
  print(type(img_features))
  print("server calculated features")
  return jsonify(img_features)

# Serve static files
@app.route('/<path:path>')
def static_proxy(path):
  # send_static_file will guess the correct MIME type
  return app.send_static_file(path)

# Run the server app
if __name__ == "__main__":
  app.debug = True
  app.run()
  app.run(debug = True)


from django.contrib.auth.middleware import get_user

from django.shortcuts import render

from django.views import View

from rest_framework.views import APIView

from authentication.logics import *
from backend.config.client_response.response_status import ResponseStatusEnum
from common.exception.childf_exception import  exception_handler
from common.util.response_utils import ResponseUtils
from person.models import  Hamyar

from person.serializers import PersonSerializer, AdminSerializer, UserSerializer, HamyarSerializer, MadadjuSerializer

# Create your views here.

class RegisterAPIView(APIView):
    def post(self, request):
        try:
            register_user(request=request,data_dict=request.data)
            resp_data = "register successfully"
            resp_status = ResponseStatusEnum.ok_200
        except Exception as e:
            resp_data, resp_status = exception_handler(e)
        return ResponseUtils.jsonify(response_enum_obj=resp_status.value, data=resp_data)

class ActiveAccountAPIView(APIView):
    def post(self, request):
        try:
            resp_data = activate_user(request, request.data)
            resp_status = ResponseStatusEnum.ok_200
        except Exception as e:
            resp_data, resp_status = exception_handler(e)
        return ResponseUtils.jsonify(response_enum_obj=resp_status.value, data=resp_data)

class ForgetPassAPIView(APIView):
    def post(self,request):
        try:
            forget_password(request, request.data)
            resp_data = "new password send to email"
            resp_status = ResponseStatusEnum.ok_200
        except Exception as e:
            resp_data, resp_status = exception_handler(e)
        return ResponseUtils.jsonify(response_enum_obj=resp_status.value, data=resp_data)

class SendCodeAPIView(APIView):
    def post(self,request):
        try:
            send_verification_code(data_dict=request.data)
            resp_data = "send activation code"
            resp_status = ResponseStatusEnum.ok_200
        except Exception as e:
            resp_data, resp_status = exception_handler(e)
        return ResponseUtils.jsonify(response_enum_obj=resp_status.value, data=resp_data)

class LoginAPIView(APIView):
    def post(self, request):
        try:
            resp_data = UserSerializer(login_user(request, request.data)).data
            resp_status = ResponseStatusEnum.ok_200

        except Exception as e:
            resp_data,resp_status = exception_handler(e)
        return ResponseUtils.jsonify(response_enum_obj=resp_status.value,data=resp_data)

class UserAPIView(APIView):
    def get(self, request,username):
        try:

            resp_data = user_exist(username)
            resp_status = ResponseStatusEnum.ok_200

        except Exception as e:
            resp_data,resp_status = exception_handler(e)
        return ResponseUtils.jsonify(response_enum_obj=resp_status.value,data=resp_data)

class LogOutAPIView(APIView):
    def get(self, request):
        try:
            logout_user(request)
            resp_data = "logout successfully"
            resp_status=ResponseStatusEnum.ok_200
        except Exception as e:
            resp_data,resp_status = exception_handler(e)
        return ResponseUtils.jsonify(response_enum_obj=resp_status.value,data=resp_data)

#############################

class TestView(View):
    def get(self, request, *args,**kwargs):
          return render(request=request, template_name="test.html")

def test(user):
    return User.objects.get(username=user.username)

class TestAPIView(APIView):

    def get(self, request):
        madadju = Person.objects.all()
       # resp_data = PersonSerializer(Person.objects.filter(user__email__),many=True).data
        return ResponseUtils.jsonify(response_enum_obj=ResponseStatusEnum.ok_200.value, data=resp_data)

            #todo exception handling


import pandas as pd
import pickle
data = pd.read_csv("/home/shiny/file.txt", delimiter =";", names = ["Selected_airport"], index_col=0)
optimal_cost = data["Selected_airport"].iloc[0]
with open('/home/shiny/optimal_cost', 'w') as f:
    f.write(',\n{}\n'.format(optimal_cost))
data = data.drop([-1], axis=0)
data = data[data["Selected_airport"] == 1]
filename = '/home/shiny/stages'
stages = pickle.load(open(filename, 'rb'))
cords = pd.read_csv("IANA_codes_coordinates.csv", index_col=0)
with open("/home/shiny/coordinates.txt", 'w') as f:
    f.write("From,lat_from,lon_from,To,lat_to,lon_to\n")
    for i, stage in enumerate(stages):
        city_from = stage.loc[data.index[i]][0]
        city_to = stage.loc[data.index[i]][1]
        lat_from = cords[cords['code'] == city_from].values.tolist()[0][1]
        lon_from = cords[cords['code'] == city_from].values.tolist()[0][2]
        lat_to = cords[cords['code'] == city_to].values.tolist()[0][1]
        lon_to = cords[cords['code'] == city_to].values.tolist()[0][2]
        f.write("{},{},{},{},{},{}\n".format(city_from,lat_from,lon_from,city_to,lat_to,lon_to))


from io import StringIO
from PIL import Image
import matplotlib
import plotly

# https://stackoverflow.com/questions/18897511/how-to-drawimage-a-matplotlib-figure-in-a-reportlab-canvas

def fig2img(fig):
    imgdata = StringIO()
    fig.savefig(imgdata, format='png')
    imgdata.seek(0)  # rewind the data

    return Image.open(imgdata)

def builder(path, ref, fig_dict = dict(), var_dict = dict()):
    SCALE = 2
    PAD = 0.3

    from pptx import Presentation
    from pptx.util import Inches
    import tempfile
    import copy
    import os

    prs = Presentation(ref)
    out = Presentation()

    out.slide_width = prs.slide_width
    out.slide_height = prs.slide_height

    for slide in prs.slides:
        blank_slide_layout = out.slide_layouts[6]
        o_slide = out.slides.add_slide(blank_slide_layout)

        for shape in slide.shapes:
            try:
                if shape.text[0] == "!" and shape.text[1] == "(" and shape.text[-1] == ")":
                    f = tempfile.NamedTemporaryFile(suffix=".png")
                    fig = fig_dict[shape.text[2:-1]]
                    if type(fig) == matplotlib.figure.Figure:
                        fig.set_size_inches(SCALE*shape.width/Inches(1), SCALE*shape.height/Inches(1))
                        fig.set_tight_layout({"pad" : PAD})
                        fig.savefig(f.name, format='png',dpi = 300)
                        pic = o_slide.shapes.add_picture(f.name, shape.left, shape.top, width=shape.width)
                        continue
                    elif type(fig) == plotly.graph_objs._figure.Figure:
                        fig.write_image(f.name)
                        pic = o_slide.shapes.add_picture(f.name, shape.left, shape.top, width=shape.width)
                        continue

                fvar = False
                otxt = ""
                nvar = ""
                i = 0

                while i < len(shape.text):
                    if fvar:
                        if shape.text[i] != "]":
                            nvar += shape.text[i]
                        else:
                            otxt += var_dict[nvar]
                            fvar = False
                            nvar = ""
                    elif shape.text[i] == "$" and shape.text[i+1] == "[":
                        fvar = True
                        nvar = ""
                        i+=1
                    else:
                        otxt += shape.text[i]
                    i+=1
                shape.text = otxt
                cp = copy.deepcopy(shape.element)
                o_slide.shapes._spTree.insert_element_before(cp, 'p:extLst')
                continue
            except:
                pass

            try:
                img = shape.image.blob
                f = tempfile.NamedTemporaryFile()
                f.write(img)
                o_slide.shapes.add_picture(f.name, shape.left, shape.top, shape.width, shape.height)
                continue
            except:
                pass

            o_slide.shapes._spTree.insert_element_before(copy.deepcopy(shape.element), 'p:extLst')
    out.save(path)


import cv2
import sys
import filters
from managers import WindowManager, CaptureManager
import rects
from trackers import FaceTracker
import depth

class CVcam(object):

    def __init__(self):
        self._windowManager = WindowManager('CVcam',
                                            self.onKeypress)
        self._captureManager = CaptureManager(cv2.VideoCapture(0),
                                              self._windowManager,
                                              True)
        self._faceTracker = FaceTracker()
        self._shouldDrawDebugRects = False
        self._showEdgeFilter = False
        self._curveFilter = filters.BGRPortraCurveFilter()

    def run(self):
        """Run the main loop"""
        self._windowManager.createWindow()
        while self._windowManager.isWindowCreated:
            self._captureManager.enterFrame()
            frame = self._captureManager.frame

            # TODO: Track faces
            self._faceTracker.update(frame)
            faces = self._faceTracker.faces
            rects.swapRects(frame, frame,
                            [face.faceRect for face in faces])

            if self._showEdgeFilter:
                filters.strokeEdges(frame, frame)
                self._curveFilter.apply(frame, frame)

            if self._shouldDrawDebugRects:
                self._faceTracker.drawDebugRects(frame)

            self._captureManager.exitFrame()
            self._windowManager.processEvents()

    def onKeypress(self, keycode):
        """ Handle a keypress.

        space -> Take a screenshot.
        tab -> Start/stop recording a screencast.
        x -> Start/stop drawing debug rectangles around faces.
        e -> Apply the sketchy edge filter
        escape -> Quit.

        """
        if keycode == 32:  # space
            self._captureManager.writeImage('screenshot.png')
        elif keycode == 9:  # tab
            if not self._captureManager.isWritingVideo:
                self._captureManager.startWritingVideo('screencast.avi')
            else:
                self._captureManager.stopWritingVideo()
        elif keycode == 120:  # x
            self._shouldDrawDebugRects = \
                not self._shouldDrawDebugRects
        elif keycode == 27:  # escape
            self._windowManager.destroyWindow()
        elif keycode == 101:
            self._showEdgeFilter = not self._showEdgeFilter

class CVdepthCam(CVcam):

    def __init__(self):
        self._windowManager = WindowManager('CVcam',
                                            self.onKeypress)
        device = depth.CV_CAP_LENOVO_DEPTH_CAM
        self._captureManager = CaptureManager(cv2.VideoCapture(device),
                                              self._windowManager, True)
        self._faceTracker = FaceTracker()
        self._shouldDrawDebugRects = False
        self._curveFilter = filters.BGRPortraCurveFilter()
        self._showEdgeFilter = False

    def run(self):
        """Run the main loop."""
        self._windowManager.createWindow()
        while self._windowManager.isWindowCreated:
            self._captureManager.enterFrame()
            self._captureManager.channel = \
                depth.CV_CAP_OPENNI_DISPARITY_MAP
            disparityMap = self._captureManager.frame
            self._captureManager.channel = \
                depth.CV_CAP_OPENNI_VALID_DEPTH_MASK
            validDepthMask = self._captureManager.frame
            self._captureManager.channel = \
                depth.CV_CAP_OPENNI_BGR_IMAGE
            frame = self._captureManager.frame
            self._faceTracker.update(frame)
            faces = self._faceTracker.faces
            masks = [depth.createMedianMask(disparityMap, validDepthMask, face.faceRect)
                     for face in faces]
            rects.swapRects(frame, frame,
                            [face.faceRect for face in faces], masks)
            if self._showEdgeFilter:
                filters.strokeEdges(frame, frame)
                self._curveFilter.apply(frame, frame)
            if self._shouldDrawDebugRects:
                self._faceTracker.drawDebugRects(frame)
            self._captureManager.exitFrame()
            self._windowManager.processEvents()

if __name__ == "__main__":
    CVcam().run()
    # CVdepthCam().run()
    sys.exit()


# coding: utf-8

import unittest

from crossref import restful

class RestfulTest(unittest.TestCase):
    """
    These tests are testing the API live integration, the main purpouse of these
    testes is to validate the JSON structure of the API results.
    These tests may lead to connectivity erros if the Crossref API is temporary
    out of service.
    """

    def test_work_agency_message(self):
        """
        Testing the base structure for the /works/{DOI}/agency endpoint.
        If all the base structure is present, this test may not lead to dict
        keyerror exceptions.
        """
        works = restful.Works()

        result = works.agency('10.1590/S0102-09352010000200002')

        self.assertEqual(result['agency']['id'], 'crossref')

    def test_work_agency_header(self):
        """
        Testing the base structure for the /works/{DOI}/agency endpoint.
        If all the base structure is present, this test may not lead to dict
        keyerror exceptions.
        """
        works = restful.Works()

        result = works.agency('10.1590/S0102-09352010000200002', only_message=False)

        self.assertEqual(result['message-type'], 'work-agency')


# coding: utf-8
from __future__ import unicode_literals

from .common import InfoExtractor
from ..utils import (
    ExtractorError,
    dict_get,
    float_or_none,
    int_or_none,
    remove_end,
    str_or_none,
    try_get,
    url_or_none,
    urljoin,
)

class GettrIE(InfoExtractor):
    _VALID_URL = r'https?://(www\.)?gettr\.com/post/(?P<id>[a-z0-9]+)'
    _MEDIA_BASE_URL = 'https://media.gettr.com/'

    _TESTS = [{
        'url': 'https://www.gettr.com/post/pcf6uv838f',
        'info_dict': {
            'id': 'pcf6uv838f',
            'title': 'md5:9086a646bbd06c41c4fe8e52b3c93454',
            'description': 'md5:be0577f1e4caadc06de4a002da2bf287',
            'ext': 'mp4',
            'uploader': 'EpochTV',
            'uploader_id': 'epochtv',
            'thumbnail': r're:^https?://.+/out\.jpg',
            'timestamp': 1632782451058,
            'duration': 58.5585,
        }
    }, {
        'url': 'https://gettr.com/post/p4iahp',
        'info_dict': {
            'id': 'p4iahp',
            'title': 'md5:b03c07883db6fbc1aab88877a6c3b149',
            'description': 'md5:741b7419d991c403196ed2ea7749a39d',
            'ext': 'mp4',
            'uploader': 'Neues Forum Freiheit',
            'uploader_id': 'nf_freiheit',
            'thumbnail': r're:^https?://.+/out\.jpg',
            'timestamp': 1626594455017,
            'duration': 23,
        }
    }]

    def _real_extract(self, url):
        post_id = self._match_id(url)
        webpage = self._download_webpage(url, post_id)

        api_data = self._download_json(
            'https://api.gettr.com/u/post/%s?incl="poststats|userinfo"' % post_id, post_id)

        post_data = try_get(api_data, lambda x: x['result']['data'])
        user_data = try_get(api_data, lambda x: x['result']['aux']['uinf'][post_data['uid']]) or {}

        if post_data.get('nfound'):
            raise ExtractorError(post_data.get('txt'), expected=True)

        title = description = str_or_none(
            post_data.get('txt') or self._og_search_description(webpage))

        uploader = str_or_none(
            user_data.get('nickname')
            or remove_end(self._og_search_title(webpage), ' on GETTR'))
        if uploader:
            title = '%s - %s' % (uploader, title)

        if not dict_get(post_data, ['vid', 'ovid']):
            raise ExtractorError('There\'s no video in this post.')

        vid = post_data.get('vid')
        ovid = post_data.get('ovid')

        formats = self._extract_m3u8_formats(
            urljoin(self._MEDIA_BASE_URL, vid), post_id, 'mp4',
            entry_protocol='m3u8_native', m3u8_id='hls') if vid else []

        if ovid:
            formats.append({
                'url': urljoin(self._MEDIA_BASE_URL, ovid),
                'format_id': 'ovid',
                'ext': 'mp4',
                'width': int_or_none(post_data.get('vid_wid')),
                'height': int_or_none(post_data.get('vid_hgt')),
                'source_preference': 1,
                'quality': 1,
            })

        self._sort_formats(formats)

        return {
            'id': post_id,
            'title': title,
            'description': description,
            'thumbnail': url_or_none(
                urljoin(self._MEDIA_BASE_URL, post_data.get('main'))
                or self._og_search_thumbnail(webpage)),
            'timestamp': int_or_none(post_data.get('cdate')),
            'uploader_id': str_or_none(
                dict_get(user_data, ['_id', 'username'])
                or post_data.get('uid')),
            'uploader': uploader,
            'formats': formats,
            'duration': float_or_none(post_data.get('vid_dur')),
            'tags': post_data.get('htgs'),
        }