import tensorflow as tf
import cv2
from tensorflow.python.ops import nn_ops, gen_nn_ops
import numpy as np
import matplotlib.pyplot as plt
import uuid

class Taylor:
    def __init__(self, input_image, init_fn, sess_config, traverse_graph, output_layer, epsilon=1e-10):
        self.epsilon = epsilon

        graph = tf.get_default_graph()
        #output_layer = graph.get_tensor_by_name('Softmax:0')
        layer = output_layer.op.inputs[0]
        relevances = [output_layer]
        relevances = traverse_graph(self, layer, relevances)

        self.init_fn = init_fn
        self.sess_config = sess_config
        self.input_image = input_image
        self.relevances = relevances

    def get_parent(self, child, num_skips):
        parent = child
        for i in range(num_skips):
            parent = [inp for inp in parent.op.inputs if not (inp.op.type=='Const')][0]
        return parent

    def backprop_conv(self, activation, weights, relevance, strides, padding):
        w_pos = tf.maximum(0., weights)
        z = tf.nn.conv2d(activation, w_pos, strides, padding) + self.epsilon
        s = relevance / z
        c = gen_nn_ops.conv2d_backprop_input(tf.shape(activation), w_pos, s, strides, padding)
        return activation * c

    def backprop_max_pool(self, activation, relevance, ksize, strides, padding):
        z = tf.nn.max_pool(activation, ksize, strides, padding) + self.epsilon
        #z = nn_ops.avg_pool(activation, ksize, strides, padding='SAME') + self.epsilon
        s = relevance / z
        #c = gen_nn_ops._avg_pool_grad(tf.shape(activation), s, ksize, strides, padding='SAME')
        c = gen_nn_ops.max_pool_grad_v2(activation, z, s, ksize, strides, padding)
        return activation * c

    def backprop_avg_pool(self, activation, relevance, ksize, strides, padding):
        z = tf.nn.avg_pool(activation, ksize, strides, padding) + self.epsilon
        s = relevance / z
        c = gen_nn_ops._avg_pool_grad(tf.shape(activation), s, ksize, strides, padding)
        return c * activation

    def backprop_inception(self, layer, activation, relevance):
        inputs = [inp for inp in layer.op.inputs if not (inp.op.type=='Const')]
        split_dim = tf.constant([int(inputs[0].shape[3]), int(inputs[1].shape[3]), int(inputs[2].shape[3]), int(inputs[3].shape[3])])
        r_1, r_3, r_5, r_p = tf.split(relevance, split_dim, axis=3)
        r_1x1 = self.backprop_1x1(inputs[0], activation, r_1)
        r_3x3 = self.backprop_nxn(inputs[1], activation, r_3)
        r_5x5 = self.backprop_nxn(inputs[2], activation, r_5)
        r_pool = self.backprop_inception_pool(inputs[3], activation, r_p)
        new_relevance = (r_1x1 + r_3x3 + r_5x5 + r_pool)
        return new_relevance

    def backprop_1x1(self, layer, activation, relevance):
        conv = self.get_parent(layer,2)
        weights = conv.op.inputs[1]
        strides = conv.op.get_attr('strides')
        padding = conv.op.get_attr('padding')
        return self.backprop_conv(activation, weights, relevance, strides, padding)

    def backprop_nxn(self, layer, activation_1x1, relevance_nxn):
        activation_nxn = self.get_parent(layer, 3)

        conv_nxn = self.get_parent(layer, 2)
        weights_nxn = conv_nxn.op.inputs[1]
        strides_nxn = conv_nxn.op.get_attr('strides')
        padding_nxn = conv_nxn.op.get_attr('padding')

        conv_1x1 = self.get_parent(conv_nxn, 3)
        weights_1x1 = conv_1x1.op.inputs[1]
        strides_1x1 = conv_1x1.op.get_attr('strides')
        padding_1x1 = conv_1x1.op.get_attr('padding')

        relevance_1x1 = self.backprop_conv(activation_nxn, weights_nxn, relevance_nxn, strides_nxn, padding_nxn)
        return self.backprop_conv(activation_1x1, weights_1x1, relevance_1x1, strides_1x1, padding_1x1)

    def backprop_inception_pool(self, layer, activation_pool, relevance_1x1):
        conv_1x1 = self.get_parent(layer, 2)
        activation_1x1 = self.get_parent(layer, 3)
        weights_1x1 = conv_1x1.op.inputs[1]
        ksize = activation_1x1.op.get_attr('ksize')
        strides = activation_1x1.op.get_attr('strides')
        padding = activation_1x1.op.get_attr('padding')
        strides_1x1 = conv_1x1.op.get_attr('strides')
        padding_1x1 = conv_1x1.op.get_attr('padding')
        relevance_pool = self.backprop_conv(activation_1x1, weights_1x1, relevance_1x1, strides_1x1, padding_1x1)
        return self.backprop_max_pool(activation_pool, relevance_pool, ksize, strides, padding)

    def backprop_conv_input(self, activation, weights, relevance, strides, padding, lowest=0., highest=1.):
        lowest = tf.reduce_min(activation)
        highest = tf.reduce_max(activation)
        W_p = tf.maximum(0., weights)
        W_n = tf.minimum(0., weights)

        L = tf.ones_like(activation, tf.float32) * lowest
        H = tf.ones_like(activation, tf.float32) * highest

        z_o = nn_ops.conv2d(activation, weights, strides, padding)
        z_p = nn_ops.conv2d(L, W_p, strides, padding)
        z_n = nn_ops.conv2d(H, W_n, strides, padding)

        z = z_o - z_p - z_n + 1e-10
        s = relevance / z

        c_o = nn_ops.conv2d_backprop_input(tf.shape(activation), weights, s, strides, padding)
        c_p = nn_ops.conv2d_backprop_input(tf.shape(activation), W_p, s, strides, padding)
        c_n = nn_ops.conv2d_backprop_input(tf.shape(activation), W_n, s, strides, padding)

        return activation * c_o - L * c_p - H * c_n

    def run_relevances(self, image, num_filters):
        sess = tf.Session(config=self.sess_config)
        self.init_fn(sess)
        relevances = sess.run(self.relevances, feed_dict={self.input_image: image})
        results = {}
        for r in range(len(relevances)):
            res = relevances[r]
            sorted_filters = []
            if len(res.shape) >=  4:
                for i in range(int(res.shape[3])):
                    filter = res[0,:,:,i]

                    filter_tuple = {}
                    filter_tuple['score'] = float(np.sum(filter))
                    filter_tuple['id'] = i
                    sorted_filters.append(filter_tuple)
                    #sorted_filters.append((su, i, filter))
                #sorted_filters = sorted(sorted_filters, reverse=True, key=lambda tup: tup[0])
                sorted_filters = sorted(sorted_filters, reverse=True, key=lambda tup: tup['score'])
                # x = []
                # z = []
                # for y in range(len(sorted_filters)):
                #     # float_img = sorted_filters[y][2]
                #     # float_img /= float_img.max()
                #     # float_img *= 255
                #     # img = cv2.resize(float_img, (224, 224), interpolation=0).astype(np.uint8)
                #     # img = cv2.applyColorMap(img, cv2.COLORMAP_JET)
                #     #
                #     # filepath = 'static/images/temp/filter_{0}_{1}_{2}.jpg'.format(str(self.relevances[r].name.split('/')[2]), y, sorted_filters[y][1])
                #     # cv2.imwrite(filepath, img)
                #     x.append(sorted_filters[y][0])
                #     z.append(y)
                # plt.bar(z, height=x)
                # #plt.xticks(z, z);
                # plt.show()
            #make sure layer is convolutional and size bigger than 1x1
            if(len(res.shape) >= 4 and res.shape[1] > 1):
                res = res[0,:,:,:]
                float_img = np.sum(res, axis=2)
                float_img /= float_img.max()
                float_img *= 255
                img = cv2.resize(float_img, (224, 224), interpolation=0).astype(np.uint8)
                img = cv2.applyColorMap(img, cv2.COLORMAP_JET)

                #filepath = 'static/images/temp/{0}_{1}.jpg'.format(r, np.sum(res))
                filepath = 'static/images/temp/'+ str(uuid.uuid4()) + '.jpg'

                cv2.imwrite(filepath, img)
                #filepaths.append(filepath)

                sorted_filters = sorted_filters[:num_filters]
                #filter_rankings[str(self.relevances[r].name)] = sorted_filters
                results[str(self.relevances[r].name.split('/')[-2])] = {'image_path': filepath, 'filter_rankings': sorted_filters}
        return results


import pygame
from Game import GameSceneBase
import Resources
import Menus
import time

BLAKE = 'Police'
RICHARD = 'Dude1'
ADRIAN = 'Dude2'
CHUN = 'Dude3'
NIELS = 'Dude4'
ANGEL = 'Girl3'
CHRISTINE = 'Girl4'

UP = 'up'
DOWN = 'down'
LEFT = 'left'
RIGHT = 'right'

SP_SPEED = 3

#possible modes
WAITING = 1
PRESENT = 2
RETURN  = 3

WALK_COUNT = 65
RETURN_COUNT = WALK_COUNT - 1
FADE_COUNT = 30
TITLE_Y = 200

LINEUP = None
def _lineup():
	global LINEUP
	if not LINEUP:
		LINEUP = {
			ADRIAN : CState(ADRIAN, 290, 218),
			ANGEL : CState(ANGEL, 330, 218),
			RICHARD : CState(RICHARD, 370, 218),
			BLAKE : CState(BLAKE, 410, 218),
			CHUN : CState(CHUN, 450, 218),
			CHRISTINE : CState(CHRISTINE, 490, 218),
			NIELS : CState(NIELS, 530, 218)
		}
	return LINEUP

class Credits(GameSceneBase):
	def __init__(self):
		GameSceneBase.__init__(self)
		global LINEUP
		LINEUP = None
		_lineup()

	def ProcessInput(self, events):
		pass

	def Update(self):
		self.next = Programming2()
		#self.next = Exit()

	def Render(self, screen):
		screen.fill((0, 0, 0))

class CreditsBase(GameSceneBase):
	def __init__(self):
		GameSceneBase.__init__(self)

		self._header_font = Resources.GetFont(255, 0, 0)
		self._font = Resources.GetFont(255, 255, 255)
		self._start_time = time.time()
		self._tick = -1
		self._lineup = _lineup()
		self._blacks = pygame.Surface((220, 310))

	def ProcessInput(self, events):
		for event in events:
			if event.type == pygame.KEYDOWN:
				if event.key == pygame.K_RETURN:
					self.next = Menus.Title()
				elif event.key == pygame.K_ESCAPE:
					self.next = Menus.Title()
			if event.type == pygame.MOUSEBUTTONUP and event.button == 1:
				self.next = Menus.Title()

	def Update(self):
		self._tick += 1
		if (self._tick == 3):
			self._tick = 0
			for s in self._lineup:
				p = self._lineup[s]
				p.Step()
		else:
			return

	def Render(self, screen):
		for p in self._lineup:
			pstate = self._lineup[p]
			screen.blit(pstate.Frame(), pstate.GetPos())

	def _MakeHeader(self, txt):
		return self._header_font.Render(txt)
	def _MakeName(self, txt):
		return self._font.Render(txt)

	def RenderHeader(self, txt):
		surf = pygame.Surface((len(txt) * 16, 16))
		offset = 0
		for i in range(len(txt)):
			t = self._header_font.Render(txt[i])
			surf.blit(t, (offset, 0))
			offset += 3 + t.get_width()
		return surf.subsurface(pygame.Rect(0,0,offset-3,16))

class Exit(CreditsBase):
	def __init__(self):
		CreditsBase.__init__(self)
		self._counter = 0

		self._header = self.RenderHeader('Thank you for playing')
		self._tag = self._MakeName('Team Nerd Paradise')

	def Update(self):
		CreditsBase.Update(self)
		self._counter += 1

	def Render(self, screen):
		screen.fill((0,0,0))
		CreditsBase.Render(self, screen)

		counter = self._counter
		start = 30

		if counter == start:
			for key in _lineup():
				p = _lineup()[key]
				if key != BLAKE:
					p.SetMode(RETURN)

		if counter == start + RETURN_COUNT:
			for key in _lineup():
				p = _lineup()[key]
				if key != BLAKE:
					p.SetMode(WAITING)

		salute = start + RETURN_COUNT + 5

		print("Count: %d" % counter)

class CBase2(CreditsBase):
	def __init__(self, header, nameList, pplList):
		CreditsBase.__init__(self)

		self._counter = 0
		self._header = self.RenderHeader(header)

		self._names = []
		for name in nameList:
			self._names.append(self._font.Render(name))
		self._people = pplList

	def Update(self):
		CreditsBase.Update(self)
		self._counter += 1

	def Render(self, screen):
		screen.fill((0,0,0))

		counter = self._counter

		screen.blit(self._header, ((200 - self._header.get_width()) / 2, TITLE_Y))

		yoffset = TITLE_Y + 20
		for i in range(len(self._names)):
			screen.blit(self._names[i], ((200 - self._names[i].get_width()) / 2, yoffset))
			yoffset += 20

		start = 65
		stop = start + WALK_COUNT
		back = stop + 60
		stop2 = back + RETURN_COUNT
		shutdown = stop2 + 35

		op = (1 - (float(counter) / (2 * FADE_COUNT))) * 255
		if op < 0:
			op = 0
		if op > 255:
			op = 255

		if counter >= stop2:
			op = ((counter - 312) / FADE_COUNT) * 255

		self._blacks.set_alpha(op)
		screen.blit(self._blacks, (0, 100))

		if (counter == start):
			for p in self._people:
				p.SetMode(PRESENT)
		if (counter == stop):
			for p in self._people:
				p.SetMode(WAITING)
		if (counter == back):
			for p in self._people:
				p.SetMode(RETURN)
		if (counter == stop2):
			for p in self._people:
				p.SetMode(WAITING)
				p.ResetPos()

		CreditsBase.Render(self, screen)

		if (counter > shutdown and op >= 255):
			self.next = self.NextScene()

class Art(CBase2):
	def __init__(self):
		CBase2.__init__(
			self,
			'Art',
			['Angel McLaughlin', 'Niels', 'Fixception'],
			[_lineup()[ANGEL], _lineup()[NIELS], _lineup()[CHUN]]
			)

	def NextScene(self):
		return Music()

class Music(CBase2):
	def __init__(self):
		CBase2.__init__(
			self,
			'Music',
			['Adrian Cline'],
			[_lineup()[ADRIAN]]
		)

	def NextScene(self):
		return LevelDesign()

class LevelDesign(CBase2):
	def __init__(self):
		CBase2.__init__(
			self,
			'Level Design',
			['Blake O\'Hare'],
			[_lineup()[BLAKE]]
			)

	def NextScene(self):
		return GameDesign()

class GameDesign(CBase2):
	def __init__(self):
		CBase2.__init__(
			self,
			'Game Design',
			['Fixception', 'Richard Bailey', 'Blake O\'Hare'],
			[_lineup()[CHUN], _lineup()[RICHARD], _lineup()[BLAKE]]
		)

	def NextScene(self):
		return SpecialThanks()

class SpecialThanks(CBase2):
	def __init__(self):
		CBase2.__init__(
			self,
			'Special Thanks To',
			['Christine Sandquist'],
			[_lineup()[CHRISTINE]]
		)

	def NextScene(self):
		#return Exit()
		return Menus.Title()

class Programming2(CBase2):
	def __init__(self):
		CBase2.__init__(
			self,
			'Development',
			['Blake O\'Hare', 'Richard Bailey'],
			[_lineup()[BLAKE], _lineup()[RICHARD]]
		)

	def NextScene(self):
		return Art()

# class CState:
	# Step()
	#  -- returns a drawable frame, a
	#  -- advances location
	# Frame()
	# GetPos()
	# SetPos(x, y)
	# Face(direction)
	# SetMode(mode)
	# GetMode()

class CState:
	def __init__(self, name, x, y):
		self.__name = name
		self.__direction = None
		self.__frame = 0
		c = self._cache
		self.__cache = {
			UP    : c( UP),
			DOWN  : c(DOWN),
			RIGHT : c(RIGHT),
			LEFT  : c(LEFT)
		}

		self.__mode = WAITING
		self.__modeStart = None

		self.__x = x
		self.__y = y
		self.__ox = x
		self.__oy = y

		self.__dx = 0
		self.__dy = 0

		self.Face(DOWN)

	def Name(self):
		return self.__name

	def Frame(self):
		return self.__cache[self.__direction][self.__frame]

	def SetMode(self, mode):
		if (mode == self.__mode):
			self.__mode = WAITING
			self.Face(DOWN)
		else:
			self.__mode = mode
		if mode == PRESENT or mode == WAITING:
			self.Face(DOWN)
		elif mode == RETURN:
			self.Face(UP)

	def GetMode(self):
		return self.__mode

	def Face(self, direction):
		self.__direction = direction
		self.__frame = 0

		if direction == UP:
			self.__dy = -SP_SPEED
			self.__dx = 0
		elif direction == DOWN:
			self.__dy = SP_SPEED
			self.__dx = 0
		elif direction == RIGHT:
			self.__dy = 0
			self.__dx = SP_SPEED
		elif direction == LEFT:
			self.__dy = 0
			self.__dx = -SP_SPEED

	def Step(self):
		if self.__mode == WAITING:
			return

		self.__frame += 1
		if (self.__frame == 3):
			self.__frame = 0

		self.__x += self.__dx
		self.__y += self.__dy

		return self.Frame()

	def ResetPos(self):
		self.__x = self.__ox
		self.__y = self.__oy

	def GetPos(self):
		return (self.__x, self.__y)

	def SetPos(self, x, y):
		self.__x = x
		self.__y = y

	def _cache(self, direction):
		person = self.__name
		return [
			Resources.ImageLibrary.Get('Sprites/%s/%s0.png' % (person, direction)),
			Resources.ImageLibrary.Get('Sprites/%s/%s1.png' % (person, direction)),
			Resources.ImageLibrary.Get('Sprites/%s/%s2.png' % (person, direction))
		]


import pytest

from ethecycle.blockchains import *
from ethecycle.blockchains.ethereum import Ethereum
from ethecycle.models.token import Token
from ethecycle.models.transaction import Txn
from ethecycle.models.wallet import Wallet
from ethecycle.util.string_constants import *

EXTRACTION_TIMESTAMP_STR = '2020-02-20T02:20:20'
TEST_DATA_SOURCE = 'the_pharcyde/bypass'
TEST_TXN_HASH = '0x666_TRANSACTION_HASHING_OF_THE_BEAST_666'
TEST_TXN_LOG_LEVEL = '777'

@pytest.fixture(scope='session')
def ethereum_of_the_beast(prep_db, token_of_the_beast):
    """Add token to Ethereum ChainInfo in memory."""
    Token.chain_addresses()[ETHEREUM][token_of_the_beast.address] = token_of_the_beast
    Token._by_blockchain_symbol[ETHEREUM][token_of_the_beast.symbol] = token_of_the_beast
    return Ethereum

@pytest.fixture(scope='session')
def wallet_1(prep_db) -> Wallet:
    return Wallet(
        address='0xPHAT_WALLET_ADDRESS_1',
        chain_info=Ethereum,
        name='Gabriel',
        category=CEX,
        data_source=TEST_DATA_SOURCE,
        extracted_at=EXTRACTION_TIMESTAMP_STR
    )

@pytest.fixture(scope='session')
def wallet_2() -> Wallet:
    return Wallet(
        address='0xPHAT_WALLET_ADDRESS_2',
        chain_info=Ethereum,
        name='Lucifer',
        category=CEX,
        data_source=TEST_DATA_SOURCE,
        extracted_at='2020-02-20T02:20:20'
    )

@pytest.fixture(scope='session')
def token_of_the_beast() -> Token:
    return Token(
        chain_info=Ethereum,
        address='0x666_TOKEN_ADDRESS_OF_THE_BEAST_666',
        symbol='S1X',
        name='Token Of The Beast',
        decimals=6,
        token_type=ERC20,
        data_source=TEST_DATA_SOURCE,
        extracted_at=EXTRACTION_TIMESTAMP_STR
    )

@pytest.fixture(scope='session')
def transaction_of_the_beast(ethereum_of_the_beast, token_of_the_beast, wallet_1, wallet_2) -> Txn:
    return Txn(
        token_address=token_of_the_beast.address,
        from_address=wallet_1.address,
        to_address=wallet_2.address,
        csv_value='6000000',
        transaction_hash=TEST_TXN_HASH,
        log_index=TEST_TXN_LOG_LEVEL,
        block_number=666666,
        chain_info=Ethereum,
        extracted_at=EXTRACTION_TIMESTAMP_STR
    )


import json
import vntypes

class NovelJSONEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, vntypes.Novel):
            base = {"id": o.vndb_id, "name": o.name}
            if o.characters is not None:
                base["characters"] = [self.default(c) for c in o.characters]
            return base
        elif isinstance(o, vntypes.Character):
            base = {"id": o.vndb_id, "name": o.name}
            if o.novels is not None:
                base["novels"] = [self.default(n) for n in o.novels]
            return base
        elif isinstance(o, vntypes.Quote):
            return {
                "text": o.text,
                "character": self.default(o.character),
                "novel": self.default(o.novel)
            }
        else:
            return super(NovelJSONEncoder, self).default(o)

def dumps(o):
    return json.dumps(o, cls=NovelJSONEncoder)


#
#  file:  cifar10_one_vs_many.py
#
#  Compare a single multiclass model vs individual binary models
#
#  RTK, 21-Oct-2019
#  Last update:  06-Nov-2019
#
################################################################

import numpy as np
from keras.models import load_model

def main():
    x_test = np.load("../data/cifar10/cifar10_test_images.npy")/255.0
    y_test = np.load("../data/cifar10/cifar10_test_labels.npy")

    #  Load the models
    mm = load_model("cifar10_cnn_model.h5")
    m = []
    for i in range(10):
        m.append(load_model("cifar10_cnn_%d_model.h5" % i))

    #  Multiclass predictions
    mp = np.argmax(mm.predict(x_test), axis=1)

    #  Individual binary predictions
    p = np.zeros((10,10000), dtype="float32")

    for i in range(10):
        p[i,:] = m[i].predict(x_test)[:,1]

    bp = np.argmax(p, axis=0)

    #  Confusion matrices
    cm = np.zeros((10,10), dtype="uint16")
    cb = np.zeros((10,10), dtype="uint16")

    for i in range(10000):
        cm[y_test[i],mp[i]] += 1
        cb[y_test[i],bp[i]] += 1

    np.save("cifar10_multiclass_conf_mat.npy", cm)
    np.save("cifar10_binary_conf_mat.npy", cb)

    #  Confusion matrices
    print()
    print("One-vs-rest confusion matrix (rows true, cols predicted):")
    print("%s" % np.array2string(100*(cb/1000.0), precision=1))
    print()
    print("Multiclass confusion matrix:")
    print("%s"  % np.array2string(100*(cm/1000.0), precision=1))

    #  Report on differences
    db = np.diag(100*(cb/1000.0))
    dm = np.diag(100*(cm/1000.0))
    df = db - dm
    sb = np.array2string(db, precision=1)[1:-1]
    sm = np.array2string(dm, precision=1)[1:-1]
    sd = np.array2string(df, precision=1)[1:-1]
    print()
    print("Comparing per class accuracies, one-vs-rest or multiclass:")
    print()
    print("    one-vs-rest: %s" % sb)
    print("    multiclass : %s" % sm)
    print("    difference : %s" % sd)

    #  Report overall accuracies
    print()
    print("Overall accuracy:")
    print("    one-vs-rest: %0.1f%%" % np.diag(100*(cb/1000.0)).mean())
    print("    multiclass : %0.1f%%" % np.diag(100*(cm/1000.0)).mean())
    print()

main()


import pygame
import random
import math

# Inicialização
pygame.init()

# Cores
WHITE = (255, 255, 255)
GREEN = (0, 128, 0)
RED = (255, 0, 0)

# Dimensões
WIDTH, HEIGHT = 800, 600

# Adicione isso no começo para definir as fontes
pygame.font.init()
font = pygame.font.SysFont(None, 36)

# Janela
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("GeneSys")

class Snake:
    def __init__(self):
        self.segments = [(WIDTH // 2, HEIGHT // 2)]
        self.angle = random.uniform(0, 2*math.pi)
        self.speed = 5
        self.length = 30
        self.angle_variation = 0.1
        self.sin_wave = 0
        self.sin_frequency = 0.1
        self.sin_amplitude = 0.5
        self.health = 100
        self.max_speed = 5
        self.radioactivity = 5 # Define quão rápido a saúde diminui por frame
        self.original_radioactivity = 5

    def adjust_radioactivity(self, value):
        self.radioactivity += value
        # Garante que a radioatividade nunca seja negativa e não exceda o valor original
        self.radioactivity = max(0, min(self.original_radioactivity, self.radioactivity))

    def reset_radioactivity(self):
        # Aumenta gradualmente a radioatividade em direção ao valor original
        if self.radioactivity < self.original_radioactivity:
            self.adjust_radioactivity(0.02)

    def update_health(self):
        self.health -= self.radioactivity*0.01
        self.health = max(0, self.health)  # Saúde nunca fica abaixo de 0
        self.speed = self.max_speed * (self.health / 100.0)  # Ajusta a velocidade com base na saúde

    def move_towards(self, target):
        dx = target[0] - self.segments[0][0]
        dy = target[1] - self.segments[0][1]
        target_angle = math.atan2(dy, dx)
        angle_diff = (target_angle - self.angle) % (2*math.pi)
        if angle_diff > math.pi:
            angle_diff -= 2*math.pi

        if abs(angle_diff) < self.angle_variation:
            self.angle = target_angle
        elif angle_diff > 0:
            self.angle += self.angle_variation
        else:
            self.angle -= self.angle_variation

        self.angle += 0.3 * self.sin_amplitude * math.sin(self.sin_wave)
        self.sin_wave += self.sin_frequency

    def update(self):
        dx = self.speed * math.cos(self.angle)
        dy = self.speed * math.sin(self.angle)
        new_segment = (self.segments[0][0] + dx, self.segments[0][1] + dy)
        self.segments.insert(0, new_segment)
        while len(self.segments) > self.length:
            self.segments.pop()

    def draw(self, screen):
        for segment in self.segments:
            pygame.draw.circle(screen, GREEN, (int(segment[0]), int(segment[1])), 7)  # Raio ajustado para 7

class Food:
    def __init__(self):
        self.position = [random.randint(0, WIDTH), random.randint(0, HEIGHT)]

    def draw(self, screen):
        pygame.draw.circle(screen, RED, (int(self.position[0]), int(self.position[1])), 8)

    def randomize_position(self):
        self.position = [random.randint(0, WIDTH), random.randint(0, HEIGHT)]

class Machine:
    def __init__(self, x, y):
        self.position = [x, y]
        self.effect_radius = 100

    def draw(self, screen):
        pygame.draw.rect(screen, (0, 0, 255), (self.position[0] - 10, self.position[1] - 10, 20, 20))
        pygame.draw.circle(screen, (173, 216, 230, 80), self.position, self.effect_radius, 2)

class SpecialFood:
    def __init__(self, x, y):
        self.position = [x, y]

    def draw(self, screen):
        pygame.draw.circle(screen, (255, 165, 0), self.position, 10)

    def eaten_by(self, snake):
        distance_to_snake = math.sqrt((self.position[0] - snake.segments[0][0])**2 + (self.position[1] - snake.segments[0][1])**2)
        return distance_to_snake < 20

snake = Snake()
food = Food()
machines = []
special_foods = []

running = True
while running:
    screen.fill(WHITE)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        # Permitindo ao usuário colocar máquinas e comidas especiais
        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:  # Botão esquerdo do mouse
                machines.append(Machine(event.pos[0], event.pos[1]))
            elif event.button == 3:  # Botão direito do mouse
                special_foods.append(SpecialFood(event.pos[0], event.pos[1]))

    if special_foods:
        closest_special_food = min(special_foods, key=lambda x: math.sqrt((x.position[0] - snake.segments[0][0])**2 + (x.position[1] - snake.segments[0][1])**2))
        snake.move_towards(closest_special_food.position)
    else:
        snake.move_towards(food.position)
    snake.update()

    distance_to_food = math.sqrt((food.position[0] - snake.segments[0][0]) ** 2 + (food.position[1] - snake.segments[0][1]) ** 2)
    if distance_to_food < 15:  # Ajustado para 15
        food.randomize_position()

    snake.draw(screen)
    food.draw(screen)

    snake.update_health()

    # Renderizar a saúde na tela
    health_surface = font.render(f'Health: {int(snake.health)}', True, (0, 0, 0))
    screen.blit(health_surface, (10, 10))

    # Renderizar o nível de radioatividade na tela
    radio_surface = font.render(f'Radioactivity: {snake.radioactivity:.2f}', True, (0, 0, 0))
    screen.blit(radio_surface, (10, 50))

    near_machine = False  # Esta flag verifica se a cobra está perto de alguma máquina

    for machine in machines:
        machine.draw(screen)
        distance_to_machine = math.sqrt((machine.position[0] - snake.segments[0][0])**2 + (machine.position[1] - snake.segments[0][1])**2)
        if distance_to_machine < machine.effect_radius:
            near_machine = True
            snake.health += 0.03  # Recupera um pouco de saúde
            snake.adjust_radioactivity(-0.01)  # Diminui a radioatividade de maneira mais gradual

    if not near_machine:
        snake.reset_radioactivity()  # Aumenta gradualmente a radioatividade até o valor original

    for special_food in special_foods:
        special_food.draw(screen)
        if special_food.eaten_by(snake):
            snake.health += 20  # Aumenta a saúde da cobra
            special_foods.remove(special_food)  # Remove a comida especial

    # Verificar se a cobrinha morreu
    if snake.health <= 0:
        running = False
        death_surface = font.render('C. Elegans Died!', True, (255, 0, 0))
        screen.blit(death_surface, (WIDTH // 2 - 100, HEIGHT // 2))
        pygame.display.flip()
        pygame.time.wait(2000)  # Espera 2 segundos antes de fechar

    pygame.display.flip()

    pygame.time.Clock().tick(60)


import logging
from collections import OrderedDict

import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parallel import DataParallel, DistributedDataParallel
import models.networks as networks
import models.lr_scheduler as lr_scheduler
from .base_model import BaseModel
from models.loss import GANLoss, DiscLossWGANGP, L_cross, L_TV, L_spa, L_color
from models.archs.unet_arch import ContrastAdjustment
import utils.util as util
from metrics.niqe import calculate_niqe

logger = logging.getLogger('base')

class RetouchModel(BaseModel):
    def __init__(self, opt):
        super(RetouchModel, self).__init__(opt)

        if opt['dist']:
            self.rank = torch.distributed.get_rank()
        else:
            self.rank = -1  # non dist training
        train_opt = opt['train']

        # define network and load pretrained models
        self.netG = networks.define_G(opt).to(self.device)
        self.netC = networks.define_C(opt).to(self.device)
        # self.netD_pair = networks.define_D_pair(opt).to(self.device)
        if opt['dist']:
            self.netG = DistributedDataParallel(self.netG, device_ids=[torch.cuda.current_device()])
            self.netC = DistributedDataParallel(self.netC, device_ids=[torch.cuda.current_device()])
            # self.netD_pair = DistributedDataParallel(self.netD_pair, device_ids=[torch.cuda.current_device()])
        else:
            self.netG = DataParallel(self.netG)
            self.netC = DataParallel(self.netC)
            # self.netD_pair = DataParallel(self.netD_pair)

        if self.is_train:

            self.netD_H = networks.define_D(opt).to(self.device)
            if opt['dist']:
                self.netD_H = DistributedDataParallel(self.netD_H, device_ids=[torch.cuda.current_device()])
            else:
                self.netD_H = DataParallel(self.netD_H)
            self.netG.train()
            self.netC.train()
            self.netD_H.train()
            # self.netD_pair.train()
            # loss
            if train_opt['pixel_weight'] > 0:
                l_pix_type = train_opt['pixel_criterion']
                if l_pix_type == 'smoothl1':
                    self.cri_pix = nn.SmoothL1Loss(beta=0.01).to(self.device)
                elif l_pix_type == 'l1':
                    self.cri_pix = nn.L1Loss().to(self.device)
                elif l_pix_type == 'l2':
                    self.cri_pix = nn.MSELoss().to(self.device)
                else:
                    raise NotImplementedError('Loss type [{:s}] not recognized.'.format(l_pix_type))
                self.l_pix_w = train_opt['pixel_weight']
            else:
                logger.info('Remove pixel loss.')
                self.cri_pix = None

            # G feature loss
            self.cri_l1 = nn.L1Loss().to(self.device)
            if train_opt['feature_weight'] > 0:
                l_fea_type = train_opt['feature_criterion']
                if l_fea_type == 'l1':
                    self.cri_fea = nn.L1Loss().to(self.device)
                elif l_fea_type == 'l2':
                    self.cri_fea = nn.MSELoss().to(self.device)
                else:
                    raise NotImplementedError('Loss type [{:s}] not recognized.'.format(l_fea_type))
                self.l_fea_w = train_opt['feature_weight']
            else:
                logger.info('Remove feature loss.')
                self.cri_fea = None
            if train_opt['spa_weight'] > 0:
                self.cri_spa = L_spa(train_opt['spa_kernel']).to(self.device)
                self.l_spa_w = train_opt['spa_weight']
            else:
                self.cri_spa = None
                logger.info('Remove spa loss.')
            if train_opt['cross_weight'] > 0:
                self.cri_cross = L_cross().to(self.device)
                self.l_cross_w = train_opt['cross_weight']
            else:
                self.cri_cross = None
                logger.info('Remove cross loss.')
            if train_opt['color_weight'] > 0:
                l_color_type = train_opt['color_criterion']
                self.cri_color = L_color().to(self.device)
                self.l_color_w = train_opt['color_weight']
            else:
                self.cri_color = None
                logger.info('Remove color loss.')
            self.l_cond_dis_w = train_opt['cond_dis_weight']
            if self.l_cond_dis_w <= 0:
                logger.info('Remove cond_distance loss.')
            self.l_cond_code_w = train_opt['cond_code_weight']
            if self.l_cond_code_w <= 0:
                logger.info('Remove cond_code loss.')

            if train_opt['tv_weight'] > 0:
                self.cri_tv = L_TV(train_opt['tv_weight']).to(self.device)
            else:
                self.cri_tv = None
                logger.info('Remove tv loss.')
            if self.cri_fea:  # load VGG perceptual loss
                self.vgg_loss = vgg_loss(instance=True).to(self.device)
                if opt['dist']:
                    self.vgg_loss = DistributedDataParallel(self.vgg_loss, device_ids=[torch.cuda.current_device()])
                else:
                    self.vgg_loss = DataParallel(self.vgg_loss)

            # GD gan loss
            if self.opt['gan_type'] == 'wgan':
                self.criterionGAN = DiscLossWGANGP()
            else:
                self.criterionGAN = GANLoss(self.opt['gan_type'], 1.0, 0.0).to(self.device)
            self.l_gan_w = train_opt['gan_weight']
            self.l_gan_pair_w = train_opt['gan_pair_weight']
            # G_update_ratio and G_init_iters
            self.G_update_ratio = train_opt['G_update_ratio'] if train_opt['G_update_ratio'] else 1
            self.G_init_iters = train_opt['G_init_iters'] if train_opt['G_init_iters'] else 0
            # D_update_ratio and D_init_iters
            self.D_update_ratio = train_opt['D_update_ratio'] if train_opt['D_update_ratio'] else 1
            self.D_init_iters = train_opt['D_init_iters'] if train_opt['D_init_iters'] else 0

            # optimizers
            # G
            wd_G = train_opt['weight_decay_G'] if train_opt['weight_decay_G'] else 0
            optim_params = []
            for k, v in self.netG.named_parameters():  # can optimize for a part of the model
                if v.requires_grad:
                    optim_params.append(v)
                else:
                    if self.rank <= 0:
                        logger.warning('Params [{:s}] will not optimize.'.format(k))
            self.optimizer_G = torch.optim.Adam(optim_params, lr=train_opt['lr_G'],
                                                weight_decay=wd_G,
                                                betas=(train_opt['beta1_G'], train_opt['beta2_G']))
            self.optimizers.append(self.optimizer_G)
            # C
            wd_C = train_opt['weight_decay_C'] if train_opt['weight_decay_C'] else 0
            self.optimizer_C = torch.optim.Adam(self.netC.parameters(), lr=train_opt['lr_C'],
                                                weight_decay=wd_C,
                                                betas=(train_opt['beta1_C'], train_opt['beta2_C']))
            self.optimizers.append(self.optimizer_C)
            # D
            wd_D = train_opt['weight_decay_D'] if train_opt['weight_decay_D'] else 0
            self.optimizer_D_H = torch.optim.Adam(self.netD_H.parameters(), lr=train_opt['lr_D'],
                                                weight_decay=wd_D,
                                                betas=(train_opt['beta1_D'], train_opt['beta2_D']))
            self.optimizers.append(self.optimizer_D_H)

            # self.optimizer_D_pair = torch.optim.Adam(self.netD_pair.parameters(), lr=train_opt['lr_D'],
                                                # weight_decay=wd_D,
                                                # betas=(train_opt['beta1_D'], train_opt['beta2_D']))
            # self.optimizers.append(self.optimizer_D_pair)

            # schedulers
            if train_opt['lr_scheme'] == 'MultiStepLR':
                for optimizer in self.optimizers:
                    self.schedulers.append(
                        lr_scheduler.MultiStepLR_Restart(optimizer, train_opt['lr_steps'],
                                                         restarts=train_opt['restarts'],
                                                         weights=train_opt['restart_weights'],
                                                         gamma=train_opt['lr_gamma'],
                                                         clear_state=train_opt['clear_state']))
            elif train_opt['lr_scheme'] == 'CosineAnnealingLR_Restart':
                for optimizer in self.optimizers:
                    self.schedulers.append(
                        lr_scheduler.CosineAnnealingLR_Restart(
                            optimizer, train_opt['T_period'], eta_min=train_opt['eta_min'],
                            restarts=train_opt['restarts'], weights=train_opt['restart_weights']))
            else:
                raise NotImplementedError('MultiStepLR learning rate scheme is enough.')

            self.log_dict = OrderedDict()

        # print network
        self.print_network()
        self.load()

    def feed_data(self, data, GT=True, ref=True):
        self.real_H, self.ref, self.ref_alt = None, None, None

        self.var_L = data['LQ'].to(self.device)  # LQ
        if ref and 'ref' in  data:
            self.ref = data['ref'].to(self.device) # ref
            self.ref_path = data['ref_path']
        if ref and 'ref_alt' in  data:
            self.ref_alt = data['ref_alt'].to(self.device) # ref
            self.ref_path_alt = data['ref_path_alt']
        if GT:
            self.real_H = data['GT'].to(self.device)  # GT

    def backward_D_basic(self, netD, real, fake, ext=''):
        # Real
        pred_real = netD.forward(real)
        pred_fake = netD.forward(fake)
        if self.opt['gan_type'] == 'wgan':
            loss_D_real = torch.sigmoid(pred_real).mean()
            loss_D_fake = torch.sigmoid(pred_fake).mean()
            loss_D = loss_D_fake - loss_D_real + self.criterionGAN.calc_gradient_penalty(netD,
                                                real.data, fake.data)
            D_real = loss_D_real
            D_fake = loss_D_fake
        elif self.opt['gan_type'] == 'ragan':
            loss_D = (self.criterionGAN(pred_real - torch.mean(pred_fake), 1.) +
                                      self.criterionGAN(pred_fake - torch.mean(pred_real), 0.)) / 2
            D_real = torch.mean(torch.sigmoid(pred_real - torch.mean(pred_fake)))
            D_fake = torch.mean(torch.sigmoid(pred_fake - torch.mean(pred_real)))
        else:
            loss_D_real = self.criterionGAN(pred_real, 1.)
            loss_D_fake = self.criterionGAN(pred_fake, 0.)
            loss_D = (loss_D_real + loss_D_fake) * 0.5
            D_real = torch.mean(torch.sigmoid(pred_real))
            D_fake = torch.mean(torch.sigmoid(pred_fake))
        self.log_dict['D_real'+ext] = D_real.item()
        self.log_dict['D_fake'+ext] = D_fake.item()
        return loss_D

    def backward_G(self, step):
        #
        l_g_total = 0
        if step % self.D_update_ratio == 0 and step > self.D_init_iters:
            if self.cri_pix:  # pixel loss between input out
                ###l_g_pix_ref_cycle = self.cri_pix(self.rec_ref_cycle, self.ref)
                l_g_pix_ref = self.cri_pix(self.rec_ref, self.ref)
                l_g_pix = self.l_pix_w *l_g_pix_ref
                ###l_g_pix = self.l_pix_w * 0.5*(l_g_pix_ref + l_g_pix_ref_cycle)
                l_g_total += l_g_pix
                self.log_dict['l_g_pix'] = l_g_pix.item()
                ## self.log_dict['l_g_pix_fake_ref'] = l_g_pix_fake_ref.item()
            if self.cri_cross:
                l_g_cross = self.l_cross_w * self.cri_cross(self.fake_H)
                l_g_total += l_g_cross
                self.log_dict['l_g_cross'] = l_g_cross.item()
            if self.cri_color:
                l_g_color = self.l_color_w * self.cri_color(self.fake_H, self.var_L)
                l_g_total += l_g_color
                self.log_dict['l_g_color'] = l_g_color.item()
            if self.cri_tv:
                l_g_tv = self.cri_tv(self.fake_H)
                l_g_total += l_g_tv
                self.log_dict['l_g_tv'] = l_g_tv.item()
            if self.cri_fea:  # feature loss between input out
                l_g_fea = self.l_fea_w * self.vgg_loss(vgg_process(self.fake_H), vgg_process(self.var_L))
                l_g_total += l_g_fea
                self.log_dict['l_g_fea'] = l_g_fea.item()
            if self.cri_spa:
                l_spa = self.l_spa_w * torch.mean(self.cri_spa(self.fake_ref, self.ref))
                l_g_total += l_spa
                self.log_dict['l_spa'] = l_spa.item()
            if self.cri_color:
                pass
            # loss on cond distribution
            if self.l_cond_dis_w >0 :
                l_g_cond_dis_fakeH_ref = self.l_cond_dis_w * nn.functional.mse_loss(self.cond_fake_H, self.cond_ref)
                l_g_total += l_g_cond_dis_fakeH_ref
                self.log_dict['l_g_cond_fakeH_dis'] = l_g_cond_dis_fakeH_ref.item()
            if self.l_cond_code_w >0 :
                diff_fakeH_refH = (self.cond_fake_H - self.cond_ref).squeeze()
                diff_fakeH_L = (self.cond_fake_H  - self.cond_L).squeeze()
                diff_refH_L = (self.cond_ref - self.cond_L).squeeze()
                self.tau = torch.mean(diff_refH_L*diff_refH_L, dim=-1)+1e-10
                self.positive = torch.mean(diff_fakeH_refH*diff_fakeH_refH, dim=-1)
                self.negative = torch.mean(diff_fakeH_L*diff_fakeH_L, dim=-1)
                positive = self.positive/self.tau
                negative = self.negative/self.tau
                l_g_cond_fakeH = self.l_cond_code_w * nn.functional.l1_loss(positive / (positive + negative), torch.zeros_like(self.positive))
                l_g_total += l_g_cond_fakeH
                self.log_dict['l_g_cond_code'] = l_g_cond_fakeH.item()
            if self.opt['use_gan']:
                #gan G loss
                # H
                pred_g_fake = self.netD_H(self.netC(self.fake_H))
                pred_g_fake_ref = self.netD_H(self.netC(self.fake_ref))
                if self.opt['gan_type'] == 'gan':
                    l_g_gan = self.l_gan_w * ( 0.9*self.criterionGAN(pred_g_fake, 1.) + 0.1*self.criterionGAN(pred_g_fake_ref, 1.) )
                elif self.opt['gan_type'] == 'wgan':
                    l_g_gan = -(0.9*pred_g_fake.mean() + 0.1*pred_g_fake_ref.mean()) * self.l_gan_w
                elif self.opt['gan_type'] == 'ragan':
                    pred_d_real = self.netD_H(self.cond_ref).detach()
                    l_g_gan = self.l_gan_w * 0.5* (
                        (self.criterionGAN(pred_d_real - torch.mean(pred_g_fake), 0.) +
                        self.criterionGAN(pred_g_fake - torch.mean(pred_d_real), 1.)) * 0.9 + (self.criterionGAN(pred_d_real - torch.mean(pred_g_fake_ref), 0.) +
                        self.criterionGAN(pred_g_fake_ref - torch.mean(pred_d_real), 1.)) * 0.1
                        )
                l_g_total += l_g_gan
                self.log_dict['l_g_gan'] = l_g_gan.item()

            self.l_g_total = l_g_total
            self.log_dict['l_g_total'] = l_g_total.item()
            return l_g_total

    def augmentation(self, input): # randomly augment some input
        aug_seed = torch.rand(1)
        if aug_seed<0.001:
            # adaptive Gaussian Noise
            bg_noise_std = 0.3 * (0.2+0.8*torch.rand(1).item()) * torch.std(input, dim=[1,2,3], keepdim=True)
            ada_noise_std = 0.04 * input.clamp(max=0.5)
            input_aug = (input + bg_noise_std*torch.randn_like(input) + ada_noise_std*torch.randn_like(input)).clamp_(min=0., max=1.)
        elif aug_seed < 0.001:
            # quantization error
            stairs = 64
            input_aug = torch.floor(input*stairs)/stairs
        else:
            input_aug = input

        return input_aug

    def light_encode(self, input): # -> (batchsize, cond_nf)
        return torch.mean(self.netC(input), dim=[2,3], keepdim=False)

    def forward(self, step):
        self.fake_H = self.netG(self.netC, self.var_L, self.ref)

        ref_aug = self.augmentation(self.ref)
        self.fake_ref = self.netG(self.netC, ref_aug, self.ref_alt)
        self.rec_ref = self.netG(self.netC, ref_aug, self.ref)

    def optimize_parameters(self, step):
        #netC
        self.optimizer_C.zero_grad()
        #turn off D gradients
        for p in self.netD_H.parameters():
            p.requires_grad = False
        #netG
        self.optimizer_G.zero_grad()
        self.forward(step)
        l_g_total = self.backward_G(step)
        if l_g_total:
            l_g_total.backward()
        # update netG
        self.optimizer_G.step()

        if self.opt['use_gan']:
            #turn on D gradients
            for p in self.netD_H.parameters():
                p.requires_grad = True
            self.optimizer_D_H.zero_grad()
            if step % self.G_update_ratio == 0 and step > self.G_init_iters:
                cond_ref = self.netC(self.ref)
                cond_fake_H_detach = self.netC(self.fake_H.detach())
                l_d = self.l_gan_w * self.backward_D_basic(self.netD_H, cond_ref, cond_fake_H_detach, ext='')
                self.log_dict['l_d'] = l_d.item()
                l_d.backward()
                # update netD_H
                self.optimizer_D_H.step()

        # update netC
        self.optimizer_C.step()

    def test(self, ref_cri):
        self.netG.eval()
        self.netC.eval()
        # self.netD_pair.eval()
        with torch.no_grad():

            index = 0
            if ref_cri == 'mse_GT': # if provided with GT
                mse = 1e6 # choose smallest
                for i in range(self.ref.size()[1]):
                    fake_H_i = self.netG(self.netC, self.var_L, self.ref[:,i,:,:,:])
                    mse_i = torch.pow(self.real_H - fake_H_i,2).sum(dim=[1,2,3])
                    if mse > mse_i: # choose smallest
                        mse = mse_i
                        index = i
            elif ref_cri == 'color_condition': # compare the condition codes
                cond_nf = self.opt['condition_nf']
                cond_L = self.light_encode(self.var_L)
                illum_L = torch.mean(self.var_L, dim=[1,2,3], keepdim=True)
                cond_diff = 1e6  # choose smallest
                for i in range(self.ref.size()[1]):
                    illum_ref_i = torch.mean(self.ref[:,i,:,:,:], dim=[1,2,3], keepdim=True)
                    if illum_ref_i < 0.3:
                        continue
                    cond_ref_i = self.light_encode(self.ref[:,i,:,:,:]/illum_ref_i*illum_L)
                    cond_diff_i = nn.functional.mse_loss(cond_L, cond_ref_i)
                    if cond_diff > cond_diff_i:
                        cond_diff = cond_diff_i
                        index = i
            elif ref_cri == 'niqe': # if no GT is provided for validation
                niqe = 1e6 # choose smallest
                for i in range(self.ref.size()[1]):
                    fake_H_i = self.netG(self.netC, self.var_L, self.ref[:,i,:,:,:])
                    fake_H_i_img = util.tensor2img(fake_H_i[0,:,:,:])  # uint8
                    try:
                        niqe_i = calculate_niqe(fake_H_i_img, 0).flatten()[0]
                        if niqe > niqe_i: # choose smallest
                            niqe = niqe_i
                            index = i
                    except:
                        niqe_i = None
                        logger.info('NIQE calculation failed')

            elif ref_cri == 'random':
                index = torch.randint(low=0, high=self.ref.size()[1], size=(1,))[0]
            else:
                raise NotImplementedError('Selection criteria ref_cri: [{:s}] not recognized. Please choose from mse_GT/niqe/random.'.format(ref_cri))

            self.ref = self.ref[:,index,:,:,:]

            if self.is_train:
                ref_aug = self.augmentation(self.ref)
                self.fake_H = self.netG(self.netC, self.var_L, self.ref)
                self.rec_ref = self.netG(self.netC, ref_aug, self.ref)
                if self.ref_alt is not None:
                    self.fake_ref = self.netG(self.netC, ref_aug, self.ref_alt)
                    self.rec_ref_cycle = self.netG(self.netC, self.fake_ref, self.ref)
                else:
                    self.fake_ref = None
                    self.rec_ref_cycle = None
            else:
                self.fake_H = self.netG(self.netC, self.var_L, self.ref)
                if self.ref_alt is not None:
                    self.fake_ref = self.netG(self.netC, ref_aug, self.ref_alt)
                    self.rec_ref_cycle = self.netG(self.netC, self.fake_ref, self.ref)
                else:
                    self.fake_ref = None
                    self.rec_ref_cycle = None

        self.netG.train()
        self.netC.train()
        # self.netD_pair.train()

    def get_current_log(self):
        return self.log_dict

    def get_current_visuals(self, GT=True):
        out_dict = OrderedDict()
        out_dict['LQ'] = self.var_L.detach()[0].float().cpu()
        out_dict['rlt'] = self.fake_H.detach()[0].float().cpu()
        if self.is_train:
            out_dict['rec_ref'] = self.rec_ref.detach()[0].float().cpu()
            if self.ref_alt is not None:
                out_dict['fake_ref'] = self.fake_ref.detach()[0].float().cpu()
                out_dict['rec_ref_cycle'] = self.rec_ref_cycle.detach()[0].float().cpu()
        out_dict['ref'] = self.ref.detach()[0].float().cpu()

        if GT:
            out_dict['GT'] = self.real_H.detach()[0].float().cpu()
        return out_dict

    def print_network(self):
        # Generator
        s, n = self.get_network_description(self.netG)
        if isinstance(self.netG, nn.DataParallel) or isinstance(self.netG, DistributedDataParallel):
            net_struc_str = '{} - {}'.format(self.netG.__class__.__name__,
                                             self.netG.module.__class__.__name__)
        else:
            net_struc_str = '{}'.format(self.netG.__class__.__name__)
        if self.rank <= 0:
            logger.info('Network G structure: {}, with parameters: {:,d}'.format(net_struc_str, n))
            logger.info(s)
        # Condition Encoder
        s, n = self.get_network_description(self.netC)
        if isinstance(self.netC, nn.DataParallel) or isinstance(self.netC, DistributedDataParallel):
            net_struc_str = '{} - {}'.format(self.netC.__class__.__name__,
                                             self.netC.module.__class__.__name__)
        else:
            net_struc_str = '{}'.format(self.netC.__class__.__name__)
        if self.rank <= 0:
            logger.info('Network C structure: {}, with parameters: {:,d}'.format(net_struc_str, n))
            logger.info(s)
        if self.is_train:
            # Discriminator
            for netD in [self.netD_H]:
                s, n = self.get_network_description(netD)
                if isinstance(netD, nn.DataParallel) or isinstance(netD,
                                                                        DistributedDataParallel):
                    net_struc_str = '{} - {}'.format(netD.__class__.__name__,
                                                    netD.module.__class__.__name__)
                else:
                    net_struc_str = '{}'.format(netD.__class__.__name__)
                if self.rank <= 0:
                    logger.info('Network D structure: {}, with parameters: {:,d}'.format(
                        net_struc_str, n))
                    logger.info(s)

    def load(self):
        load_path_G = self.opt['path']['pretrain_model_G']
        if load_path_G is not None:
            logger.info('Loading model for G [{:s}] ...'.format(load_path_G))
            self.load_network(load_path_G, self.netG, self.opt['path']['strict_load'])
        load_path_C = self.opt['path']['pretrain_model_C']
        if load_path_C is not None:
            logger.info('Loading model for C [{:s}] ...'.format(load_path_C))
            self.load_network(load_path_C, self.netC, self.opt['path']['strict_load'])
        load_path_D_H = self.opt['path']['pretrain_model_D_H']
        if load_path_D_H is not None:
            logger.info('Loading model for D_H [{:s}] ...'.format(load_path_D_H))
            self.load_network(load_path_D_H, self.netD_H, self.opt['path']['strict_load'])
        load_path_D_pair = self.opt['path']['pretrain_model_D_pair']

    def updateG(self, new_model_dict):
        if isinstance(self.netG, nn.DataParallel):
            network = self.netG.module
            network.load_state_dict(new_model_dict)

    def save(self, iter_label):
        self.save_network(self.netG, 'G', iter_label)
        self.save_network(self.netC, 'C', iter_label)
        self.save_network(self.netD_H, 'D_H', iter_label)


import requests
from bs4 import BeautifulSoup
import pandas as pd

url = "https://webscraper.io/test-sites/e-commerce/allinone/computers/laptops"
htmlDoc = requests.get(url)
# print(htmlDoc.text)

# Parser

soup = BeautifulSoup(htmlDoc.text, "lxml")
# print(soup.prettify)

# Access h1 tag
# print(soup.h1)

# Access header tag
# print(soup.header)

# Access div tag
# print(soup.div)

# Access string from nested tags
# print(soup.header.p)
# print(soup.header.p.string)

# Access a tag in header
# check1 = soup.header.a
# check1.attrs
# print(check1.attrs["data-target"])

# check1["new-target"] = "This is the new attribute"
# print(check1.attrs)

# Searching specific attribute

# price = soup.find("h4", class_="pull-right price")
# price = soup.find_all("h4", class_="pull-right price")[2:5]

# price = soup.find_all(["h4","a","p"])
# price =soup.find_all(["header", "div"])
# price =soup.find_all(id=True)
# print(price)

# Data Collection

name = soup.find_all("a", class_="title")
price = soup.find_all("h4", class_="pull-right price")
reviews = soup.find_all("p", class_="pull-right")
description = soup.find_all("p", class_="description")

# price = soup.find("h4", class_="pull-right price")
# print(price.text)

# Creating loop to make string from find_all list
productNameList = []
for i in name:
    name = i.text
    productNameList.append(name)

productPriceList = []
for i in price:
    price = i.text
    productPriceList.append(price)

productReviewsList = []
for i in reviews:
    reviews = i.text
    productReviewsList.append(reviews)

productDescriptionList = []
for i in description:
    description = i.text
    productDescriptionList.append(description)

# Creating data frame
table = pd.DataFrame({"Product Name": productNameList, "Product Price": productPriceList, "Product Reviews": productReviewsList, "Product Description": productDescriptionList})

# Exporting to csv
# table.to_csv("Price.csv", index=False)

# Read CSV
tabel2 = pd.read_csv("Price.csv")
print(tabel2)


import re
from pathlib import Path
from typing import List

from . import context, md
from .names import valid_name, reset_names
from ..models import Book, Section, Task
from .consts import LANG_TO_EMOJI

MD_IF_REGEX = re.compile(r"```(if(?:-not)?):(.*?)\n(.*?)```", re.MULTILINE | re.DOTALL)
STYLE_REGEX = re.compile(r"<style(?:.*?)>(.*?)</style>", re.MULTILINE | re.DOTALL)

LANG_TO_PRETTY_LANG = {
    "javascript": "JavaScript",
    "coffeescript": "CoffeeScript",
}

def extract_css_styles(content: str) -> str:
    styles = STYLE_REGEX.findall(content)

    if styles:
        content = STYLE_REGEX.sub("", content)

        for style in styles:
            add_styles(style)

    return content

def add_styles(style: str):
    style_path = context.WEBSITE_CSS.get()

    old_styles = style_path.read_text(encoding="utf-8")
    style_path.write_text(f"{old_styles}\n{style}", encoding="utf-8")

def solve_if_logic(task: Task):
    if "```if:" in task.description:
        supported_lags = {*task.solutions}

        def replacer(match: re.Match) -> str:
            if_type, langs, if_content = match.groups()
            if_langs = {*langs.strip().split(",")}

            if (if_type == "if") == bool(supported_lags & if_langs):
                return if_content

            return ""

        return MD_IF_REGEX.sub(replacer, task.description)

    return task.description

def generate_task(parent: Path, task: Task):
    def _generate_task():
        yield md.header(md.link(task.name, task.link))
        yield
        yield extract_css_styles(solve_if_logic(task))
        yield
        yield md.header("Solutions")

        for lang, (solution, *_) in task.solutions.items():
            pretty_lang = LANG_TO_PRETTY_LANG.get(lang.lower(), lang.title())

            yield md.header(f"{LANG_TO_EMOJI[lang.lower()]} {pretty_lang}", important=4)
            yield md.code(solution.code, lang)

        yield

    md.readme(parent, _generate_task(), f"{valid_name(task.name, unique=True)}.md")

def generate_section(parent: Path, section: Section):
    root = parent / valid_name(section.name)
    root.mkdir(parents=True, exist_ok=True)

    for task in section.tasks:
        generate_task(root, task)

def generate_book(book: Book):
    root = context.DOCS.get() / valid_name(book.name)

    for section in book.sections:
        generate_section(root, section)

def generate_summary(books: List[Book]):
    def section_summary(parent: str, section: Section):
        yield md.option(
            md.link(
                name=section.name,
                url=f"/{parent}/{valid_name(section.name)}",
                wrap=True,
            )
        )

        for task in section.tasks:
            yield md.option(
                md.link(
                    name=task.name,
                    url=f"/{parent}/{valid_name(section.name)}/{valid_name(task.name, unique=True)}.md",
                    wrap=True,
                ),
                ident=4,
            )

    def book_summary(book: Book):
        yield
        yield md.header(book.name)

        for section in book.sections:
            yield from section_summary(valid_name(book.name), section)

    def summary():
        yield md.header("Codding Challenges тнР", important=1)

        for book in books:
            yield from book_summary(book)

    md.readme(context.DOCS.get(), summary(), "SUMMARY.md")
    reset_names()

def generate_docs(books: List[Book], docs_path: Path):
    context.init_context(docs_path)
    generate_summary(books)

    for book in sorted(books, key=lambda b: b.name):
        generate_book(book)

__all__ = ["generate_docs"]


"""
Test for the design class

Created on: 09/02/2023
Author: Alexandre Bohyn
"""
import numpy as np
import pandas as pd  # type: ignore
import pytest  # type: ignore

from collections import Counter

import fatld
import random

class TestDesignErrors:
    def test_wrong_init(self):
        assert True

class TestDesignMethods:
    # Design 6 from Table 3 of Wu (1993)
    design = fatld.Design(runsize=32, m=1, cols=[29, 26, 22])
    relation = fatld.relation.Relation(["bcef", "bdeg", "acdeh"], m=1)

    def test_twlp(self):
        twlp = self.design.twlp(max_length=5)
        assert twlp == [[0, 0], [1, 4], [0, 2]]

    def test_twlp_type1(self):
        twlp = self.design.twlp(type_0=False, max_length=5)
        assert twlp == [[0, 0], [4, 1], [2, 0]]

    def test_wlp(self):
        wlp = self.design.wlp(max_length=5)
        assert wlp == [0, 5, 2]

    def test_flatten(self):
        flat_array = self.design.flatten()
        assert all(np.unique(flat_array) == [0, 1])

    def test_flatten_zero_coding(self):
        flat_array = self.design.flatten(zero_coding=False)
        assert all(np.unique(flat_array) == [-1, 1])

    def test_relation(self):
        rel = self.design.defining_relation()
        assert rel.words == self.relation.words

class TestCols:
    design = fatld.Design(runsize=32, m=1, cols=[29, 27])

    def test_add_cols(self):
        design_more = self.design.add_factor(22)
        assert design_more.cols == [4, 8, 16, 22, 27, 29]

    def test_add_wrong_col(self):
        with pytest.raises(ValueError):
            self.design.add_factor(72)

    def test_add_already_used_cols(self):
        with pytest.raises(ValueError):
            self.design.add_factor(4)

    def test_remove_cols(self):
        design_less = self.design.remove_factor(29)
        assert design_less.cols == [4, 8, 16, 27]

    def test_remove_wrong_cols(self):
        with pytest.raises(ValueError):
            self.design.remove_factor(17)

class TestClarity:
    design = fatld.Design(32, 1, [27, 29])
    df = pd.DataFrame(
        {
            "4-4 clear": [0, 15, 10, 25],
            "4-2 clear": [0, 15, 4, 19],
            "2-2 clear": [0, 9, 10, 19],
            "Totally clear": [0, 9, 4, 13],
        },
        dtype=int,
    )
    df = df.set_index(pd.Index(["4-4", "4-2", "2-2", "Any type"]))

    design2 = fatld.Design(runsize=32, m=2, cols=[17, 21, 25, 29, 31])
    df2 = pd.DataFrame(
        {
            "4-4 clear": [9, 36, 8, 53],
            "4-2 clear": [9, 4, 15, 28],
            "2-2 clear": [2, 36, 9, 47],
            "Totally clear": [2, 4, 2, 8],
        },
        dtype=int,
    )
    df2 = df2.set_index(pd.Index(["4-4", "4-2", "2-2", "Any type"]))

    def test_clarity(self):
        tfi = self.design.clarity()
        assert tfi.equals(self.df)

    def test_clarity_m2(self):
        tfi = self.design2.clarity()
        assert tfi.equals(self.df2)

    def test_clear(self):
        assertion_list = []
        for row in ["4-4", "4-2", "2-2"]:
            if row == "Any type":
                row_index = "all"
            else:
                row_index = row
            for col in [
                "4-4 clear",
                "4-2 clear",
                "2-2 clear",
                "Totally clear",
            ]:
                if col == "Totally clear":
                    col_index = "all"
                else:
                    col_index = col.replace(" clear", "")
                assertion_list.append(
                    self.design.clear(row_index, col_index)
                    == self.df.loc[row, col]
                )
        assert all(assertion_list)

    def test_clear_error(self):
        with pytest.raises(ValueError):
            self.design.clear("4-2", "4-3")

def test_from_array():
    D = fatld.Design(32, 1, [17, 21, 29, 31])
    mat = D.array
    newD = fatld.design.from_array(mat)
    assert D.cols == newD.cols

def test_beta_wlp():
    D = fatld.Design(32, 2, [17, 18, 20, 24, 19, 28, 5, 9, 6, 10, 7, 11, 13])
    vec, perm = D.beta_wlp(max_length=5)
    assert vec == [8.0, 37.0, 107.0]

def test_beta_aberration_low_n():
    D = fatld.Design(
        32, 2, [31]
    )  # Here n = 2 which is lower than the max_length set
    qvec, perm = D.beta_wlp(max_length=6)
    assert qvec == [0.0, 0.0, 0.0, 1.0]

def test_number_interactions():
    assert fatld.main.nbr_interactions(7, 5) == 119

def test_tfi_model_matrix():
    tfi_model_matrix = fatld.design.build_tfi_model_matrix(n=7, max_length=5)
    int_length = np.sum(tfi_model_matrix, axis=0).tolist()
    c = Counter(int_length)
    d = dict(c)
    assert d == {1: 7, 2: 21, 3: 35, 4: 35, 5: 21}

def test_beta_star_m3():
    """Test the computation of B* vector for m=3"""
    D = fatld.Design(64, 3, [22, 27, 41, 46])
    b, p = D.beta_star_wlp(max_length=6)
    assert b == [[0.0, 0], [0.1, 0], [3.2, 0], [2.9, 0]]

def test_beta_star_sum():
    """
    Test that for any design, the sum of A_i^0  words is equal to the sum of
    the beta* values
    """
    available_cols = [
        i for i in range(1, 32) if i not in [1, 2, 3, 4, 8, 12, 16]
    ]
    cols = random.sample(available_cols, 5)
    D = fatld.Design(32, 2, cols)
    ai_values = [sum(i[1:]) for i in D.twlp(type_0=True)]
    beta_values = [b[0] for b in D.beta_star_wlp()[0]]
    assert np.round(sum(ai_values)) == np.round(sum(beta_values))


from io import BytesIO
from xml.parsers.expat import ExpatError

import pytest

from pubtools.pulplib import YumRepository

def test_upload_comps_xml(client, requests_mocker):
    """A client can upload expected units from within a comps.xml."""

    repo_id = "repo1"
    repo = YumRepository(id=repo_id)
    repo.__dict__["_client"] = client

    # Some XML to upload.
    # This is fairly minimal as this test focuses on upload functionality.
    # There are other tests exercising the XML parser more thoroughly.
    xml = BytesIO(
        b"""
        <comps>
            <group>
                <id>3d-printing</id>
                <name>3D Printing</name>
                <name xml:lang="af">3D-drukwerk</name>
                <description>3D printing software</description>
                <packagelist>
                    <packagereq type="default">admesh</packagereq>
                    <packagereq>blender</packagereq>
                </packagelist>
            </group>

            <category>
                <id>kde-desktop-environment</id>
                <name>KDE Desktop</name>
                <display_order>10</display_order>
                <grouplist>
                    <groupid>kde-office</groupid>
                    <groupid>kde-telepathy</groupid>
                </grouplist>
            </category>

            <environment>
                <id>basic-desktop-environment</id>
                <name>Basic Desktop</name>
                <name xml:lang="af">Basiese werkskerm</name>
                <description>X Window System with a choice of window manager.</description>
                <grouplist>
                    <groupid>networkmanager-submodules</groupid>
                    <groupid>standard</groupid>
                </grouplist>
                <optionlist>
                    <groupid default="true">xmonad</groupid>
                    <groupid>xmonad-mate</groupid>
                </optionlist>
            </environment>

            <langpacks>
                <match install="stardict-dic-%s" name="stardict"/>
                <match install="tkgate-%s" name="tkgate"/>
            </langpacks>
        </comps>
    """
    )

    # Set up the requests it'll do:
    #
    # It should unassociate previous units
    requests_mocker.post(
        "https://pulp.example.com/pulp/api/v2/repositories/repo1/actions/unassociate/",
        json={"spawned_tasks": [{"task_id": "remove-task"}]},
    )

    # It'll search for the status of tasks.
    # Note: to avoid an overly complex mock we just let every task search return all
    # tasks rather than differentiating between remove and upload tasks
    upload_count = 4
    requests_mocker.post(
        "https://pulp.example.com/pulp/api/v2/tasks/search/",
        json=[{"task_id": "remove-task", "state": "finished"}]
        + [
            {"task_id": "upload-task-%d" % i, "state": "finished"}
            for i in range(0, upload_count)
        ],
    )

    # It will request various uploads
    requests_mocker.post(
        "https://pulp.example.com/pulp/api/v2/content/uploads/",
        [{"json": {"upload_id": "upload-%d" % i}} for i in range(0, upload_count)],
    )

    # It'll do an import against the uploads
    requests_mocker.post(
        "https://pulp.example.com/pulp/api/v2/repositories/repo1/actions/import_upload/",
        [
            {"json": {"spawned_tasks": [{"task_id": "upload-task-%d" % i}]}}
            for i in range(0, upload_count)
        ],
    )

    # It'll clean up the uploads
    for i in range(0, upload_count):
        requests_mocker.delete(
            "https://pulp.example.com/pulp/api/v2/content/uploads/upload-%d/" % i
        )

    # Mocker setup is complete.

    # It should start the upload OK
    upload_f = repo.upload_comps_xml(xml)

    # I can await the result
    tasks = upload_f.result()

    # There should be various tasks returned from the API
    assert sorted([t.id for t in tasks]) == [
        "upload-task-0",
        "upload-task-1",
        "upload-task-2",
        "upload-task-3",
    ]

    # Each task should be successful
    for t in tasks:
        assert t.completed
        assert t.succeeded

    # Gather info on exactly what the client imported
    imported_units = []
    for req in requests_mocker.request_history:
        if req.url.endswith("/import_upload/"):
            imported_units.append(req.json()["unit_metadata"])

    imported_units.sort(key=lambda u: u["_content_type_id"])

    # Did we import exactly the expected units?
    assert imported_units == [
        {
            "_content_type_id": "package_category",
            "id": "kde-desktop-environment",
            "name": "KDE Desktop",
            "display_order": 10,
            "packagegroupids": ["kde-office", "kde-telepathy"],
            "repo_id": "repo1",
        },
        {
            "_content_type_id": "package_environment",
            "id": "basic-desktop-environment",
            "name": "Basic Desktop",
            "translated_name": {"af": "Basiese werkskerm"},
            "description": "X Window System with a choice of window manager.",
            "group_ids": ["networkmanager-submodules", "standard"],
            "options": [
                {"group": "xmonad", "default": True},
                {"group": "xmonad-mate", "default": False},
            ],
            "repo_id": "repo1",
        },
        {
            "_content_type_id": "package_group",
            "id": "3d-printing",
            "name": "3D Printing",
            "translated_name": {"af": "3D-drukwerk"},
            "description": "3D printing software",
            "default_package_names": ["admesh"],
            "mandatory_package_names": ["blender"],
            "repo_id": "repo1",
        },
        {
            "_content_type_id": "package_langpacks",
            "matches": [
                {"install": "stardict-dic-%s", "name": "stardict"},
                {"install": "tkgate-%s", "name": "tkgate"},
            ],
            "repo_id": "repo1",
        },
    ]

def test_upload_empty_comps_xml(client, requests_mocker):
    """A client can upload an empty comps.xml, which merely removes existing units."""

    repo_id = "repo1"
    repo = YumRepository(id=repo_id)
    repo.__dict__["_client"] = client

    xml = BytesIO(b"<comps/>")

    # Set up the requests it'll do:
    #
    # It should unassociate previous units
    requests_mocker.post(
        "https://pulp.example.com/pulp/api/v2/repositories/repo1/actions/unassociate/",
        json={"spawned_tasks": [{"task_id": "remove-task"}]},
    )

    # It'll search for the status of tasks.
    requests_mocker.post(
        "https://pulp.example.com/pulp/api/v2/tasks/search/",
        json=[{"task_id": "remove-task", "state": "finished"}],
    )

    # And... that's it.

    # It should start the upload OK
    upload_f = repo.upload_comps_xml(xml)

    # I can await the result
    tasks = upload_f.result()

    # It should just return the removal task
    assert [t.id for t in tasks] == ["remove-task"]
    assert tasks[0].completed
    assert tasks[0].succeeded

    # Check exactly the removed types
    assert requests_mocker.request_history[0].json() == {
        "criteria": {
            "type_ids": [
                "package_group",
                "package_category",
                "package_environment",
                "package_langpacks",
            ]
        }
    }

def test_bad_comps_xml(client, requests_mocker, tmpdir):
    """A client requested to upload an invalid comps.xml will raise immediately
    without making any requests to Pulp."""

    repo_id = "repo1"
    repo = YumRepository(id=repo_id)
    repo.__dict__["_client"] = client

    comps_xml = tmpdir.join("comps.xml")
    comps_xml.write(b"Oops not valid comps")

    # It should raise
    with pytest.raises(ExpatError):
        repo.upload_comps_xml(str(comps_xml))

    # As we did not register anything in requests_mocker, we've already
    # implicitly tested that no requests happened. But just to be clear...
    assert not requests_mocker.request_history


from django.shortcuts import render, redirect
from django.http import HttpResponse, Http404
from .models import Location,Category,Image
import pyperclip
# Create your views here.
def gen_pics(request):
   images = Image.objects.all()
   category_results = Category.objects.all()
   location_results = Location.objects.all()
   return render(request, 'all-pics/general.html', {"all_images":images})
def search_results(request):
   if 'searchItem' in request.GET and request.GET["searchItem"]:
       search_term = request.GET.get("searchItem")
       searched_image = Image.search_by_category(search_term)
       message = f"{search_term}"
       return render(request, 'all-pics/search.html', {"message": message, "searchItem": searched_image})
   else:
       message = "You haven't searched for any thing"
       return render(request, 'all-pics/general.html', {"message": message})
def get_category(request):
   category_results = Category.objects.all()
   location_results = Location.objects.all()
   return render(request, 'all-pics/general.html', {'category_results': category_results, 'location_results': location_results})
def get_location(request):
   category_results = Category.objects.all()
   location_results = Location.objects.all()
   return render(request, 'all-pics/general.html', { 'category_results': category_results, 'location_results': location_results})


from app import create_app
from flask import jsonify, request
import sqlalchemy
from sqlalchemy.sql import text
import os
import data_analysis as da

#ENV variable
localhost=False
fields = ['team_name','points','yards','pass_yards','rush_yards']

conn = sqlalchemy.create_engine('sqlite:///football_stats.db')
app = create_app("development")

if(not localhost):
    import logging
    logging.basicConfig(filename='logging.log',level=logging.DEBUG)

def map_keys_to_values(keys, values):
    return {key : value for key, value in zip(keys, values)}

@app.route('/')
def index():
    return 'To query the API, put team names as parameters. For example: "/team_a=DEN&team_b=DET" '

@app.route('/to_sql')
def sqlify():
    if(localhost):
        da.to_sql()
        return "Done!"
    else:
        return "This can only be done locally!"

@app.route('/team_a=<a>&team_b=<b>')
def get_stats(a,b):
    return jsonify(da.stats(a,b))

@app.route('/max_difference/<stat>')
def get_max_difference(stat):
    if stat not in fields:
        return {"error":"Couldn't query database - invalid stat."}

    max_offense = conn.execute(text("select max("+stat+") from offense")).fetchone()[0]
    min_offense = conn.execute(text("select min("+stat+") from offense")).fetchone()[0]

    max_defense = conn.execute(text("select max("+stat+") from defense")).fetchone()[0]
    min_defense = conn.execute(text("select min("+stat+") from defense")).fetchone()[0]

    output = {}
    output["offense"] = max_offense-min_offense
    output["defense"] = max_defense-min_defense
    return jsonify(output)

@app.route('/stats/<team>')
def get_team_stats(team):
    output = {}
    query = text("select "+','.join(fields)+" from defense where team_name = :t")
    defense_stats = conn.execute(query,t=team).fetchone()
    output['defense'] = map_keys_to_values(fields,defense_stats)

    query = text("select "+','.join(fields)+" from offense where team_name = :t")
    offense_stats = conn.execute(query,t=team).fetchone()
    output['offense'] = map_keys_to_values(fields,offense_stats)

    return jsonify(output)

@app.route('/log')
def read_log():
    f  = open('logging.log', "r")
    return f.read()

@app.route('/status')
def status():
    return 'Ok!'

@app.after_request
def after_request(response):
  response.headers.add('Access-Control-Allow-Origin', '*')
  response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
  response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
  return response

if __name__ == '__main__':
    if(localhost):
        app.run()
    else:
        port = int(os.environ.get("PORT", 8886))
        app.run(host='0.0.0.0', port=port)


import tensorflow as tf
from tensorflow import keras
from abc import ABC, abstractmethod
from utils.Builders.model_builder import (build_discrete_actor, build_continuous_stochastic_actor,
    build_state_value_critic, CheckpointedModel)
from utils.model_util_functions import *
from utils.util_functions import append_folder_name_to_path

class A2CModel(ABC):

    def create_models(self, state_space, action_space, learning_rate, gradient_clipping, save_path):
        self.actor = self._create_actor(state_space, action_space, learning_rate, gradient_clipping,
            append_folder_name_to_path(save_path, 'actor'))
        self.critic = build_state_value_critic(state_space, learning_rate, gradient_clipping,
            append_folder_name_to_path(save_path, 'critic'))

    def load_models(self, checkpoint_path, gradient_clipping):
        self.actor = CheckpointedModel(append_folder_name_to_path(checkpoint_path, 'actor'), gradient_clipping)
        self.critic = CheckpointedModel(append_folder_name_to_path(checkpoint_path, 'critic'), gradient_clipping)

    @abstractmethod
    def _create_actor(self, state_space, action_space, learning_rate, gradient_clipping, save_path):
        pass

    @abstractmethod
    def forward(self, states):
        pass

    @abstractmethod
    def _compute_actor_loss(tape, states, actions, advantages):
        pass

    def update_actor(self, states, actions, advantages):
        tape = tf.GradientTape()
        loss = self._compute_actor_loss(tape, states, actions, advantages)
        trainable_variables = self.actor.get_trainable_variables()
        gradients = tape.gradient(loss, trainable_variables)
        self.actor.update_model(gradients)
        return loss

    def update_critic(self, states, returns):
        with tf.GradientTape() as tape:
            state_values = self.critic(states)
            state_values = tf.squeeze(state_values, axis = -1)
            loss = keras.losses.MSE(returns, state_values)

        trainable_variables = self.critic.get_trainable_variables()
        gradients = tape.gradient(loss, trainable_variables)
        self.critic.update_model(gradients)
        return loss

    def save_models(self):
        self.actor.save_model()
        self.critic.save_model()

class A2CModelDiscrete(A2CModel):

    def _create_actor(self, state_space, action_space, learning_rate, gradient_clipping, save_path):
        return build_discrete_actor(state_space, action_space, learning_rate, gradient_clipping, save_path)

    def forward(self, states):
        values = tf.squeeze(self.critic(states), axis = -1)
        prob_dists = self.actor(states)
        actions = sample_from_categoricals(prob_dists)
        return values.numpy(), actions.numpy()

    def _compute_actor_loss(self, tape, states, actions, advantages):
        with tape:
            prob_dists = self.actor(states)
            log_probs_dists = compute_log_of_tensor(prob_dists)
            log_probs_actions = select_values_of_2D_tensor(log_probs_dists, actions)
            loss = -tf.reduce_mean(log_probs_actions*advantages)
        return loss

class A2CModelContinuous(A2CModel):

    def __init__(self, action_space):
        self.min_action = action_space.get_min_action()
        self.max_action = action_space.get_max_action()

    def _create_actor(self, state_space, action_space, learning_rate, gradient_clipping, save_path):
        return build_continuous_stochastic_actor(state_space, action_space, learning_rate, gradient_clipping, save_path)

    def forward(self, states):
        values = tf.squeeze(self.critic(states), axis = -1)
        mus, log_sigmas = self.actor(states)
        actions = tf.clip_by_value(sample_from_gaussians(mus, log_sigmas), self.min_action, self.max_action)
        return values.numpy(), actions.numpy()

    def _compute_actor_loss(self, tape, states, actions, advantages):
        with tape:
            mus, log_sigmas = self.actor(states)
            probs_actions = compute_pdf_of_gaussian_samples(mus, log_sigmas, actions)
            log_probs_actions = compute_log_of_tensor(probs_actions)
            loss = -tf.reduce_mean(log_probs_actions*advantages)
        return loss


import streamlit as st
from PIL import Image
import cv2
import numpy as np
from tensorflow.keras.models import load_model

def prepare_image(img):
    img_size = 64
    image = img.resize((img_size, img_size))
    image = np.array(image).reshape(1, 64, 64, 3)
    return image

@st.cache
def load_image(image_file):
    img = Image.open(image_file)
    return img

def main():
    st.write('''

    Clasificación de Números realizados con la Mano

''', unsafe_allow_html=True)

    menu = ["Sobre la App", "Cargar Imagen", "Cámara"]
    st.sidebar.write('''

Bienvenido

''', unsafe_allow_html=True)
    choice = st.sidebar.selectbox("Selecciona una opción", menu)

    col1, col2 = st.beta_columns(2)

    if choice == "Cargar Imagen":
        col1.write('''

Aquí se muestra la Imagen

''', unsafe_allow_html=True)

        #st.sidebar.title('Cargar Imagen')
        image_file = st.sidebar.file_uploader("", type=['jpg', 'jpeg'])

        if image_file is not None:
            #st.write(type(image_file))
            # st.write(dir(image_file))
            file_details = {"filename":image_file.name, "filetype":image_file.type, "filesize":image_file.size}
            #st.write(file_details)

            img = load_image(image_file)
            col1.image(img, width=250)

            data = prepare_image(img)

            col2.write('''

''', unsafe_allow_html=True)

            if col2.button('Clasificar', key="1"):
                prediction = model.predict([data])
                #print(prediction)
                col2.write("El número en la imagen corresponde a {}".format((prediction[0].tolist()).index(max(prediction[0].tolist()))))
    elif choice == "Cámara":
        st.sidebar.write("")
        col1.write('''

Cámara Activa

''', unsafe_allow_html=True)
        FRAME_WINDOW = col1.image([])
        camera = cv2.VideoCapture(0) # 0 corresponde al índice de la cámara

        col2.write('''

''', unsafe_allow_html=True)
        capture = col2.button('Tomar Foto', key="2")
        col2.write("")

        while choice == 'Cámara':
            _, frame = camera.read()
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            FRAME_WINDOW.image(frame)
            if capture:
                image = cv2.resize(frame, (64, 64))
                data = image.reshape(1, 64, 64, 3)
                prediction = model.predict([data])
                #print(prediction)
                col2.write("El número en la imagen corresponde a {}".format((prediction[0].tolist()).index(max(prediction[0].tolist()))))
                capture = False
    else:
        col1.write('''

Sobre la App

                        Esta es una aplicación de Computer Vision que tiene como objetivo la clasificación de
                        imágenes de números realizados con la mano, desde cero (0) hasta cinco (5).

''',unsafe_allow_html=True)
        col2.write('''

Cargar Imagen

                        En esta opción, se carga la imagen que se desea clasificar; luego, se presiona
                        el botón de clasificar y la aplicación imprime el resultado.

Cámara

                        En esta opción, se toma la captura de la imagen que se desea clasificar
                        y la aplicación imprime el resultado.

''', unsafe_allow_html=True)
if __name__ == '__main__':
    model = load_model('Network.model')
    main()


from __future__ import annotations
from typing import List, Callable, Iterable, Optional, Tuple, Union

import routingblocks
from .cluster_removal import ClusterRemovalOperator, DistanceBasedClusterMemberSelector

class StationSeedSelector:
    def __init__(self, stations: List[routingblocks.Vertex], randgen: Optional[routingblocks.Randgen] = None):
        self._stations = stations
        self._randgen = randgen

    def _get_station_locations(self, solution: routingblocks.Solution):
        return [
            y for x in self._stations for y in solution.find(x.vertex_id)
        ]

    def __call__(self, evaluation: routingblocks.Evaluation, solution: routingblocks.Solution,
                 removed_vertices: List[routingblocks.NodeLocation]) -> routingblocks.NodeLocation:
        # Get all stations in the solution not removed yet
        stations = [x for x in self._get_station_locations(solution) if
                    x not in removed_vertices]
        if len(stations) == 0:
            raise StopIteration
        # Return a random one
        picked_station_location = stations[self._randgen.randint(0, len(stations) - 1)]
        return picked_station_location

class StationVicinityRemovalOperator(routingblocks.DestroyOperator):
    """
    Station vicinity removal is a specialized cluster removal operator designed to reorder customer visits in the
    vicinity of replenishment stations. The operator defines the vicinity of a station by selecting a random radius
    based on a percentage of the maximum distance between vertices. It then randomly chooses a recharging station
    and removes the station along with vertices within the selected radius, repeating this process until the
    desired number of vertices are removed.
    """

    def __init__(self, instance: routingblocks.Instance,
                 get_distance: Callable[[routingblocks.Vertex, routingblocks.Vertex], float],
                 min_radius_factor: float, max_radius_factor: float,
                 randgen: Optional[routingblocks.Randgen]):
        """
        :param instance: Instance the operator will be applied to
        :param get_distance: A function taking two vertices and returning the distance between them. The distance can be arbitrary, i.e., does not have to correspond to the evaluation function.
        :param min_radius_factor: Minimum of the interval the radius is picked from
        :param max_radius_factor: Maximum of the interval the radius is picked from
        :param randgen: Random number generator
        """
        routingblocks.DestroyOperator.__init__(self)
        self._cluster_removal_operator = ClusterRemovalOperator(
            seed_selector=StationSeedSelector(list(instance.stations), randgen),
            cluster_member_selector=DistanceBasedClusterMemberSelector(
                vertices=[*instance.stations, *instance.customers],
                get_distance=get_distance,
                min_radius_factor=min_radius_factor,
                max_radius_factor=max_radius_factor,
                randgen=randgen)
        )

    def can_apply_to(self, solution: routingblocks.Solution) -> bool:
        """
        Station vicinity removal can be applied to any solution that contains at least one station.
        """
        return any(node.vertex.is_station
                   for route in solution.routes for node in route)

    def name(self) -> str:
        return "StationVicinityRemovalOperator"

    def apply(self, evaluation: routingblocks.Evaluation, solution: routingblocks.Solution,
              number_of_removed_vertices: int) -> List[int]:
        return self._cluster_removal_operator.apply(evaluation, solution, number_of_removed_vertices)


import streamlit as st
import yfinance as yf
import plotly.graph_objects as go

# Título do App
st.title('Stock History App')
st.sidebar.title('Selecione o stock')

ticker_symbol=st.sidebar.text_input('stock','AAPL',max_chars=10)

# Baixando os dados
data=yf.download(ticker_symbol,start='2020-01-01',end='2023-06-26')

# Exibindo os dados
st.subheader('HIstorico')
st.dataframe(data)

# Plot o grafico
fig=go.Figure()
fig.add_trace(go.Scatter(x=data.index,y= data['Close'],name= 'Fechamento'))
fig.update_layout(title=f"{ticker_symbol}",xaxis_title = "Date", yaxis_title = "Preço")
st.plotly_chart(fig)


#!/usr/bin/python3
"""
Schools AIP action
"""
from app.models import storage
from app.api.v1.views import app_views
from app.models.certificate import Certificate
from app.models.certificate_request_verification import VerifyCertificate
from flask import abort, jsonify, make_response, request

@app_views.route('/certificate', methods=['GET'], strict_slashes=False)
def get_certificate():
    """
    Retrieves the list of all certificate objects
    or a specific certificate
    """
    all_certificates = storage.all(Certificate).values()
    list_certificates = []
    for certificate in all_certificates:
        list_certificates.append(certificate.to_dict())
    return jsonify(list_certificates)

@app_views.route('/users/<user_id>/certificate', methods=['GET'], strict_slashes=False)
def get_user_certificate(user_id):
    """
    Retrieves the list of all certificate objects
    for a specific user
    """
    all_certificates = storage.get_user_certificates(Certificate, user_id)
    if not all_certificates:
        abort(404, "No certificate was found")
    list_certificates = []
    for certificate in all_certificates:
        certificate_verification_status = storage.get_certificates_status(VerifyCertificate, certificate.id)
        certificate_data = certificate.to_dict()
        certificate_data["certificate_status"] = certificate_verification_status.certificate_status
        list_certificates.append(certificate_data)
    return jsonify(list_certificates)

@app_views.route('certificate/<certificate_id>',
                 methods=['GET'], strict_slashes=False)
def get_Certificate(certificate_id):
    """ Retrieves an Certificate """
    certificate = storage.get(Certificate, certificate_id)
    if not certificate:
        abort(404)
    return jsonify(certificate.to_dict())

@app_views.route('/users/<user_id>/certificates/<certificate_id>', methods=['DELETE'],
                 strict_slashes=False)
def delete_Certificate(certificate_id):
    """
    Deletes a certificate Object
    """

    certificate = storage.get(Certificate, certificate_id)

    if not certificate:
        abort(404)

    storage.delete(certificate)
    storage.save()

    return make_response(jsonify({}), 200)

@app_views.route('/users/<user_id>/certificates', methods=['POST'], strict_slashes=False)
def post_certificate(user_id):
    """
    Creates a certificate
    """
    data = request.get_json()
    if not data:
        abort(400, description="Not a JSON")
    if 'student_name' not in data:
        abort(400, description="student_name")
    if 'student_email' not in data:
        abort(400, description="Missing student email")
    if "school_id" not in data:
        abort(400, 'Missing school id')
    if "school_name" not in data:
        abort(400, 'Missing school name')
    if "school_major" not in data:
        abort(400, 'Missing school major')
    if "school_department" not in data:
        abort(400, "Missing school department")
    if "school_location" not in data:
        abort(400, "MIssing school location")

    data['user_id'] = user_id
    instance = Certificate(**data)
    certificate_status = {
        "user_id": user_id,
        "school_id": instance.school_id,
        "certificate_id": instance.id
    }
    status = VerifyCertificate(**certificate_status)
    instance.save()
    status.save()
    certificate = instance.to_dict()
    certificate["certificate_status"] = status.certificate_status
    return make_response(jsonify(certificate), 201)

@app_views.route('/users/<user_id>/certificates/<certificate_id>',
                 methods=['PUT'], strict_slashes=False)
def put_certificate(user_id, certificate_id):
    """
    Updates a certificate
    """
    certificate = storage.get(Certificate, certificate_id)

    if not certificate:
        abort(404)

    if not request.get_json():
        abort(400, description="Not a JSON")

    ignore = ['id', 'email', 'created_at', 'updated_at']

    data = request.get_json()
    for key, value in data.items():
        if key not in ignore:
            setattr(certificate, key, value)
    storage.save()
    return make_response(jsonify(certificate.to_dict()), 200)


from wordcloud import WordCloud, STOPWORDS
import numpy as npy
import random as random
from PIL import Image

def randomize(str):
    str = str.split(' ')
    random.shuffle(str)
    str = ' '.join(str)
    return str

dataset = open("alt.txt", "r").read()
dataset = randomize(dataset)
maskArray = npy.array(Image.open("india.jpg"))
customstopwords = {'in', 'on', 'as', 'from', 'video', 'viral', 'shared', 'claim', 'fake', 'image', 'old', 'new', 'false', 'falsely'}
customstopwords |= STOPWORDS
cloud = WordCloud(background_color = "white", width = 800, height = 400, mask = maskArray, max_words = 200, stopwords = set(customstopwords))
cloud.generate(dataset)
cloud.to_file("wordcloud-india.png")