# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# +
import pandas as pd
import matplotlib.pyplot as plt 
import numpy as np 
# %matplotlib inline
from sklearn import svm
from sklearn.model_selection import train_test_split
from sklearn import metrics
import pickle

import requests
# -

data = pd.read_csv('http://3e9387c7.ngrok.io/get_data')

data

# +
# data.to_csv('gesture_decline.csv')
# -

gesture1 = pd.read_csv('gesture_accept.csv')
gesture2 = pd.read_csv('gesture_decline.csv')

# #### training data prepocessing 

gesture1[:11]

a = gesture1.loc[:10]







gesture1.any(1)

(gesture1[:10] == 0).all(1)

gesture1.loc[(gesture1==0).any(1)]

# +
# 1 = accept, 2 = decline

gesture1 = gesture1.drop(columns=['Unnamed: 0'])
gesture2 = gesture2.drop(columns=['Unnamed: 0'])

drop_zeros = gesture1.loc[(gesture1==0).any(1)].index
gesture1 = gesture1.drop(drop_zeros, axis=0)
gesture1= gesture1.reset_index(drop=True)

drop_zeros = gesture2.loc[(gesture2==0).any(1)].index
gesture2 = gesture2.drop(drop_zeros, axis=0)
gesture2= gesture2.reset_index(drop=True)


gesture1['label'] = 0
gesture2['label'] = 1
# -

gesture1

# +
gesture1 = gesture1.loc[:2980]
gesture2 = gesture2.loc[:2470]

dataset = gesture1.append(gesture2)

dataset= dataset.reset_index(drop=True)
# -

# ### Preprocessing 1

# +
labels = dataset['label'].to_numpy()
labels = labels[:-9:10]

dataset = dataset[['x','y','z']]
# -

dataset

labels.size

dataset = dataset.loc[:5450]

dataset

# ### Preprocessing 2

frames = []
def frame():
    n=0
    while n != len(dataset)-1:
        frames.append(dataset.loc[n:n+1].to_numpy())
        n += 1
    else:
        return frames



gest_frames = frame()

len(gest_frames)


# ### Peprocessing 3 > FFT, feature extraction and feature vector 

# +
def fft_transform(frame_data):
    
    fft_transform.feature_set = np.array([])
    
    for frame in frame_data:
        
        frame_feature_set = np.array([])
        
        fft_frame = np.fft.fft(frame, axis=0)
#         fft_transform.fft_data.append(fft_frame)
        
#         n = frame.size
#         freq = np.fft.fftfreq(n, d=0.01)
#         fft_transform.fft_freq.append(freq)
        
#         fft_ps = np.abs(fft_frame)**2
#         fft_transform.fft_power_spec.append(fft_ps)
        
        mean = np.mean(fft_frame, axis=0)
        frame_feature_set = np.concatenate((frame_feature_set, mean), axis=0)
        
        
        energy = (np.sum((fft_frame**2),axis=0))/len(fft_frame)
        frame_feature_set = np.concatenate((frame_feature_set, energy), axis=0)
        
        
        stdev = np.std(fft_frame, axis=0)
        frame_feature_set = np.concatenate((frame_feature_set, stdev), axis=0)
        
        
        correlation = np.corrcoef(fft_frame, rowvar=False).reshape(3,3)
        frame_feature_set = np.concatenate((frame_feature_set.reshape(3,3), correlation), axis=0)
        
        fft_transform.feature_set = np.concatenate((frame_feature_set.flatten(), fft_transform.feature_set), axis=0)
    
#  make a simple array         

    return fft_transform.feature_set
# -

fft_transform(gest_frames)

# ### Training data set 

n = int((fft_transform.feature_set.size)/180)
axis = 3
feature_10axis = 60
fft_transform.feature_set = fft_transform.feature_set.reshape(n,(feature_10axis*axis))
X = np.abs(fft_transform.feature_set)
y = labels

y.shape

X[1]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

C = 0.1
clf = svm.SVC(kernel='poly',C=C, probability=True)
clf.fit(X_train, y_train)

with open('/Users/martinantos/Documents/school/IoT/Panache/clf.pickle', 'wb') as f:
    pickle.dump(clf, f)

model = pickle.dumps(clf)

# +
# clftest = pickle.loads(model)

# +
# clftest.predict(X.reshape(1,-1))
# -

y_pred = clf.predict(X_test)

print("accuracy:", metrics.accuracy_score(y_test, y_pred))
print("Precision:",metrics.precision_score(y_test, y_pred))
print("Recall:",metrics.recall_score(y_test, y_pred))


# 1 = accetpt, 
def clfout(sample):
    sample = sample.reshape(1,-1)
    if clf.decision_function(sample) <=(-1.2):
        return 1
    elif clf.decision_function(sample) >= 1.0:
        return 2 
    else:
        return 0


clfout(X[356])

clf.decision_function(X).max()

clf.decision_function(X)

clf.predict(X[65].reshape(1,-1))

# +

clf.decision_function(X[65].reshape(1,-1))

StarcoderdataJupyterScriptsDedupFiltered