import time

import utilities.customer_logger as cl
import logging
from time import sleep
from base.basepage import BasePage

class ComparisonPage(BasePage):

    log = cl.customLogger(logging.DEBUG)

    def __init__(self, driver):
        super().__init__(driver)
        self.driver = driver

    # Locators
    _premium_package = ".//button//comparison-package//h1[contains(text(),'Premium')]"
    _stor_package = ".//button//comparison-package//h1[contains(text(),'Stor')]"
    _mellan_package = ".//button//comparison-package//h1[contains(text(),'Mellan')]"
    _bas_package = ".//button//comparison-package//h1[contains(text(),'Bas')]"
    _channel = ".//comparison-channel-list/div//comparison-channel//img[@alt='TV3 ']"
    _close_button = ".//div[contains(@class,'expanded')]//div[@class='comparison-close-icon']"
    _channel_format = ".//comparison-channel-list/div//comparison-channel//img[@alt='{0}']"
    _channel_title = ".//div[contains(@class,'comparison-channels-title')]"
    _channel_description = ".//div[contains(@class,'comparison-channels-description')]"

    _cookie = ".//app-cookie-notice//button"
    _clickable_logos = ".//comparison-channel-list//div[@class='comparison-channel-container']/div[contains(@class,'clickable')]/img"
    _comparison_channels_title = ".//div[contains(@class,'comparison-channels-title')]"
    _comparison_tabs_filters = ".//comparison-tabs-filters//button"
    _comparison_tabs_filters_2 = ".//comparison-tabs-filters//button[contains(@class,'comparison-tab-button') and contains(text(),'{}')]"

    _channels_in_package = ".//div[contains(@class,'comparison-current-channel')]//comparison-channel/div/div/img"
    _main_packages = ".//button//comparison-package//h1[contains(text(),'')]"

    def closeCookie(self):
        self.ElementClick(self._cookie, locatorType="xpath")

    def clickOnPremium(self):
        self.ElementClick(self._premium_package, locatorType="xpath")

    def clickOnStor(self):
        self.ElementClick(self._stor_package, locatorType="xpath")

    def clickOnMellan(self):
        self.ElementClick(self._mellan_package, locatorType="xpath")

    def clickOnBas(self):
        self.ElementClick(self._bas_package, locatorType="xpath")

    def clickChannel(self):
        self.scrollIntoView(self._channel, locatorType="xpath")
        self.ElementClick(self._channel, locatorType="xpath")
        time.sleep(3)

    def closeChannel(self):
        self.waitForElement(self._close_button, locatorType="xpath")
        self.ElementClick(self._close_button, locatorType="xpath")

    def getMainPackages(self):
        list_main_package = []
        channel_amount = self.getElements(self._main_packages, locatorType="xpath")
        for channel in channel_amount:
            # print(channel.text)
            list_main_package.append(channel.text)
        self.log.info(list_main_package)
        return len(list_main_package)

    def getClickableChannels(self):
        """
        :return: list of clickable channels
        """
        # time.sleep(3)
        list_clickable_channels = []
        Clickable_channels = self.getElements(self._clickable_logos, locatorType="xpath")
        for clickable_channel in Clickable_channels:
            clickable_channel = clickable_channel.get_attribute('alt')
            list_clickable_channels.append(clickable_channel)
        return list_clickable_channels

    def clickThroughComparisonPackages(self):
        self.closeCookie()

        self.clickOnPremium()
        assert self.verify_channel_list() == True
        self.clickOnStor()
        assert self.verify_channel_list() == True
        self.clickOnMellan()
        assert self.verify_channel_list() == True
        self.clickOnBas()
        assert self.verify_channel_list() == True

    def checkPremiumPackage(self):
        self.clickOnPremium()
        self.getMainPackages()

    def openChannel(self):
        self.clickChannel()

    def tabFilters(self):
        tab_filter_buttons = self.getElements(self._comparison_tabs_filters, locatorType="xpath")
        return tab_filter_buttons

    def openAllPremiumChannels(self):
        self.closeCookie()

        channel_list = self.getClickableChannels()
        for channel in channel_list:
            import time
            time.sleep(0.5)
            self.scrollIntoView(locator=self._channel_format.format(channel), locatorType="xpath")
            self.ElementClick(locator=self._channel_format.format(channel), locatorType="xpath")
            assert self.isElementDisplayed(self._channel_title, locatorType="xpath") == True
            assert self.isElementDisplayed(self._channel_description, locatorType="xpath") == True
        self.scrollIntoView(self._comparison_channels_title, locatorType="xpath")

    def openAllPremiumTabs(self):
        """
        :return: Idea is to scroll through the channel icons on each tab filter
        """
        self.closeCookie()
        comparison_tabs_filter = self.tabFilters()
        exclude_first_tab = comparison_tabs_filter[1:]
        for click_button in exclude_first_tab:
            self.ElementClick(element=click_button)
            time.sleep(2)

    def openAllStorTab(self):
        """
        :return: Idea is to scroll through the channel icons on each tab filter
        """
        self.closeCookie()
        self.clickOnStor()
        comparison_tabs_filter = self.tabFilters()
        exclude_first_tab = comparison_tabs_filter[1:]
        for click_button in exclude_first_tab:
            self.ElementClick(element=click_button)
            time.sleep(2)

    def clickOnTab(self, tab):
        """
        :param tab: selected Tv kanaler, Playtjänster, Viaplay
        :return:
        """
        self.scrollIntoView(locator=self._comparison_tabs_filters_2.format(tab), locatorType="xpath")

        if tab == "Tv kanaler":
            self.ElementClick(locator=self._comparison_tabs_filters_2.format(tab), locatorType="xpath")
        elif tab == "Playtjänster":
            self.ElementClick(locator=self._comparison_tabs_filters_2.format(tab), locatorType="xpath")
            time.sleep(2)
        elif tab == "Viaplay":
            self.ElementClick(locator=self._comparison_tabs_filters_2.format(tab), locatorType="xpath")
            time.sleep(2)
        else:
            self.log.error("Tab doesn't exist")

    def openAllStorChannels(self):

        self.clickOnStor()

        channel_list = self.getClickableChannels()
        for channel in channel_list:
            import time
            time.sleep(0.5)
            self.scrollIntoView(locator=self._channel_format.format(channel), locatorType="xpath")
            self.ElementClick(locator=self._channel_format.format(channel), locatorType="xpath")
            assert self.isElementDisplayed(self._channel_title, locatorType="xpath") == True
            assert self.isElementDisplayed(self._channel_description, locatorType="xpath") == True
        self.scrollIntoView(self._comparison_channels_title, locatorType="xpath")

    def openAllMellanChannels(self):

        self.clickOnMellan()

        channel_list = self.getClickableChannels()
        for channel in channel_list:
            import time
            time.sleep(0.5)
            self.scrollIntoView(locator=self._channel_format.format(channel), locatorType="xpath")
            self.ElementClick(locator=self._channel_format.format(channel), locatorType="xpath")
            assert self.isElementDisplayed(self._channel_title, locatorType="xpath") == True
            assert self.isElementDisplayed(self._channel_description, locatorType="xpath") == True
        self.scrollIntoView(self._comparison_channels_title, locatorType="xpath")

    def openAllBasChannels(self):

        self.clickOnBas()

        channel_list = self.getClickableChannels()
        for channel in channel_list:
            import time
            time.sleep(0.5)
            self.scrollIntoView(locator=self._channel_format.format(channel), locatorType="xpath")
            self.ElementClick(locator=self._channel_format.format(channel), locatorType="xpath")
            assert self.isElementDisplayed(self._channel_title, locatorType="xpath") == True
            assert self.isElementDisplayed(self._channel_description, locatorType="xpath") == True
        self.scrollIntoView(self._comparison_channels_title, locatorType="xpath")

    def clickableChannels(self):
        self.clickOnBas()
        time.sleep(2)
        assert self.verify_channel_list() == True
        self.getClickableChannels()

    def clickOnStorAndTab(self, tab):
        self.clickOnStor()
        self.clickOnTab(tab)

    ##validation
    def verify_channel_list(self):
        result = self.isElementPresent(self._channels_in_package, locatorType="xpath")
        return result

    def verify_channel_content(self):
        result = self.isElementPresent(".//div[@class='comparison-channel-title']", locatorType="xpath")
        return result

    def verify_comparison_title(self):
        result = self.isElementDisplayed(self._channel_title, locatorType="xpath")
        return result

    def verify_comparison_description(self):
        result = self.isElementDisplayed(self._channel_description, locatorType="xpath")
        return result


from __future__ import division
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.ensemble import RandomForestClassifier
from pygam import LinearGAM, s, f

def get_pred_label(pred):
    '''
    This functions return splitting labels
    '''
    result = []
    for i in pred:
        if i < 0 :
            result.append(1)
        else:
            result.append(0)
    return result

def split_patient(patient_ids, df):
  '''
  This function returns splitting using ids
  '''
  X_train, X_test, y_train, y_test = train_test_split(patient_ids, patient_ids, test_size=0.25)
  df_train = df[df.PERSON_CD.isin(X_train)]
  df_test = df[df.PERSON_CD.isin(X_test)]
  return df_train, df_test

def split_naive(df):
  X_train, X_test, y_train, y_test = train_test_split(df, df, test_size=0.25)
  return X_train, X_test, y_train, y_test

def get_label(df):
    '''
    This functions return splitting labels
    '''
    result = []
    for index, rows in df.iterrows():
        if rows['DIFF_HRZ'] < 0 :
            result.append(1)
        else:
            result.append(0)
    return result

#Loading Datasets
df = pd.read_csv('/Users/lin/Desktop/thesis_code/df_age.csv')

# #Splitting DataSet using ids
# X_train_id, X_test_id = split_patient(df.PERSON_CD.unique(), df = df)
# y_train_id, y_test_id = get_label(X_train_id), get_label(X_test_id)

#Splitting DataSet naively
X_train, X_test, _, _ = split_naive(df)
y_train, y_test = X_train['DIFF_HRZ'], X_test['DIFF_HRZ']

##Linear mixed effect
def Linearmixed(model, df_train, df_test):
  md = smf.mixedlm(model, data = df_train, groups=df_train["AgeGroup"])
  mdf = md.fit()
  print(mdf.summary())
  test_result = mdf.predict(df_test)
  result_pred = []
  for i in test_result:
    if i < 0 :
      result_pred.append(1)
    else:
      result_pred.append(0)

  return result_pred

#Params
numeric_columns = ['AGE', 'DOSE_MG_PER_KG', 'DOPAMINE_RATE_MEAN',
                   'HYDROMORPHONE_RATE_MEAN', 'MEDIAN_HR_5_Z_y']
categorical_columns = ['opioid_inf',
                       'sed_inf',
                       'opioid_bolus',
                       'sed_bolus',
                       'vasodi_inf',
                       'vasodi_bolus',
                       'ino_inf',
                       'ino_bolus',
                       'AgeGroup']

categorical_columns_linear = ['opioid_inf',
                       'sed_inf',
                       'opioid_bolus',
                       'sed_bolus',
                       'vasodi_inf',
                       'vasodi_bolus',
                       'ino_inf',
                       'ino_bolus',
                       'AgeGroup']
columns  = categorical_columns + numeric_columns

column_model = " + ".join(columns)
model = "DIFF_HRZ ~ " + column_model

prediction_Linear_mixed = Linearmixed(model, X_train, X_test)

##Random Forest
clf = RandomForestClassifier(max_depth=100,
                             bootstrap=True,
                             max_features = 3,
                             min_samples_leaf = 5,
                             min_samples_split = 12,
                             n_estimators = 300)
clf.fit(X_train[columns],get_label(X_train))
random_Forest_result = clf.predict(X_test[columns])

#GAM
formula = f(0)
for i,name in enumerate(categorical_columns[1:]):
    formula += f(i)
for j,name in enumerate(numeric_columns):
    formula += s(j+len(categorical_columns))
print(formula)

listings_gam = LinearGAM(formula).fit(X_train[columns], y_train)

label_true = get_label(X_test)
preds = listings_gam.predict(X_test[columns])
pred_label = get_pred_label(preds)
pred_label_mixedLinear = get_pred_label(prediction_Linear_mixed)

print("The accuracy score for GAM model is {:0.3f}".format(accuracy_score(label_true, pred_label)))
print("The accuracy score for Random Forest is: {:0.3f}".format(accuracy_score(label_true,random_Forest_result)))
print("The accuracy score for linear Mixed effect model is: {:0.3f}".format(accuracy_score(label_true,pred_label_mixedLinear)))

final_pred=[]
for i in range (len(label_true)):
  if pred_label[i] + random_Forest_result[i] + pred_label_mixedLinear[i] >= 2:
    final_pred.append(1)
  else:
    final_pred.append(0)

print("The accuracy score for final is {:0.3f}".format(accuracy_score(label_true, final_pred)))

df_result = pd.DataFrame(data = {'PERSON_CD':X_test['PERSON_CD'],'Time':X_test['DT_UTC'], 'RandomForest':random_Forest_result, 'LinearMixed':prediction_Linear_mixed, 'y_true':y_test})
df_result.to_csv('model_result.csv', index = False)

from IPython import embed
embed()


"""
Series of tests and example code to run elecsus via the API

Last updated 2018-07-04 MAZ
"""
# py 2.7 compatibility
from __future__ import (division, print_function, absolute_import)

import matplotlib.pyplot as plt
import numpy as np
import time

import sys
sys.path.append('../')
import elecsus_methods as EM
sys.path.append('../libs')
from spectra import get_spectra

def test_MLfit():
	"""
	Test simple Marquart-Levenburg fit for S1 spectrum. Generate a data set and add random noise,
	then run an ML fit to the noisy data set, with randomised initial parameters that are the correct ones
	plus some small change
	"""

	p_dict = {'Elem':'Rb','Dline':'D2','T':80.,'lcell':2e-3,'Bfield':600.,'Btheta':0.,
		'Bphi':0.,'GammaBuf':0.,'shift':0.}

	p_dict_guess = p_dict

	# only need to specify parameters that are varied
	p_dict_bools = {'T':True,'Bfield':True}

	E_in = np.sqrt(1./2) * np.array([1.,1.,0])
	# need to express E_in as Ex, Ey and phase difference for fitting
	E_in_angle = [E_in[0].real,[abs(E_in[1]),np.angle(E_in[1])]]

	# Generate spectrum and add some random noise
	x = np.linspace(-10000,10000,300)
	[y] = get_spectra(x,E_in,p_dict,outputs=['S1']) + np.random.randn(len(x))*0.01

	# randomise the starting parameters a little
	p_dict_guess = p_dict
	p_dict_guess['T'] += np.random.randn()*1
	p_dict_guess['Bfield'] += np.random.randn()*10

	data = [x,y.real]

	best_params, RMS, result = EM.fit_data(data, p_dict_guess, p_dict_bools, E_in=E_in_angle, data_type='S1',fit_algorithm='ML')
	report = result.fit_report()
	fit = result.best_fit

	print(report)

	plt.plot(x,y,'k.',label='Data')
	plt.plot(x,fit,'r-',lw=2,label='Fit')

	plt.legend(loc=0)

	plt.show()

def compare_fit_methods():
	"""
	Compare ML and RR, SA and differential_evolution (DE) fitting for a more complicated case where there is a chi-squared local minimum in parameter space.
	In this case, the simple ML fit doesn't work, since it gets stuck in a very bad local minimum.

	The RR, SA and DE methods all converge to a good solution, but in different times.
	The RR fit takes somewhere in the region of 50x longer than ML, but produces a much better fit.
	The SA fit takes somewhere in the region of 100x longer than ML, but produces a much better fit.
	The DE fit takes somewhere in the region of 20x longer than ML, but produces a much better fit.

	From this test (and others which are broadly similar but for different data sets), we see that for global minimisation, we recommend using DE
	"""

	p_dict = {'Elem':'Rb','Dline':'D2','T':100.,'lcell':5e-3,'Bfield':7000.,'Btheta':0.,
		'Bphi':0.,'GammaBuf':50,'shift':0.}

	# only need to specify parameters that are varied
	p_dict_bools = {'T':True,'Bfield':True,'GammaBuf':True}#,'E_x':True,'E_y':True,'E_phase':True}

	E_in = np.array([0.7,0.7,0])
	# need to express E_in as Ex, Ey and phase difference for fitting
	E_in_angle = [E_in[0].real,[abs(E_in[1]),np.angle(E_in[1])]]

	x = np.linspace(-21000,-13000,300)
	y = get_spectra(x,E_in,p_dict,outputs=['S0'])[0] + np.random.randn(len(x))*0.01 # <<< RMS error should be around 0.01 for the best case fit
	data = [x,y.real]

	# start at not the optimal parameters (near a local minimum in chi-squared)
	p_dict['T'] = 90
	p_dict['Bfield'] = 6100
	p_dict['GammaBuf'] = 150

	p_dict_bounds = {}

	# time it...
	st_ML = time.time()
	best_paramsML, RMS_ML, resultML = EM.fit_data(data, p_dict, p_dict_bools, E_in=E_in_angle, data_type='S0')
	et_ML = time.time() -st_ML
	print('ML complete')

	# RR and SA need range over which to search
	p_dict_bounds['T'] = [30]
	p_dict_bounds['Bfield'] = [3000]
	p_dict_bounds['GammaBuf'] = [150]

	st_RR = time.time()
	best_paramsRR, RMS_RR, resultRR = EM.fit_data(data, p_dict, p_dict_bools, E_in=E_in_angle,
																					p_dict_bounds=p_dict_bounds, data_type='S0', fit_algorithm='RR')
	et_RR = time.time() - st_RR
	print('RR complete')

	st_SA = time.time()
	best_paramsSA, RMS_SA, resultSA = EM.fit_data(data, p_dict, p_dict_bools, E_in=E_in_angle,
																					p_dict_bounds=p_dict_bounds, data_type='S0', fit_algorithm='SA')
	et_SA = time.time() - st_SA
	print('SA complete')

	# differential evolution needs upper and lower bounds on fit parameters
	p_dict_bounds['T'] = [70,130]
	p_dict_bounds['Bfield'] = [4000,8000]
	p_dict_bounds['GammaBuf'] = [0, 100]

	st_DE = time.time()
	best_paramsDE, RMS_DE, resultDE = EM.fit_data(data, p_dict, p_dict_bools, E_in=E_in_angle,
																					p_dict_bounds=p_dict_bounds, data_type='S0',
																					fit_algorithm='differential_evolution')
	et_DE = time.time() - st_DE
	print('DE complete')

	print(('ML found best params in ', et_ML, 'seconds. RMS error, ', RMS_ML))
	print(('RR found best params in ', et_RR, 'seconds. RMS error, ', RMS_RR))
	print(('SA found best params in ', et_SA, 'seconds. RMS error, ', RMS_SA))
	print(('DE found best params in ', et_DE, 'seconds. RMS error, ', RMS_DE))

	reportML = resultML.fit_report()
	fitML = resultML.best_fit
	reportRR = resultRR.fit_report()
	fitRR = resultRR.best_fit
	reportSA = resultSA.fit_report()
	fitSA = resultSA.best_fit
	reportDE = resultDE.fit_report()
	fitDE = resultDE.best_fit

	#print '\n ML fit report:'
	#print reportML
	#print '\n DE fit report:'
	#print reportDE

	plt.plot(x,y,'k.',label='Data')
	plt.plot(x,fitML,'-',lw=2,label='ML fit')
	plt.plot(x,fitDE,'-',lw=2,label='RR fit')
	plt.plot(x,fitDE,'--',lw=2,label='SA fit')
	plt.plot(x,fitDE,':',lw=2,label='DE fit')

	plt.legend(loc=0)

	plt.show()

if __name__ == '__main__':
	compare_fit_methods()


import string
from collections import deque

def algo() -> int:
    heights = dict()
    start_point = (-1, -1)
    end_goal = (-1, -1)
    result = -1
    directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]

    print("hello, day 12: Hill Climbing Algorithm")

    # you'll need to find the shortest path from any square at elevation a to the square marked E
    # What is the fewest steps required to move starting from any square with elevation a
    # to the location that should get the best signal?

    grid_list = read_instructions()
    height = len(grid_list)
    width = len(grid_list[0])

    for y, line in enumerate(grid_list):
        for x, char in enumerate(line):
            if char == "S":
                start_point = (x, y)
                heights[(x, y)] = 0
            elif char == "E":
                end_goal = (x, y)
                heights[(x, y)] = 25
            else:
                heights[(x, y)] = string.ascii_lowercase.index(char)

    visited = set()
    visited.add(end_goal)

    q = deque()
    distance = 0
    q.appendleft((distance, end_goal))

    while q:
        current_distance, current_location = q.popleft()
        current_height = heights[current_location]
        if current_height == 0:
            result = current_distance
            break

        x, y = current_location
        for dx, dy in directions:
            new_x, new_y = x + dx, y + dy
            # don't go outside the grid
            if new_x < 0 or new_x >= width or new_y < 0 or new_y >= height:
                continue

            neighbour_location = (new_x, new_y)
            if neighbour_location in visited:
                continue

            neighbour_height = heights[neighbour_location]
            if current_height - 1 <= neighbour_height:
                new_distance = current_distance + 1
                neighbour_entry = (new_distance, neighbour_location)
                q.append(neighbour_entry)
                visited.add(neighbour_location)

    return result

def read_instructions() -> list[str]:
    instructions_raw = open(instruction_file).readlines()
    instructions_lines = [line.strip() for line in instructions_raw]
    return instructions_lines

if __name__ == '__main__':
    instruction_file = 'day12_input.txt'
    debug = False
    trace = False

    print(f'result: {algo()}')


#!/usr/bin/env python
# encoding: utf-8

# Before running this program, first Start HFO server:
# $> ./bin/HFO --offense-agents 1

import itertools
import math
from hfo import *
import argparse

"""
Possible game statuses:
  [IN_GAME] Game is currently active
  [GOAL] A goal has been scored by the offense
  [CAPTURED_BY_DEFENSE] The defense has captured the ball
  [OUT_OF_BOUNDS] Ball has gone out of bounds
  [OUT_OF_TIME] Trial has ended due to time limit
  [SERVER_DOWN] Server is not alive
"""

def main():
  parser = argparse.ArgumentParser()
  parser.add_argument('--port', default=6000, type=int)
  parser.add_argument('--feature_set', default=HIGH_LEVEL_FEATURE_SET, type=int)
  args = parser.parse_args()

  # Create the HFO Environment
  hfo = HFOEnvironment()
  # Connect to the server with the specified
  # feature set. See feature sets in hfo.py/hfo.hpp.
  hfo.connectToServer(args.feature_set,
                      '/home/student/Desktop/HFO-master/bin/teams/base/config/formations-dt', args.port,
                      'localhost', 'base_right', True)

  for episode in range(5):
    status = IN_GAME
    while status == IN_GAME:
      # Grab the state features from the environment
      features = hfo.getState()
      status = hfo.step()
    # Check the outcome of the episode
    print(('Episode %d ended with %s'%(episode, hfo.statusToString(status))))
    # Quit if the server goes down
    if status == SERVER_DOWN:
      hfo.act(QUIT)
      exit()

if __name__ == '__main__':
  main()


import cv2
import numpy as np
from PIL import Image
import os
# from matplotlib import pyplot as plt

dir = '/test/nPCR'
image_path = 'D:/Study/Dataset/medicaldata_uint16_png_3_2_1' + dir
outputpath = 'D:/Study/Dataset/medicaldata_uint16_png_3_2_2' + dir
outputpath = outputpath + '/'
#outputpath = 'D:/Study/Dataset/PCR_nPCR/output_GE/'

def rotateimage(img_path,outputpath,filename):
    img = cv2.imread(img_path,-1)
    #img180 = np.rot90(img, 2)
    img180 = cv2.rotate(img, cv2.ROTATE_180)
    # cv2.imshow("rotate", img180)
    # cv2.waitKey(0)
    output_imagepath = outputpath + 'rotate' + filename
    cv2.imwrite(output_imagepath, img180)

filelist = os.listdir(image_path) #获取主目录下的子文件
for first_dir in filelist:
    img_path = image_path + '/' + first_dir
    #imagename, suffix = os.path.splitext(first_dir)
    rotateimage(img_path, outputpath, first_dir)


# encoding: utf-8
'''
@author: jinjin
@contact: cantaloupejinjin@gmail.com
@file: expanddata.py
@time: 2019/5/10 11:13
'''
import pandas as pd
from  imblearn.over_sampling import SMOTE
filePath = "preprocess/test1.csv"
df = pd.read_csv(filePath,names=['sentiment','review'])
x = df["review"].tolist()  #x
y = df["sentiment"].tolist()#y
groupby_data_orginal = df.groupby('sentiment').count()
print("print x", x)
print("print y", y)
print(groupby_data_orginal)#打印输出原始数据集样本分类分布

# 使用SMOTE方法进行过抽样处理
model_smote = SMOTE() # 建立SMOTE模型对象
x_smote_resampled, y_smote_resampled = model_smote.fit_sample(x,y) # 输入数据并作过抽样处理
print("上一步没问题")
x_smote_resampled = pd.DataFrame(x_smote_resampled, columns=['review']) # 将数据转换为数据框并命名列名
y_smote_resampled = pd.DataFrame(y_smote_resampled,columns=['sentiment']) # 将数据转换为数据框并命名列名
smote_resampled = pd.concat([x_smote_resampled, y_smote_resampled],axis=1) # 按列合并数据框
groupby_data_smote = smote_resampled.groupby('sentiment').count() # 对label做分类汇总
print (groupby_data_smote) # 打印输出经过SMOTE处理后的数据集样本分类分布


from setuptools import setup

def required_packages():
    deps = [
        'pandas',
        'numpy',
        'matplotlib',
        'torch',
        'torchvision',
        'pillow',
        'seaborn',
    ]

setup(name='roofnet',
      version='0.1',
      description='Code for RoofNet',
      url='http://github.com/MishaLaskin/roofnet',
      author='ML',
      author_email='laskin.misha@gmail.com',
      install_requires=required_packages(),
      license='MIT',
      packages=['roofnet'],
      zip_safe=False)


import os
import sys
import glob
import random
from pathlib import Path
from argparse import ArgumentParser
import numpy as np
import torch
from mmcv.onnx import register_extra_symbolics
from mmocr.apis import init_detector

sys.path.append('mmocr/tools')
from deployment.pytorch2onnx import _convert_batchnorm

def create_input_data(prep_dir):
    prep_dir = Path(prep_dir)
    file_name = random.choice(os.listdir(prep_dir/'texts'))

    dummy_input = []
    for input_name in ['relations', 'texts', 'mask']:
        file_path = prep_dir/input_name/file_name
        data = torch.from_numpy(np.load(file_path))
        dummy_input.append(data)

    return tuple(dummy_input)

def pytorch2onnx(config_file, checkpoint_file, prep_dir,
                 output_file, opset_version=12):
    device = torch.device(type='cpu')
    model = init_detector(config_file, checkpoint_file, device=device)
    if hasattr(model, 'module'):
        model = model.module
    model.to(torch.device('cpu')).eval()
    _convert_batchnorm(model)

    dummy_input = create_input_data(prep_dir)
    dynamic_axes = {
        'relations': {0: 'num_texts', 1: 'num_texts'},
        'texts': {0: 'num_texts', 1: 'num_chars'},
        'mask': {0: 'num_texts', 1: 'num_chars'},
        'nodes': {0: 'num_texts', 1: 'num_texts'},
        'edges': {0: 'num_edges'},
    }

    model.forward = model.forward_onnx
    model.bbox_head.forward = model.bbox_head.forward_onnx
    register_extra_symbolics(opset_version)
    with torch.no_grad():
        torch.onnx.export(
            model,
            dummy_input,
            output_file,
            input_names=['relations', 'texts', 'mask'],
            output_names=['nodes', 'edges'],
            export_params=True,
            keep_initializers_as_inputs=False,
            verbose=False,
            opset_version=opset_version,
            dynamic_axes=dynamic_axes,
        )
    print(f'Successfully exported ONNX model: {output_file}')

def main():
    parser = ArgumentParser('Convert MMOCR models from pytorch to ONNX')
    parser.add_argument('--config', type=str, help='config file.')
    parser.add_argument('--checkpoint', type=str, help='checkpint file.')
    parser.add_argument('--prep-dir', type=str, help='path to preprocessed data')
    parser.add_argument('--onnx', type=str, help='path to save onnx model.')
    parser.add_argument('--opset-version', type=int, default=12,
                        help='ONNX opset version.')
    args = parser.parse_args()

    pytorch2onnx(args.config, args.checkpoint, args.prep_dir,
                 args.onnx, opset_version=args.opset_version)

if __name__ == '__main__':
    main()


# Author: Andrey Boytsov <andrey.boytsov@uni.lu> <andrey.m.boytsov@gmail.com>
# License: BSD 3 clause (C) 2017

# Fitting iris dataset (from sklearn). Generating embedding function and using it to visualize smooth transition from
# one value to another. Comparing to embedding_close, explores way more options, different transformations.

import sys
import os
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt

# Importing from parent directory
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import dynamic_tsne
import numpy as np

if __name__ == "__main__":
    data = load_iris()
    X = data.data
    labels = data.target

    # Embedding function requires unique arrays.
    # Well, embedding fuction can protect from it, but still we can get some confusion in mean square error, if it
    # "chooses" different sample
    temp = np.ascontiguousarray(X).view(np.dtype((np.void, X.dtype.itemsize * X.shape[1])))
    _, un_idx = np.unique(temp, return_index=True)
    X = X[un_idx, :]
    labels = labels[un_idx]

    dTSNE = dynamic_tsne.DynamicTSNE(perplexity=20)
    # Small dataset. Iterations are very fast, we can afford more
    y = dTSNE.fit(X, verbose=2, optimizer_kwargs={'momentum': 0.8, 'n_iter' : 3000}, random_seed=1)
    embedder_lagrange_norm = dTSNE.generate_embedding_function(embedding_function_type='makeshift-lagrange-norm')
    embedder_weighted = dTSNE.generate_embedding_function(embedding_function_type='weighted-inverse-distance')
    embedder_linear = dTSNE.generate_embedding_function(embedding_function_type='linear')
    embedder_dim_linear = dTSNE.generate_embedding_function(embedding_function_type='linear-per-dimension')
    embedder_lagrange = dTSNE.generate_embedding_function(embedding_function_type='lagrange-per-dimension')
    embedder_rbf = dTSNE.generate_embedding_function(embedding_function_type='rbf')
    start_index = 0
    end_index = 100
    steps = 100
    Xtransition = [X[start_index, :] + (X[end_index,:] - X[start_index, :])*i/steps for i in range(steps+1)]
    y_lagrange_norm = embedder_lagrange_norm(Xtransition, verbose=2)
    y_lagrange_per_dimension = embedder_lagrange(Xtransition, verbose=2)
    y_linear_per_dimension = embedder_dim_linear(Xtransition, verbose=2)
    y_weighted = embedder_weighted(Xtransition, verbose=2)
    y_linear = embedder_linear(Xtransition, verbose=2)
    y_rbf = embedder_rbf(Xtransition, verbose=2)
    color_list = ['blue', 'orange', 'green']

    plt.gcf().set_size_inches(10, 10)
    legend_list = list()
    legend_list.append("Lagrange-like norm polynomial)")
    legend_list.append("Sum of 1D lagrange interpolations")
    legend_list.append("Sum of 1D linear interpolations")
    legend_list.append("Weighted by inverse distances")
    legend_list.append("Multidimensional linear")
    legend_list.append("RBF (multiquadratic)")
    for l in set(sorted(labels)):
        plt.scatter(y[labels == l, 0], y[labels == l, 1], c=color_list[l])
        legend_list.append(str(data.target_names[l]))
    plt.plot(y_lagrange_norm[:, 0], y_lagrange_norm[:, 1], color='black', marker='x')
    plt.plot(y_lagrange_per_dimension[:, 0], y_lagrange_per_dimension[:, 1], color='red', marker='x')
    plt.plot(y_linear_per_dimension[:, 0], y_linear_per_dimension[:, 1], color='blue', marker='x')
    plt.plot(y_weighted[:, 0], y_weighted[:, 1], color='cyan', marker='x')
    plt.plot(y_linear[:, 0], y_linear[:, 1], color='grey', marker='x')
    plt.plot(y_rbf[:, 0], y_rbf[:, 1], color='green', marker='x')
    plt.legend(legend_list)
    plt.xlim([np.min(y[:, 0])-20, np.max(y[:, 0])+20])
    plt.ylim([np.min(y[:, 1])-20, np.max(y[:, 1])+20])
    plt.title("Smooth transitioning of samples "+str(start_index) + " to " + str(end_index))
    plt.show()


#!/usr/bin/env python3

import argparse
import logging
from time import sleep
import json

from market_data import MarketDataListener
from trading_client import TradingClientFactory
from candle import CandleManager
from tick import TickManager
from collections import OrderedDict
import os
from os import path
from utils import get_workdir

def main(args):
    workdir = get_workdir()
    os.makedirs(workdir, exist_ok=True)

    logging.basicConfig(level=logging.DEBUG, filename=path.join(workdir, 'log.txt'), format='%(asctime)s - %(levelname)s - %(message)s')

    with open(args.portfolio_file, 'r') as f:
        portfolio = json.load(f)

    client_factory = TradingClientFactory()

    candle_manager_dict = {} #Contains mapping from symbol to its candle manager to prevent duplication of candle managers for clients of same symbol
    symbol_list = []
    clients = []

    for client in portfolio:
        symbol = client['symbol']
        if(symbol not in symbol_list):
            symbol_list.append(symbol)
        trading_client = client_factory.load(client['Name'], **OrderedDict(client))
        clients.append(trading_client)

        if(symbol not in candle_manager_dict):
            candle_manager = CandleManager(symbol)
            candle_manager_dict[symbol] = candle_manager
        else:
            candle_manager = candle_manager_dict[symbol]
        candle_manager.register_trading_client(trading_client)

    market_data_listener = MarketDataListener(symbol_list, args.api_key, args.request_token, args.api_secret)
    tick_manager = TickManager(market_data_listener.instrument_token_to_symbol)

    for client in clients:
        client.order_manager.initialize_kite(market_data_listener.kite)

    for symbol, candle_manager in candle_manager_dict.items():
        candle_manager.create_candle_generators()
        tick_manager.register_candle_manager(candle_manager)

    market_data_listener.connect()
    while True:
        market_data_listener.kws.on_ticks = tick_manager.on_ticks

def get_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('--portfolio_file',help='give the json file having the portfolio to be traded on', required=True)
    parser.add_argument('--api_key', help='API Key, contact developer', required=True)
    parser.add_argument('--api_secret', help='API Secret, contact developer', required=True)
    parser.add_argument('--request_token', help='API request_token, login at https://kite.trade/connect/login?api_key={api_key}&v=3', required=True)
    return parser.parse_args()

if __name__ == "__main__":
    main(get_args())


import torch
import numpy as np
from functions import plot_results

def training_loop(num_epochs, model, trainloader, valloader, optimizer, save_path):

    val_loss_n = [100000, 99999]
    train_loss_n = [100000, 99999]

    for epoch in range(num_epochs):

        print(f'Epoch {epoch+1}/{num_epochs}')
        print('-' * 10)

        train_loss = []
        val_loss = []

        model.train()
        for inputs, targets in trainloader:

            inputs = [input.permute(2, 0, 1) for input in inputs] #H W C to C H W
            outputs = model(inputs, targets)
            losses = sum(loss for loss in outputs.values())
            loss_value = losses.item()

            optimizer.zero_grad()
            losses.backward()
            optimizer.step()

            train_loss.append(loss_value)

        with torch.no_grad():
            for inputs, targets in valloader:
                inputs = [input.permute(2, 0, 1) for input in inputs]
                outputs = model(inputs, targets)
                losses = sum(loss for loss in outputs.values())
                loss_value = losses.item()

                val_loss.append(loss_value)

            train_loss = np.sum(train_loss)/len(train_loss)
            val_loss = np.sum(val_loss)/len(val_loss)

            if val_loss < np.min(val_loss_n):
                torch.save({
                        'epoch': epoch,
                        'model_state_dict': model.state_dict(),
                        'optimizer_state_dict': optimizer.state_dict(),
                        'loss': val_loss,
                        }, save_path)
                print('\nmodel saved!\n')

            train_loss_n.append(train_loss)
            val_loss_n.append(val_loss)

        print(f'Training loss: {train_loss:.2f}, Validation loss: {val_loss:.2f}')

    return model

def testing_loop(model, testloader, threshold):

    model.eval()

    for inputs, targets in testloader:
        images = []
        for img in inputs:
            images.append(img.cpu().detach().numpy())

        inputs = [input.permute(2, 0, 1) for input in inputs]

        outputs = model(inputs)

        plot_results(images, outputs, targets, threshold)
        break


from django.urls import path
from . import views, auth
urlpatterns = [
    path('', views.index),
    path('administrador/', views.administrador),
    path('registro/', auth.registro),
    path('login/', auth.login),
    path('logout/', auth.logout),
    path('mensaje', views.nuevo_mensaje),
    path('comentario/<int:mensaje_id>', views.nuevo_comentario)
]


import json
import requests
from common import get_token

BASE = "<>"
PASS = "<>"
USER = "<>"
COLLECTION = "<>"

def headers():
    return {"X-Metabase-Session": get_token(BASE, USER, PASS)}

def get_collection(old):
    collections = requests.get(f"{BASE}/api/collection/", headers=headers()).json()
    collections = [c for c in collections if c["name"] == old["name"]]
    if collections:
        return collections[0]["id"]
    else:
        return requests.post(
            f"{BASE}/api/collection/", headers=headers(), json=old
        ).json()["id"]

def delete_model(id, model):
    return requests.delete(
        f"{BASE}/api/{model}/{id}",
        headers=headers(),
    ).json()

def clear_collection(id):
    items = requests.get(
        f"{BASE}/api/collection/{id}/items",
        headers=headers(),
    ).json()

    for item in items["data"]:
        try:
            delete_model(item["id"], item["model"])
        except:
            pass

def update_collection(id, c):
    clear_collection(id)
    out = requests.put(
        f"{BASE}/api/collection/{id}",
        headers=headers(),
        json=c,
    ).json()
    return out["id"]

def create_card(c):
    out = requests.post(
        f"{BASE}/api/card/", headers=headers(), json=c
    ).json()
    return out["id"]

def create_dashboard(c, cache):
    id = requests.post(
        f"{BASE}/api/dashboard/", headers=headers(), json=c
    ).json()["id"]
    for card in c["ordered_cards"]:
        card["cardId"] = cache["card__" + str(card["card_id"])]
        out = requests.post(
            f"{BASE}/api/dashboard/{id}/cards",
            headers=headers(),
            json=card,
        ).text
        print(out)
    return out

def get_databases():
    items = requests.get(
        f"{BASE}/api/database?include=tables", headers=headers()
    ).json()
    out = {}
    for db in items["data"]:
        out[db["name"]] = {
            "tables": dict((t["name"], t["id"]) for t in db["tables"]),
            "id": db["id"],
        }
    return out

def map_table(src_dbs, dst_dbs, db, table):
    src_db = src_dbs[str(db)]
    dst_db = dst_dbs[src_db["name"]]

    if table is not None:
        src_table = src_db["tables"][str(table)]
        dst_table = dst_db["tables"][src_table]
    else:
        dst_table = None

    return dst_db["id"], dst_table

def process_and_upload_card(c, src_dbs, dst_dbs, cards, cache={}):
    print(c['id'])
    if f"card__{c['id']}" in cache:
        return

    def find_card(id):
        return [c for c in cards if f"card__{c['id']}" == id][0]

    def table_mapper(table):
        if isinstance(table, str):
            process_and_upload_card(find_card(table), src_dbs, dst_dbs, cards, cache)
            return "card__" + str(cache[table])
        else:
            return map_table(src_dbs, dst_dbs, src_db, table)[1]

    c["collection_id"] = id
    src_db = c["database_id"]
    c["database_id"] = map_table(src_dbs, dst_dbs, src_db, c["table_id"])[0]
    dataset_query = c["dataset_query"]
    dataset_query["database"] = c["database_id"]
    if "query" in dataset_query:
        query = dataset_query["query"]
        if "source-table" in query:
            query["source-table"] = table_mapper(query["source-table"])
        if "source-query" in query and "source-table" in query["source-query"]:
            query["source-query"]["source-table"] = table_mapper(
                query["source-query"]["source-table"]
            )
        for join in query.get("joins", []):
            join["source-table"] = table_mapper(join["source-table"])
    cache[f"card__{c['id']}"] = create_card(c)

if __name__ == "__main__":
    dbs = get_databases()
    data = json.load(open(f"{COLLECTION}.json"))
    src_dbs = data["db"]
    id = get_collection(data["collection"])
    update_collection(id, data["collection"])
    cards, dashboards = data["cards"], data["dashboards"]

    cache = {}
    for c in cards:
        process_and_upload_card(c, src_dbs, dbs, cards, cache)

    for c in dashboards:
        for card in c['ordered_cards']:
            process_and_upload_card(card['card'], src_dbs, dbs, cards, cache)
        c["collection_id"] = id
        create_dashboard(c, cache)


from ..pages.product_page import ProductPage
from ..pages.main_page import MainPage
from ..pages.login_page import LoginPage
from ..pages.basket_page import BasketPage
from ..pages.locators import ProductPageLocators
from pytest import mark, param, fixture
from time import sleep, time

PROD_PAGE_LINK = "http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/"

class TestUserAddToBasketFromProductPage:

    @fixture(scope="function", autouse=True)
    def setup(self, browser):
        page = ProductPage(browser, PROD_PAGE_LINK)
        page.open()
        page.go_to_login_page()
        login_page = LoginPage(browser, browser.current_url)
        login_page.register_new_user(str(time()) + "@fakemail.org", "VerySecurePassword")
        login_page.should_be_authorized_user()

    def test_user_cant_see_success_message(self, browser):
        page = ProductPage(browser, PROD_PAGE_LINK)
        page.open()
        page.should_not_be_success_message()

    @mark.need_review
    def test_user_can_add_product_to_basket(self, browser):
        page = MainPage(browser, PROD_PAGE_LINK)
        page.open()
        prod_page = ProductPage(browser, browser.current_url)
        product, price = prod_page.should_be_product_page()
        prod_page.put_to_basket()
        prod_page.shoud_be_notified(product, price)

@mark.need_review
@mark.parametrize("promo", [
    *range(0, 7),
    param(7, marks=mark.xfail(reason="Bug that is not gonna be fixed")),
    8, 9
    ])
def test_guest_can_add_product_to_basket(browser, promo):
    link = PROD_PAGE_LINK + "?promo=offer{promo}"
    page = MainPage(browser, link)
    page.open()
    prod_page = ProductPage(browser, browser.current_url)
    product, price = prod_page.should_be_product_page()
    prod_page.put_to_basket()
    page.solve_quiz_and_get_code()
    prod_page.shoud_be_notified(product, price)

def test_guest_cant_see_success_message_after_adding_product_to_basket(browser):
    page = MainPage(browser, PROD_PAGE_LINK)
    page.open()
    prod_page = ProductPage(browser, browser.current_url)
    prod_page.put_to_basket()
    assert page.is_not_element_present(*ProductPageLocators.ALERT_SUCCESS)

def test_message_disappeared_after_adding_product_to_basket(browser):
    page = MainPage(browser, PROD_PAGE_LINK)
    page.open()
    prod_page = ProductPage(browser, browser.current_url)
    prod_page.put_to_basket()
    assert page.is_disappeared(*ProductPageLocators.ALERT_SUCCESS)

def test_guest_should_see_login_link_on_product_page(browser):
    link = "http://selenium1py.pythonanywhere.com/en-gb/catalogue/the-city-and-the-stars_95/"
    page = ProductPage(browser, link)
    page.open()
    page.should_be_login_link()

@mark.need_review
def test_guest_can_go_to_login_page_from_product_page(browser):
    link = "http://selenium1py.pythonanywhere.com/en-gb/catalogue/the-city-and-the-stars_95/"
    page = ProductPage(browser, link)
    page.open()
    page.go_to_login_page()
    login_page = LoginPage(browser, browser.current_url)
    login_page.should_be_login_page()

@mark.need_review
def test_guest_cant_see_product_in_basket_opened_from_product_page(browser):
    link = "http://selenium1py.pythonanywhere.com/en-gb/catalogue/the-city-and-the-stars_95/"
    page = ProductPage(browser, link)
    page.open()
    page.view_cart()
    basket = BasketPage(browser, browser.current_url)
    basket.should_be_empty_cart()
    basket.should_be_empty_cart_message()


import openai as ai
completion = ai.Completion()

def chatbot_interface(description, history, sentence, api_key):
    ai.api_key = api_key
    chat_log = description + "\n" + history + "\n"
    prompt = f"{chat_log}Human: {sentence}\nAI:"
    response = completion.create(
        model="text-davinci-002",
        prompt=prompt,
        temperature=0.85,
        max_tokens=100,
        top_p=1,
        frequency_penalty=0,
        presence_penalty=0.6,
        stop=[" Human:", " AI:"])
    res = response.choices[0].text.strip('\n')

    return res

if __name__ == "__main__":
    history = ""

    #description = "This is a conversation with an AI assistant. This assistant is very kind, helpful and humorous."
    description = "your-description"

    #user_sentences = ["Hi, do you know the Avengers?", "What's your favourite character of the Avengers?"]
    user_sentences = "your-sentences"

    api_key = "your-api-key"

    #an example of usage, the user_sentences can be obtained from other interface(e.g. front-end of a softerware, user input)
    #while fit your conditions
    for i in range(2):
        res = chatbot_interface(description, history, user_sentences[i], api_key)
        print(f"user: {user_sentences[i]}\nchatbot: {res}")
        user_history = "Human: " + user_sentences[i] + "\n"
        chatbot_history = "AI: " + res
        history = history + user_history + chatbot_history


import os
import tempfile

import numpy as np
import numpy.testing as npt
import pytest
from pygt3x.reader import FileReader

from paat import io, preprocessing

@pytest.fixture
def unscaled_data(file_path):
    return io.read_gt3x(file_path, rescale=False, pandas=True)

def test_loading_data(file_path, load_gt3x_file):
    data, _ = load_gt3x_file
    _, acceleration, _ = io.read_gt3x(file_path, rescale=True, pandas=False)

    assert np.array_equal(acceleration, data[["Y", "X", "Z"]].values)

@pytest.mark.slow
def test_against_actigraph_implementation(file_path, unscaled_data):
    with FileReader(file_path) as reader:
        ref = reader.to_pandas()

    npt.assert_almost_equal(unscaled_data[["X", "Y", "Z"]].values, ref[["X", "Y", "Z"]].values)
    #assert np.allclose(data[["X", "Y", "Z"]].values, ref[["X", "Y", "Z"]].values)

def test_exceptions():
    with pytest.raises(NotImplementedError) as e_info:
        time_data = np.arange(10)
        hz = 33
        io._create_time_array(time_data, hz)
        assert e_info

    with pytest.raises(NotImplementedError) as e_info:
        start = np.asarray(np.datetime64('today'), dtype='datetime64[ms]')
        n_samples = 330
        hz = 33
        io._create_time_vector(start, n_samples, hz)
        assert e_info


from inspect import classify_class_attrs
import numpy
import cv2
import customtkinter
import pickle
from PIL import ImageTk, Image
import pandas
import mediapipe
import tkinter
from sample_landmarks import landmarks

app = tkinter.Tk()
customtkinter.set_appearance_mode("dark")
app.title("Computer Vision Workout App")
app.geometry("480x700")

def reset():
    global reps
    reps = 0

#obtains the picture of the motion done on the camera and analyzes it via pose estimation
def detect_motions():
    global prob
    global current_motion_point
    global reps
    global class_current

    r, f = video_capture.read()

    captured_image = cv2.cvtColor(f, cv2.COLOR_BGR2RGB)

    process_image = pose_estimation.process(captured_image)

    draw_lines.draw_landmarks(captured_image, process_image.pose_landmarks, get_estimation.POSE_CONNECTIONS, draw_lines.DrawingSpec(circle_radius = 2, color = (0,0,255), thickness = 2), draw_lines.DrawingSpec(circle_radius = 2, color = (0,255,0), thickness = 2))

    try:
        landmark_row = numpy.array([[landmark.x, landmark.y, landmark.z, landmark.visibility] for landmark in process_image.pose_landmarks.landmark]).flatten().tolist()
        landmark_row_col = pandas.DataFrame([landmark_row], columns = landmarks)
        prob = train_model.predict_proba(landmark_row_col)[0]
        class_current = train_model.predict(landmark_row_col)[0]
        if(prob[prob.argmax()] > 0.7 and class_current == "up" and current_motion_point == "down"):
            current_motion_point = "up"
            reps = reps + 1
        elif(prob[prob.argmax()] > 0.7 and class_current == "down"):
            current_motion_point = "down"
    except Exception as error:
        pass

    slice_img = captured_image[:, :460, :] #slice the image
    array_img = Image.fromarray(slice_img) #convert it into an array
    tk_img = ImageTk.PhotoImage(array_img) #convert from array to tk image
    window_l.tk_img = tk_img
    window_l.configure(image = tk_img)
    window_l.after(10, detect_motions)
    probability_b.configure(text = prob[prob.argmax()])
    class_b.configure(text = current_motion_point)
    counter_b.configure(text = reps)

probability_l = customtkinter.CTkLabel(app, text_font = ("Arial", 18), text_color = "black", padx = 10, width = 120, height = 40)
probability_l.configure(text = "Odds")
probability_l.place(x = 300, y = 1)
probability_b = customtkinter.CTkLabel(app, text_font = ("Arial", 18), text_color = "black", fg_color = "red", width = 120, height = 40)
#probability_b.configure(text = "0")
probability_b.place(x = 300, y = 41)

class_l = customtkinter.CTkLabel(app, text_font = ("Arial", 18), text_color = "black", padx = 10, width = 120, height = 40)
class_l.configure(text = "Motion")
class_l.place(x = 10, y = 1)
class_b = customtkinter.CTkLabel(app, text_font = ("Arial", 18), text_color = "black", fg_color = "red", width = 120, height = 40)
class_b.configure(text = "0")
class_b.place(x = 10, y = 41)

counter_l = customtkinter.CTkLabel(app, text_font = ("Arial", 18), text_color = "black", padx = 10, width = 120, height = 40)
counter_l.configure(text = "Reps")
counter_l.place(x = 160, y = 1)
counter_b = customtkinter.CTkLabel(app, text_font = ("Arial", 18), text_color = "black", fg_color = "red", width = 120, height = 40)
counter_b.configure(text = "0")
counter_b.place(x = 160, y = 41)

reset_button = customtkinter.CTkButton(app, text_font = ("Arial", 18), text_color = "black", command = reset, fg_color = "red", text = "Reset Reps", width = 120, height = 40)
reset_button.place(x = 10, y = 600)

window = tkinter.Frame(width = 480, height = 480)
window.place(x = 10, y = 90)
window_l = tkinter.Label(window)
window_l.place(x = 0, y = 0)

get_estimation = mediapipe.solutions.pose
pose_estimation = get_estimation.Pose(min_detection_confidence = 0.5, min_tracking_confidence = 0.5)

draw_lines = mediapipe.solutions.drawing_utils

with open('deadlift_training_data.pkl', 'rb') as data:
    train_model = pickle.load(data)

prob = numpy.array([0,0])
current_motion_point = ''
reps = 0
class_current = ''
video_capture = cv2.VideoCapture(0)
detect_motions()

app.mainloop()


"""
Created on Sat Mar  7 08:48:27 2020

@author: SamKoebrich
"""

import os
from pathlib import Path

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~ GENERAL SETTINGS ~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

# --- Number of generators for training set ---
#   - most downloads are cached, so if you set a higher number,
#     and then a lower, you don't lose data.
RUN_PRE_EE = True
FETCH_S3 = True
RUN_BAYES_OPT = True
N_GENERATORS = None
MAX_YEAR = 2019
SCHEMA = 'production'

# --- Multiprocessing settings ---
MULTIPROCESSING = True
WORKERS = 12
THREADS = 6 #ThreadPoolExecutor is failing for Earth Engine queries, so this is still using ProcessPool

# --- Bool for detailed output ---
VERBOSE = False

# --- Frequency of observations (i.e. 'D' for daily, 'W', for weekly, 'M' for monthly, 'A' for annual) ---
TS_FREQUENCY = '1W'
if TS_FREQUENCY in ['1W']:
    TS_DIVISOR = 52
elif TS_FREQUENCY in ['MS']:
    TS_DIVISOR = 12
elif TS_FREQUENCY in ['D', '1D']:
    TS_DIVISOR = 365
elif TS_FREQUENCY in ['A','AS']:
    TS_DIVISOR = 1
elif TS_FREQUENCY == '3D':
    TS_DIVISOR = int(365 / 3)
elif TS_FREQUENCY == '2D':
    TS_DIVISOR = int(365 / 2)
else:
    raise NotImplementedError(f'Please write a wrapper for {TS_FREQUENCY}!')

TRAIN_COUNTRIES = ['United States of America']
PREDICT_COUNTRIES = ['WORLD'] #['Colombia', 'Venezuela', 'Costa Rica', 'Guatemala', 'Jamaica', 'Puerto Rico']

PREDICT_START_DATE = '01-01-2019'
PREDICT_END_DATE = '12-31-2019'

CEMS_MEASUREMENT_FLAGS = [] #blank for include everything

FETCH_SENTINEL_FROM = 'S3'

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~ EARTH ENGINE SETTINGS ~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

# --- Sources ---
EARTHENGINE_DBS = [
    "CIESIN/GPWv411/GPW_Population_Count",
    "ECMWF/ERA5/DAILY"
]

# --- API Query settings ---
EE_TIMEOUT = 120 #forced timeout, overriding exponential backoff before calling a API query nans
RETRY_EE_NANS = False #after loading cache, retry queries that returned nans in last call

# --- Scale (in meters) to query ---
BUFFERS = [20000] #1e2, 1e4

# --- Hour to grab after --- (i.e. don't consider an observation unless it is after this hour)
LEFT_WINDOW_HOUR = 20

# --- Degrees to match GPPD and EIA dataframes ---
DEGREES_DISTANCE_MATCH = 0.005

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~ L3 SETTINGS ~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

RAW_S3_DIR = os.path.join(str(Path.home()),'HDD','tycho_raw')

S3_DBS = [
        'COGT/OFFL/L2__SO2___/',
        # 'COGT/OFFL/L2__O3____/', #available 2019-04 on
        'COGT/OFFL/L2__NO2___/',
        'COGT/OFFL/L2__HCHO__/',
        'COGT/OFFL/L2__CH4___/',
        'COGT/OFFL/L2__CO____/',
        # 'COGT/OFFL/L2__CLOUD_/' #available 2019-04 on
        'COGT/OFFL/L2__AER_AI/'
        ]

S3_BUCKET = 'meeo-s5p'

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~ SANITIZE/SPLIT SETTINGS ~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

# --- US y (target) variables ---
CEMS_Y_COLS = [ #LEAKAGE WARNING! Removing something from this list will cause it to persist in the X sets
    'gross_load_mw',
    'so2_lbs',
    'nox_lbs',
    'operational_time',
    'co2_lbs'
]

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~ ML SETTINGS ~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
HOW_TO_SPLIT = 0.1 #test frac
TRAIN_MODEL = 'bayes-xgb'
PREDICT_MODEL = 'bayes-xgb'
ML_Y_COLS = ['gross_load_mw','so2_lbs','nox_lbs','co2_lbs']
CV_FOLDS = 3

RANDOMSEARCH_ITER = 50

# --- Params for Bayes training ---
BAYES_N_ITER = 50
BAYES_INIT_POINTS = 100
BAYES_ACQ = 'ucb'

# --- Params for TPOT Training ---
TPOT_GENERATIONS = 100
TPOT_POPULATION_SIZE = 100
TPOT_TIMEOUT_MINS = 60*24
# TPOT_CONFIG_DICT = tpot_configs.lgbm_config_dict


import pytest
from django.urls import reverse

from cars.models import Order, OrderLine

@pytest.mark.django_db
def test_delete(user_client, color_factory, brand_factory, car_model_factory, order_line_factory, order_factory):
    color = color_factory()
    brand = brand_factory()
    model = car_model_factory(brand=brand)

    order = order_factory()
    order_line_factory(order=order, model=model, color=color)

    response = user_client.delete(reverse('orders-detail', args=[order.pk]))

    assert response.status_code == 204
    assert not Order.objects.exists()
    assert not OrderLine.objects.exists()


import weakref
import importlib

class Component(object):
    __slots__ = [
        '_entity',
        'typeid',
        'synchronize',
        '_is_unique',
        '_import_string',
    ]

    def __init__(self):
        self._is_unique = False
        self.synchronize = False
        self._import_string = self.__class__.__module__ + '.' + self.__class__.__name__

    def __del__(self):
        #print("__del__", self)
        pass

    def cleanup(self):
        pass

    @property
    def entity(self):
        return self._entity()

    @property
    def is_unique(self):
        return self._is_unique

    def serialize(self):
        return {'import_string': self._import_string}

class UniqueComponent(Component):
    __slots__ = []

    def __init__(self):
        super().__init__()
        self._is_unique = True

class Entity(object):
    __slots__ = [
        '_components',
        '_new_components',
        '__weakref__',
        'guid',
        'space',
        'netid',
    ]

    def __init__(self, space):
        self._components = {}
        self._new_components = {}
        self.guid = None
        self.space = space
        self.netid = 0

    def __del__(self):
        for k, v in self._components.items():
            for i in v:
                i.cleanup()
        self._components.clear()

        for k, v in self._new_components.items():
            for i in v:
                i.cleanup()
        self._new_components.clear()
        #print("__del__", self)

    def add_component(self, component):
        typeid = component.typeid

        enforce_unique = component.is_unique
        if not enforce_unique:
            try:
                enforce_unique = bool([i for i in self.get_components(typeid) if i.is_unique])
            except KeyError:
                enforce_unique = False

        if enforce_unique and self.has_component(typeid):
            raise RuntimeError('Entity already has component with typeid of {}'.format(typeid))
        component._entity = weakref.ref(self)

        if typeid in self._new_components:
            self._new_components[typeid].append(component)
        else:
            self._new_components[typeid] = [component]

    def remove_component(self, component):
        if component.typeid in self._components:
            d = self._components
            clist = self._components[component.typeid]
        elif component.typeid in self._new_components:
            d = self._new_components
            clist = self._new_components[component.typeid]
        else:
            raise KeyError('Enity has no component with typeid of {}'.format(component.typeid))

        component.cleanup()
        clist.remove(component)
        if not clist:
            del d[component.typeid]

    def get_component(self, typeid):
        if len(self.get_components(typeid)) > 1:
            raise RuntimeError('Entity has more than one component with typeid of {}'.format(typeid))

        return self.get_components(typeid)[0]

    def get_components(self, typeid):
        if typeid in self._components:
            return self._components[typeid]
        elif typeid in self._new_components:
            return self._new_components[typeid]
        else:
            raise KeyError('Enity has no component with typeid of {}'.format(typeid))

    def has_component(self, typeid):
        return typeid in self._components or typeid in self._new_components

    def serialize(self):
        d = {}
        for typeid, clist in self._components.items():
            d[typeid] = []
            for component in clist:
                if component.synchronize:
                    d[typeid].append(component.serialize())
            if not d[typeid]:
                del d[typeid]

        return d

    def update(self, netid, d):
        self.netid = netid
        #print(self.netid, d)
        for typeid, clist in d.items():
            for i, cdata in enumerate(clist):
                mod_parts = cdata['import_string'].split('.')
                cmod = '.'.join(mod_parts[:-1])
                cclass = mod_parts[-1]

                try:
                    component = self.get_components(typeid)[i]
                except (IndexError, KeyError):
                    mod = importlib.import_module(cmod)
                    component = getattr(mod, cclass)()
                    self.add_component(component)

                component.update(cdata)

class System(object):
    __slots__ = [
        'component_types',
    ]

    def init_components(self, dt, entities):
        pass

    def update(self, dt, entities):
        pass

class DuplicateSystemException(Exception):
    pass

class ECSManager(object):
    def __init__(self):
        self.entities = []
        self.systems = {}
        self.next_entity_guid = 0
        self.space = Entity(None)
        self.removed_entities = set()

    def create_entity(self):
        # TODO allow for multiple spaces
        if self.space is None:
            raise RuntimeError("ECSManager.space is None")
        entity = Entity(self.space)
        self._add_entity(entity)

        return entity

    def _add_entity(self, entity):
        entity.guid = self.next_entity_guid
        self.next_entity_guid += 1
        self.entities.append(entity)

    def remove_entity(self, entity):
        if entity.netid != 0:
            self.removed_entities.add(entity.netid)
        self.entities.remove(entity)

    def add_system(self, system):
        name = system.__class__.__name__
        if name in self.systems:
            raise DuplicateSystemException("{} has already been added.".format(name))
        self.systems[name] = system

    def has_system(self, system_str):
        return system_str in self.systems

    def get_system(self, system_str):
        if system_str not in self.systems:
            raise KeyError('No system found with the name of {}'.format(system_str))
        return self.systems[system_str]

    def remove_system(self, system_str):
        if system_str not in self.systems:
            raise KeyError('No system found with the name of {}'.format(system_str))
        del self.systems[system_str]

    def remove_space(self):
        # TODO allow for multiple spaces
        for entity in self.entities[:]:
            if entity.space == self.space:
                self.entities.remove(entity)

        self.space = None

    def _get_components_by_type(self, component_list, component_types):
        components = {k: [] for k in component_types}
        for entity in self.entities:
            for typeid in component_types:
                components[typeid] += getattr(entity, component_list).get(typeid, [])

        return components

    def update(self, dt):
        entities = self.entities[:]

        for system in self.systems.values():
            system.init_components(dt, self._get_components_by_type('_new_components', system.component_types))

        for entity in entities:
            for typeid, clist in entity._new_components.items():
                if typeid in entity._components:
                    entity._components[typeid].extend(clist)
                else:
                    entity._components[typeid] = clist[:]
            entity._new_components.clear()

        for system in self.systems.values():
            system.update(dt, self._get_components_by_type('_components', system.component_types))


import sys

sys.path.append("src")
import numpy.testing as npt
from geometry.smooth import surfaces
import numpy as np
from geometry.discrete.surfaces import TriangleMesh
import math
from thirdparty.octasphere import octasphere, icosphere
import open3d

sphere = TriangleMesh.from_o3d(open3d.geometry.TriangleMesh.create_sphere())
torus = TriangleMesh.from_o3d(open3d.geometry.TriangleMesh.create_torus())

def test_gauss_bonnet2():
    """
    assert the relationship between gaussian
    curvature and topology
    """
    for mesh in [sphere, torus]:
        E = mesh.euler_characteristic()
        G = mesh.total_gaussian_curvature()

        Ge = E * 2 * math.pi

        np.testing.assert_almost_equal(G, E * 2 * math.pi, 5)

def test_gauss_bonnet1():
    """ Test the theorum that total guassian curvature
    of a closed surface equa ls 2*pi*euler characteristic
    """
    SPHERE_EULER_CHARACTERISTIC = 2
    TORUS_EULER_CHARACTERISTIC = 0

    np.testing.assert_almost_equal(
        sphere.euler_characteristic(),
        SPHERE_EULER_CHARACTERISTIC,
        decimal=5
    )
    np.testing.assert_almost_equal(
        torus.euler_characteristic(),
        TORUS_EULER_CHARACTERISTIC,
        decimal=5
    )

def test_discrete_smooth_total_gaussian_curvature():
    total_smooth   = surfaces.Sphere(2).total_gaussian_curvature(100)
    total_discrete = sphere.total_gaussian_curvature()

    np.testing.assert_almost_equal(total_smooth, total_discrete, decimal=1)

    # smooth_sphere = surfaces.Sphere()
    # discrete_sphere = TriangleMesh.from_surface(smooth_sphere, 100)

    # uv = smooth_sphere.coordinates(100)

    # smooth_curvatures = smooth_sphere.gaussian_curvature(uv)
    # discrete_cuvatures = discrete_sphere.vertex_angle_defects()
    # import pdb; pdb.set_trace()

    # surface = Sphere(2)
    # total = surface.total_gaussian_curvature(500)
    # np.testing.assert_almost_equal(total, 2 * math.pi * SPHERE_EULER_CHARACTERISTIC, decimal=1)

    # surface = EllipsoidLatLon()
    # total = surface.total_gaussian_curvature(500)
    # np.testing.assert_almost_equal(total, 2 * math.pi * SPHERE_EULER_CHARACTERISTIC, decimal=1)

    # surface = Torus()
    # total = surface.total_gaussian_curvature(500)
    # np.testing.assert_almost_equal(total, 2 * math.pi * TORUS_EULER_CHARACTERISTIC, decimal=1)


import os
import torchaudio as ta
from Demucs import *
import scipy.io.wavfile
import numpy as np

def create_noise_file(audio_clean,noise_path,output):
    noise, _ = ta.load(str(noise_path), normalize=True)
    audio_length = audio_clean.shape[-1]
    noise_length = noise.shape[-1]
    if noise_length > audio_length:
        noise = noise[..., 0: audio_length]
        clean = np.transpose(audio_clean.detach().cpu().numpy(), (1, 0))
        scipy.io.wavfile.write(output+"_original.wav", samplerate, clean)
    elif noise_length < audio_length:
        audio_clean = audio_clean[..., 0: noise_length]
        clean = np.transpose(audio_clean.detach().cpu().numpy(), (1, 0))
        scipy.io.wavfile.write(output+"_original.wav", samplerate, clean)
        #noise = torch.cat([noise, torch.zeros((noise.shape[0], audio_length - noise_length))], dim=-1)

    return audio_clean + noise_power*noise

def denoise(audio_list,noise_list,output_path):
    for i,audio_path in enumerate(audio_list):
        output = output_path + "/" + str(i)
        wavS, _ = ta.load(str(audio_path), normalize=True)
        if createnoise == 1:
            wavS = create_noise_file(wavS,noise_list[i],output)
            noised = np.transpose(wavS.detach().cpu().numpy(), (1, 0))
            scipy.io.wavfile.write(output+"_noised.wav", samplerate, noised)
        else:
            noised = np.transpose(wavS.detach().cpu().numpy(), (1, 0))
            scipy.io.wavfile.write(output+"_noised.wav", samplerate, noised)

        lenofwave = wavS.shape[1]
        lenofseg = samplerate*segemntlength
        steps = int(lenofwave/lenofseg)
        rest = lenofwave - steps * lenofseg
        listofsplits = []
        for i in range(steps):
            listofsplits.append(wavS[0][i*lenofseg:(i+1)*lenofseg])
        restarr = torch.cat([wavS[0][steps*lenofseg:], torch.zeros(lenofseg - rest)], dim=-1)
        listofsplits.append(restarr)
        stacked = torch.stack(listofsplits)
        denoised = model(stacked.view([-1,1,lenofseg]).to(device))
        denoised = denoised.view([1,1,-1])
        denoised = denoised[0][0][:-int(lenofseg - rest)]
        denoised = np.transpose(denoised.view([1,-1]).detach().cpu().numpy(), (1, 0))
        scipy.io.wavfile.write(output+"_denoised.wav", samplerate, denoised)

if __name__ == "__main__":
    audio_list = ["D:/LibriSpeech/cleandataset/38/4.flac",
                  "D:/LibriSpeech/cleandataset/302/0.flac",
                  "D:/LibriSpeech/cleandataset/369/1.flac",
                  "D:/LibriSpeech/cleandataset/696/1.flac",]
    noise_list = ["D:/musan/musan/noise/free-sound/noise-free-sound-0006.wav",
                  "D:/musan/musan/noise/free-sound/noise-free-sound-0147.wav",
                  "D:/musan/musan/noise/free-sound/noise-free-sound-0155.wav",
                  "D:/musan/musan/noise/free-sound/noise-free-sound-0654.wav",]
    createnoise = 1
    model_path = {"HDemucs_mrstft": "./current_models_Sweeprun_mrstft_HDemucs/G_5_004000.pth",
                  "Demucs_mrstft": "./current_models_Sweeprun_mrstft_Demucs/G_5_004000.pth",
                  "HDemucs_l1": "./current_models_Sweeprun_l1_HDemucs/G_5_004000.pth",
                  "Demucs_l1": "./current_models_Sweeprun_l1_Demucs/G_5_004000.pth",
                  "HDemucs_ranstft": "./current_models_Sweeprun_ranstft_HDemucs/G_5_004000.pth",
                  "Demucs_ranstft": "./current_models_Sweeprun_ranstft_Demucs/G_5_004000.pth"}
    samplerate = 16000
    segemntlength = 2
    noise_power = 0.3
    if not os.path.exists(f'./output'):
        os.mkdir(f'./output')

    for i in model_path:
        output_path = "./output/"+i
        if not os.path.exists(output_path):
            os.mkdir(output_path)
        device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
        if i[0] == "H":
            model = HDemucs().to(device)
        else:
            model = Demucs().to(device)
        model.eval()
        tempmodel = torch.load(model_path[i], map_location=torch.device('cpu'))
        # G.load_state_dict(torch.load(args.G_path, map_location=torch.device('cpu')), strict=True)
        from collections import OrderedDict

        new_state_dict = OrderedDict()
        for k, v in tempmodel.items():
            name = k[7:]  # remove `module.`
            new_state_dict[name] = v
        # load params
        model.load_state_dict(new_state_dict)
        denoise(audio_list,noise_list,output_path)


import base64
import binascii
import struct
from typing import Union

from crc16 import crc16xmodem

from .exceptions import (
    Ed25519SecretSeedInvalidError,
    Ed25519PublicKeyInvalidError,
    MuxedEd25519AccountInvalidError,
    ValueError,
    TypeError,
)
from .xdr import Xdr

__all__ = ["StrKey"]

_version_bytes = {
    "ed25519_public_key": binascii.a2b_hex("30"),  # G 48 6 << 3
    "ed25519_secret_seed": binascii.a2b_hex("90"),  # S 144 18 << 3
    "pre_auth_tx": binascii.a2b_hex("98"),  # T 152 19 << 3
    "sha256_hash": binascii.a2b_hex("b8"),  # X 184 23 << 3
    "muxed_account": binascii.a2b_hex("60"),  # M 96 12 << 3
}

# https://github.com/stellar/js-stellar-base/pull/330/files
# https://github.com/stellar/js-stellar-base/pull/327/files

class StrKey:
    """StrKey is a helper class that allows encoding and decoding strkey.

    """

    @staticmethod
    def encode_ed25519_public_key(data: bytes) -> str:
        """Encodes data to strkey ed25519 public key.

        :param data: data to encode
        :return: strkey ed25519 public key
        :raises:
            :exc:`ValueError <stellar_sdk.exceptions.ValueError>`
            :exc:`TypeError <stellar_sdk.exceptions.TypeError>`
        """
        return encode_check("ed25519_public_key", data)

    @staticmethod
    def decode_ed25519_public_key(data: str) -> bytes:
        """Decodes strkey ed25519 public key to raw data.

        :param data: strkey ed25519 public key
        :return: raw bytes
        :raises:
            :exc:`Ed25519PublicKeyInvalidError <stellar_sdk.exceptions.Ed25519PublicKeyInvalidError>`
        """
        try:
            return decode_check("ed25519_public_key", data)
        except Exception:
            raise Ed25519PublicKeyInvalidError(
                "Invalid Ed25519 Public Key: {}".format(data)
            )

    @staticmethod
    def is_valid_ed25519_public_key(public_key: str) -> bool:
        """Returns True if the given Stellar public key is a valid ed25519 public key.

        :param public_key: strkey ed25519 public key to check
        :return: `True` if the given Stellar public key is a valid ed25519 public key.
        """
        return is_valid("ed25519_public_key", public_key)

    @staticmethod
    def encode_ed25519_secret_seed(data: bytes) -> str:
        """Encodes data to strkey ed25519 seed.

        :param data: data to encode
        :return: strkey ed25519 seed
        :raises:
            :exc:`ValueError <stellar_sdk.exceptions.ValueError>`
            :exc:`TypeError <stellar_sdk.exceptions.TypeError>`
        """
        return encode_check("ed25519_secret_seed", data)

    @staticmethod
    def decode_ed25519_secret_seed(data: str) -> bytes:
        """Decodes strkey ed25519 seed to raw data.

        :param data: strkey ed25519 seed
        :return: raw bytes
        :raises:
            :exc:`Ed25519SecretSeedInvalidError <stellar_sdk.exceptions.Ed25519SecretSeedInvalidError>`
        """
        try:
            return decode_check("ed25519_secret_seed", data)
        except Exception:
            raise Ed25519SecretSeedInvalidError(
                "Invalid Ed25519 Secret Seed: {}".format(data)
            )

    @staticmethod
    def is_valid_ed25519_secret_seed(seed: str):
        """Returns True if the given Stellar secret key is a valid ed25519 secret seed.

        :param seed: strkey ed25519 secret seed
        :return: `True` if the given Stellar secret key is a valid ed25519 secret seed.
        :raises:
            :exc:`ValueError <stellar_sdk.exceptions.ValueError>`
            :exc:`TypeError <stellar_sdk.exceptions.TypeError>`
        """
        return is_valid("ed25519_secret_seed", seed)

    @staticmethod
    def encode_pre_auth_tx(data: bytes) -> str:
        """Encodes data to strkey preAuthTx.

        :param data: data to encode
        :return: strkey preAuthTx
        :raises:
            :exc:`ValueError <stellar_sdk.exceptions.ValueError>`
            :exc:`TypeError <stellar_sdk.exceptions.TypeError>`
        """
        return encode_check("pre_auth_tx", data)

    @staticmethod
    def decode_pre_auth_tx(data: str) -> bytes:
        """Decodes strkey PreAuthTx to raw data.

        :param data: strkey preAuthTx
        :return: raw bytes
        :raises:
            :exc:`ValueError <stellar_sdk.exceptions.ValueError>`
            :exc:`TypeError <stellar_sdk.exceptions.TypeError>`
        """
        return decode_check("pre_auth_tx", data)

    @staticmethod
    def encode_sha256_hash(data: bytes) -> str:
        """Encodes data to strkey sha256 hash.

        :param data: data to encode
        :return: strkey sha256 hash
        :raises:
            :exc:`ValueError <stellar_sdk.exceptions.ValueError>`
            :exc:`TypeError <stellar_sdk.exceptions.TypeError>`
        """
        return encode_check("sha256_hash", data)

    @staticmethod
    def decode_sha256_hash(data: str) -> bytes:
        """Decodes strkey sha256 hash to raw data.

        :param data: strkey sha256 hash
        :return: raw bytes
        :raises:
            :exc:`ValueError <stellar_sdk.exceptions.ValueError>`
            :exc:`TypeError <stellar_sdk.exceptions.TypeError>`
        """
        return decode_check("sha256_hash", data)

    @staticmethod
    def encode_muxed_account(data: Xdr.types.MuxedAccount) -> str:
        """Encodes data to strkey muxed account.

        :param data: data to encode
        :return: strkey muxed account
        :raises:
            :exc:`ValueError <stellar_sdk.exceptions.ValueError>`
            :exc:`TypeError <stellar_sdk.exceptions.TypeError>`
        """
        if data.type == Xdr.const.KEY_TYPE_ED25519:
            return StrKey.encode_ed25519_public_key(data.ed25519)
        packer = Xdr.StellarXDRPacker()
        packer.pack_int64(data.med25519.id)
        packer.pack_uint256(data.med25519.ed25519)
        data = packer.get_buffer()
        return encode_check("muxed_account", data)

    @staticmethod
    def decode_muxed_account(data: str) -> Xdr.types.MuxedAccount:
        """Decodes strkey muxed account to raw data.

        :param data: strkey muxed account
        :return: raw bytes
        :raises:
            :exc:`ValueError <stellar_sdk.exceptions.ValueError>`
            :exc:`TypeError <stellar_sdk.exceptions.TypeError>`
        """
        data_length = len(data)
        if data_length == 56:
            muxed = Xdr.types.MuxedAccount(
                type=Xdr.const.KEY_TYPE_ED25519,
                ed25519=StrKey.decode_ed25519_public_key(data),
            )
        elif data_length == 69:
            # let's optimize it in v3.
            try:
                xdr = decode_check("muxed_account", data)
            except Exception:
                raise MuxedEd25519AccountInvalidError(
                    "Invalid Muxed Account: {}".format(data)
                )
            unpacker = Xdr.StellarXDRUnpacker(xdr)
            med25519 = Xdr.nullclass()
            med25519.id = unpacker.unpack_int64()
            med25519.ed25519 = unpacker.unpack_uint256()
            muxed = Xdr.types.MuxedAccount(
                type=Xdr.const.KEY_TYPE_MUXED_ED25519, med25519=med25519
            )
        else:
            raise ValueError("Invalid encoded string, this is not a valid account.")
        return muxed

def decode_check(version_byte_name: str, encoded: str) -> bytes:
    encoded_data = _bytes_from_decode_data(encoded)
    encoded_data = encoded_data + b"=" * ((4 - len(encoded_data) % 4) % 4)

    try:
        decoded_data = base64.b32decode(encoded_data)
    except binascii.Error:
        raise ValueError("Incorrect padding.")

    if encoded_data != base64.b32encode(decoded_data):  # Is that even possible?
        raise ValueError("Invalid encoded bytes.")

    version_byte = decoded_data[0:1]
    payload = decoded_data[0:-2]
    data = decoded_data[1:-2]
    checksum = decoded_data[-2:]

    expected_version = _version_bytes.get(version_byte_name)
    if expected_version is None:
        raise TypeError(
            '{} is not a valid version byte name. expected one of "ed25519_public_key", '
            '"ed25519_secret_seed", "pre_auth_tx", "sha256_hash", "muxed_account"'.format(
                version_byte_name
            )
        )

    if version_byte != expected_version:
        raise TypeError(
            "Invalid version byte. Expected {}, got {}".format(
                str(expected_version), str(version_byte)
            )
        )

    expected_checksum = _calculate_checksum(payload)
    if expected_checksum != checksum:
        raise ValueError("Invalid checksum")

    return data

def encode_check(version_byte_name: str, data: bytes) -> str:
    if data is None:
        raise ValueError("cannot encode null data")

    version_byte = _version_bytes.get(version_byte_name)
    if version_byte is None:
        raise TypeError(
            '{} is not a valid version byte name. expected one of "ed25519_public_key", '
            '"ed25519_secret_seed", "pre_auth_tx", "sha256_hash", "muxed_account"'.format(
                version_byte_name
            )
        )
    payload = version_byte + data
    crc = _calculate_checksum(payload)
    return base64.b32encode(payload + crc).decode("utf-8").rstrip("=")

def is_valid(version_byte_name: str, encoded: str) -> bool:
    if encoded and len(encoded) != 56:
        return False
    try:
        decoded = decode_check(version_byte_name, encoded)
        # if len(decoded) != 32:
        #     return False
    except (ValueError, TypeError):
        return False
    return True

def _bytes_from_decode_data(s: Union[str, bytes, bytearray]) -> bytes:
    """copy from base64._bytes_from_decode_data
    """
    bytes_types = (bytes, bytearray)  # Types acceptable as binary data
    if isinstance(s, str):
        try:
            return s.encode("ascii")
        except UnicodeEncodeError:
            raise ValueError("string argument should contain only ASCII characters")
    if isinstance(s, bytes_types):
        return s
    try:
        return memoryview(s).tobytes()
    except TypeError:
        raise TypeError(
            "argument should be a bytes-like object or ASCII "
            "string, not %r" % s.__class__.__name__
        ) from None

def _calculate_checksum(payload):
    # This code calculates CRC16-XModem checksum of payload
    checksum = crc16xmodem(payload)
    # Ensure that the checksum is in LSB order.
    checksum = struct.pack("<H", checksum)
    return checksum


import mediapipe as mp
import numpy as np
import cv2
import torch
import pyvirtualcam as pv
from os import system
from time import sleep

from tha2.poser.modes import mode_20
from tha2.util import resize_PIL_image, \
    extract_PIL_image_from_filelike, \
    extract_pytorch_image_from_PIL_image, \
    convert_output_image_from_torch_to_numpy

from utils import Point
import calc
import config

class Translator:
    def __init__(self, poser, cuda):
        self.poser = poser
        self.cuda = cuda

        self.face_mesh = mp.solutions.face_mesh.FaceMesh(
            False, 1, True,
            config.min_detection_confidence,
            config.min_tracking_confidence
        )
        self.mp_drawing = mp.solutions.drawing_utils
        self.drawing_spec = self.mp_drawing.DrawingSpec(thickness=1, circle_radius=1)

        pil_img = resize_PIL_image(extract_PIL_image_from_filelike('./data/illust/9e.png'))
        self.source_img = extract_pytorch_image_from_PIL_image(pil_img).to(self.cuda)

        self.cam = cv2.VideoCapture(0)
        self.install_webcam()

    def __del__(self):
        self.cam.release()
        cv2.destroyAllWindows()
        print('tracking terminated')

    # 启动本机摄像头，读取图像
    def run(self):
        while self.cam.isOpened():
            try:
                success, img = self.cam.read()
                if not success:
                    print('Ignoring empty frame...')
                    continue

                landmarks = self.process_img(img)
                if len(landmarks) != 0:
                    img = self.translate_to_anime(landmarks)
                    self.webcam.send(img)
                    self.webcam.sleep_until_next_frame()

            except KeyboardInterrupt:
                break

    # 翻译数据
    def translate_to_anime(self, landmarks):
        if len(landmarks) == 0:
            return

        params = [0.0 for i in range(config.num_params)]
        params[40] = calc.x_angle(landmarks)
        params[39] = calc.y_angle(landmarks, params[40])
        params[41] = calc.z_angle(landmarks)
        params[14] = calc.eye_open(landmarks, True, params[41])
        params[13] = calc.eye_open(landmarks, False, params[41])
        params[26] = calc.mouth_open(landmarks)
        params[38] = calc.iris_ang(landmarks)

        pose = torch.tensor(params, device=self.cuda)
        output_img = self.poser.pose(self.source_img, pose, 0)[0].detach().cpu()
        numpy_img = np.uint8(np.rint(convert_output_image_from_torch_to_numpy(output_img) * 255.0))[:, :, :3]
        # numpy_img = cv2.cvtColor(cv2.flip(numpy_img, 1), cv2.COLOR_BGR2RGB)

        # cv2.imshow('anime', numpy_img)
        # cv2.waitKey(1)

        return numpy_img

    # 解析面部数据点
    def process_img(self, img):
        landmarks = []
        img = cv2.cvtColor(cv2.flip(img, 1), cv2.COLOR_BGR2RGB)
        img.flags.writeable = False
        h, w, c = img.shape
        results = self.face_mesh.process(img)

        if results.multi_face_landmarks:
            total_landmarks = results.multi_face_landmarks[0]
            for idx, landmark in enumerate(total_landmarks.landmark):
                x, y = landmark.x * w, landmark.y * h
                # cv2.circle(img, (int(x), int(y)), 1, (0, 255, 255), -1)
                # cv2.putText(img, str(idx), (int(x), int(y)), cv2.FONT_HERSHEY_SIMPLEX, 0.2, (0, 255, 255), 1)
                landmarks.append(Point(x, y))

        # cv2.imshow('face', img)
        # cv2.waitKey(1)

        return landmarks

    # 创建/获取虚拟摄像头
    def install_webcam(self):
        try:
            self.webcam = pv.Camera(width=256, height=256, fps=20, device='VirtualCamera')
        except RuntimeError:
            system('.\\vc\\Install.bat')
            error_n = 0
            while True:
                try:
                    self.webcam = pv.Camera(width=256, height=256, fps=20, device='VirtualCamera')
                    break
                except RuntimeError:
                    error_n += 1
                    if error_n > 5:
                        raise RuntimeError('Fail to install webcam')
                    sleep(1)

if __name__ == '__main__':
    cuda = torch.device('cuda')
    poser = mode_20.create_poser(cuda)

    translator = Translator(poser, cuda)
    translator.run()


import dataclasses
import importlib
import logging
from typing import Dict
from typing import Iterable
from typing import Optional
from typing import Tuple
from typing import Union

import OpenGL.GL
import OpenGL.GL.NV.conservative_raster
import glcontext
import moderngl
import numpy as np
import torch as t

from corenet.gl import egl_context

importlib.reload(glcontext)
egl_context.monkey_patch_moderngl()

InputTensor = Union[t.Tensor, np.ndarray, int, float, bool, Iterable]

log = logging.getLogger(__name__)

@dataclasses.dataclass(frozen=True)
class Uniform:
  name: str
  value: InputTensor

@dataclasses.dataclass()
class Buffer:
  binding: int
  value: InputTensor
  is_io: bool = False

@dataclasses.dataclass(frozen=True)
class Texture:
  name: str
  value: InputTensor
  bind_as_array: bool = False

@dataclasses.dataclass(frozen=True)
class RenderInput:
  # The number of points to render. The geometry shader can then convert these
  # into other geometry.
  num_points: int

  # The parameters to pass to the shaders.
  arguments: Iterable[Union[Uniform, Buffer, Texture]]

  # The vertex shader
  vertex_shader: str

  # The geometry shader
  geometry_shader: str

  # The fragment shader
  fragment_shader: str

  # The output resolution, tuple (height, width)
  output_resolution: Tuple[int, int] = (256, 256)

  # The clear color, tuple (R, G, B) or (R, G, B, A).
  clear_color: Iterable[float] = (0, 0, 0)

  # The output type (either uint8 or float32).
  output_type: t.dtype = t.uint8

  # Whether depth testing is enabled.
  depth_test_enabled: bool = True

  # Whether to use conservative rasterization
  conservative_rasterization: bool = False

class _EglRenderer:
  _context_cache = {}  # type: Dict[int, _EglRenderer]

  def __init__(self, gl_context: moderngl.Context):
    self._program_cache = {}  # type: Dict[str, moderngl.Program]
    self._gl_context = gl_context

  @classmethod
  def get_instance(cls, cuda_device: int):
    if cuda_device not in cls._context_cache:
      # Cuda has to be initialized for the cuda_egl backend to work
      t.cuda.init()
      ctx = moderngl.create_standalone_context(backend="cuda_egl",
                                               cuda_device=cuda_device)
      cls._context_cache[cuda_device] = _EglRenderer(ctx)
    return cls._context_cache[cuda_device]

  def _check_gl_error(self):
    err = self._gl_context.error
    if err != "GL_NO_ERROR":
      raise ValueError(f"OpenGL error encountered: {err}")

  def _upload_uniform(self, program: moderngl.Program,
                      parameter: Uniform):
    if parameter.name not in program:
      log.info(f"Uniform {parameter.name} not found in program")
    else:
      value = t.as_tensor(parameter.value).cpu()
      if len(value.shape) == 2:
        value = tuple(value.transpose(0, 1).reshape([-1]))
      elif len(value.shape) == 1:
        value = tuple(value)
      elif value.shape == ():
        value = value.item()
      else:
        raise ValueError("Only supports 0, 1, and 2 dim tensors.")
      program[parameter.name].value = value

  def render(self, render_input: RenderInput):
    inp = render_input
    with self._gl_context:
      program_key = (
          f"{inp.vertex_shader}|{inp.geometry_shader}|{inp.fragment_shader}")

      if program_key not in self._program_cache:
        self._program_cache[program_key] = self._gl_context.program(
            vertex_shader=inp.vertex_shader,
            fragment_shader=inp.fragment_shader,
            geometry_shader=inp.geometry_shader)
      program = self._program_cache[program_key]

      objects_to_delete = []
      buffer_bindings = {}  # type: Dict[int, moderngl.Buffer]
      texture_location = 0
      try:
        for parameter in inp.arguments:
          if isinstance(parameter, Uniform):
            self._upload_uniform(program, parameter)
          elif isinstance(parameter, Buffer):
            value = t.as_tensor(parameter.value).reshape([-1]).cpu().numpy()
            buffer = self._gl_context.buffer(value)
            buffer.bind_to_storage_buffer(parameter.binding)
            buffer_bindings[parameter.binding] = buffer
            objects_to_delete.append(buffer)
          elif isinstance(parameter, Texture):
            if not parameter.bind_as_array:
              raise NotImplementedError()
            if parameter.name not in program:
              log.info(f"Uniform {parameter.name} not found in program")
            else:
              val = parameter.value.cpu().numpy()
              texture = self._gl_context.texture_array(
                  val.shape[1:3] + val.shape[0:1], val.shape[3], val)
              texture.repeat_x = True
              texture.repeat_y = True
              texture.use(location=texture_location)
              program.get(parameter.name, None).value = texture_location
              texture_location += 1
              objects_to_delete.append(texture)
          else:
            raise ValueError("Unknown parameter type")
          self._check_gl_error()

        h, w = inp.output_resolution
        gl_dtype, np_dtype = {
            t.uint8: ("f1", np.uint8),
            t.float32: ("f4", np.float32)
        }[inp.output_type]

        render_buffer = self._gl_context.renderbuffer(
            (w, h), components=4, samples=0, dtype=gl_dtype)
        objects_to_delete.append(render_buffer)
        depth_buffer = self._gl_context.depth_renderbuffer((w, h), samples=0)
        objects_to_delete.append(depth_buffer)
        framebuffer = self._gl_context.framebuffer(render_buffer, depth_buffer)
        objects_to_delete.append(framebuffer)
        framebuffer.use()

        vertex_array = self._gl_context.vertex_array(program, ())
        objects_to_delete.append(vertex_array)
        self._gl_context.clear(*inp.clear_color)
        self._gl_context.disable(moderngl.CULL_FACE)
        if inp.depth_test_enabled:
          self._gl_context.enable(moderngl.DEPTH_TEST)
          self._gl_context.depth_func = "<="
        else:
          self._gl_context.disable(moderngl.DEPTH_TEST)

        if render_input.conservative_rasterization:
          OpenGL.GL.glEnable(
              OpenGL.GL.NV.conservative_raster.GL_CONSERVATIVE_RASTERIZATION_NV)
        else:
          OpenGL.GL.glDisable(
              OpenGL.GL.NV.conservative_raster.GL_CONSERVATIVE_RASTERIZATION_NV)

        vertex_array.render(mode=moderngl.POINTS, vertices=inp.num_points)
        self._check_gl_error()
        result = np.zeros([h, w, 4], dtype=np_dtype)
        framebuffer.read_into(result, components=4, dtype=gl_dtype)
        self._check_gl_error()

        for parameter in inp.arguments:
          if isinstance(parameter, Buffer) and parameter.is_io:
            old = parameter.value
            npdt = {t.float32: np.float32, t.int32: np.int32}[old.dtype]
            temp_buffer = np.zeros(old.shape, npdt)
            buffer_bindings[parameter.binding].read_into(temp_buffer)
            parameter.value = t.as_tensor(temp_buffer)

        return t.as_tensor(result)

      finally:
        for v in objects_to_delete:
          v.release()

def gl_simple_render(
    render_input: RenderInput,
    cuda_device: Optional[int] = None
):
  """Renders the supplied configuration with OpenGL.

  Args:
    render_input: The render input
    cuda_device: The GPU to use, given as a CUDA device number

  Returns:
    The rendered image, output_type[height, width, 4]

  Buffer parameters with is_io set to True will be read back. This can either
  happen in the original buffer or in a new buffer. The implementation will
  update the value field in the buffer parameter in the latter case.

  There is no guarantee about the device of both the rendered image and the
  buffers that are read back.
  """
  if cuda_device is None:
    cuda_device = t.cuda.current_device()
  instance = _EglRenderer.get_instance(cuda_device)
  return instance.render(render_input)