# Path: apicultor/emotion/MusicEmotionMachine.py
# class descriptors_and_keys():
# class deep_support_vector_machines(object):
# class svm_layers(deep_support_vector_machines):
# class main_svm(deep_support_vector_machines):
# class MusicEmotionStateMachine(object):
#     def __init__(self, tags_dir,  multitag):
# def feature_scaling(f):
# def KMeans_clusters(fscaled):
#     def __init__(self, kernel1, kernel2):
#     def polynomial_kernel(self, x, y, gamma):
#     def linear_kernel_matrix(self, x, y): 
#     def sigmoid_kernel(self, x, y, gamma):
#     def rbf_kernel(self, x, y, gamma):
#     def fit_model(self, features,labels, kernel1, kernel2, C, reg_param, gamma, learning_rate):
#     def decision_function(self, features):
#     def predictions(self, features, targts): 
#     def __init__(self):
#     def layer_computation(self, features, labels, kernel_configs):
#     def store_attention(self, files, output_dir):
#     def attention(self):
#     def best_labels(self):
#     def store_good_labels(self, files, output_dir):
# def best_kernels_output(best_estimator, kernel_configs):
#     def __init__(self, S, lab, C, reg_param, gamma, kernels_config, output_dir):
#     def neg_and_pos(self, files):
#     def save_decisions(self):
#     def save_classes(self, files):
# def emotions_data_dir(files_dir):
# def multitag_emotions_dictionary_dir():
# def multitag_emotions_dir(tags_dirs, files_dir, generator):
#     def __init__(self, name, files_dir):
#     def sad_music_remix(self, neg_arous_dir, files, decisions, files_dir, harmonic = None):
#     def happy_music_remix(self, pos_arous_dir, files, decisions, files_dir, harmonic = None):
#     def relaxed_music_remix(self, neg_arous_dir, files, decisions, files_dir):
#     def angry_music_remix(self, pos_arous_dir, files, decisions, files_dir):
#     def not_happy_music_remix(self, neg_arous_dir, files, decisions, files_dir):
#     def not_sad_music_remix(self, pos_arous_dir, files, decisions, files_dir):
#     def not_angry_music_remix(self, neg_arous_dir, files, decisions, files_dir):
#     def not_relaxed_music_remix(self, pos_arous_dir, files, decisions, files_dir):
#     def remix(self, files, decisions, files_dir):
# def main():  
#         K = 0                                         
#     C = best_estimator['C'][max_score]    
# 
# Path: apicultor/sonification/Sonification.py
# def write_file(filename, fs, data):           
#     write(filename+'.wav', fs, data) 
#     call(['ffmpeg', '-i', filename+'.wav', filename+'.ogg', '-y'])
#     call(['rm', '-f', filename+'.wav'])


from ..emotion.MusicEmotionMachine import scratch_music
from ..utils.data import *
from colorama import Fore
from sklearn import preprocessing
from ..utils.algorithms import *
from ..sonification.Sonification import write_file
from soundfile import read
from sklearn.decomposition.pca import PCA                                      
from sklearn.cluster import AffinityPropagation
from collections import defaultdict
from random import choice
import time
import numpy as np                                                      
import matplotlib.pyplot as plt                                   
import os, sys                                                      
import shutil
import librosa
import logging
    :param descriptor: descriptor used for similarity                                       
    :param euclidean_labels: groups of clusters                                             
    :param files: the .json files (use get_files)                                           
    """  
    groups = [[] for i in range(len(np.unique(euclidean_labels)))]
    for i, x in enumerate(euclidean_labels):
        groups[x].append([files[i], x])
                
    for c in range(len(groups)):
        if not os.path.exists(files_dir+'/tempo/'+str(c)):
            os.makedirs(files_dir+'/tempo/'+str(c))
            os.makedirs(files_dir+'/tempo/'+str(c)+'/remix')
        for t in groups[c]:
            for s in list(os.walk(files_dir+'/tempo', topdown=False))[-1][-1]:
                 if str(t[0]).split('.json')[0] == s.split('tempo.ogg')[0]:
                     shutil.copy(files_dir+'/tempo/'+s, files_dir+'/tempo/'+str(c)+'/'+s)     
                     print(str().join((str(t)))) 
        try:
            simil_audio = [read(files_dir+'/tempo/'+str(c)+'/'+f)[0] for f in list(os.walk(files_dir+'/tempo/'+str(c), topdown = False))[-1][-1]]
            audio0 = scratch_music(choice(simil_audio))
            audio1 = scratch_music(choice(simil_audio)) 
            del simil_audio                               
            audio_N = min([len(i) for i in [audio0, audio1]])  
            audio_samples = [i[:audio_N]/i.max() for i in [audio0, audio1]]                                               
            simil_x = np.array(audio_samples).sum(axis=0) 
            del audio_samples
            simil_x = 0.5*simil_x/simil_x.max()      
            h, p = librosa.decompose.hpss(librosa.core.stft(simil_x))
            del simil_x, h
            p = librosa.istft(p)                                                

# Path: apicultor/emotion/MusicEmotionMachine.py
# class descriptors_and_keys():
# class deep_support_vector_machines(object):
# class svm_layers(deep_support_vector_machines):
# class main_svm(deep_support_vector_machines):
# class MusicEmotionStateMachine(object):
#     def __init__(self, tags_dir,  multitag):
# def feature_scaling(f):
# def KMeans_clusters(fscaled):
#     def __init__(self, kernel1, kernel2):
#     def polynomial_kernel(self, x, y, gamma):
#     def linear_kernel_matrix(self, x, y): 
#     def sigmoid_kernel(self, x, y, gamma):
#     def rbf_kernel(self, x, y, gamma):
#     def fit_model(self, features,labels, kernel1, kernel2, C, reg_param, gamma, learning_rate):
#     def decision_function(self, features):
#     def predictions(self, features, targts): 
#     def __init__(self):
#     def layer_computation(self, features, labels, kernel_configs):
#     def store_attention(self, files, output_dir):
#     def attention(self):
#     def best_labels(self):
#     def store_good_labels(self, files, output_dir):
# def best_kernels_output(best_estimator, kernel_configs):
#     def __init__(self, S, lab, C, reg_param, gamma, kernels_config, output_dir):
#     def neg_and_pos(self, files):
#     def save_decisions(self):
#     def save_classes(self, files):
# def emotions_data_dir(files_dir):
# def multitag_emotions_dictionary_dir():
# def multitag_emotions_dir(tags_dirs, files_dir, generator):
#     def __init__(self, name, files_dir):
#     def sad_music_remix(self, neg_arous_dir, files, decisions, files_dir, harmonic = None):
#     def happy_music_remix(self, pos_arous_dir, files, decisions, files_dir, harmonic = None):
#     def relaxed_music_remix(self, neg_arous_dir, files, decisions, files_dir):
#     def angry_music_remix(self, pos_arous_dir, files, decisions, files_dir):
#     def not_happy_music_remix(self, neg_arous_dir, files, decisions, files_dir):
#     def not_sad_music_remix(self, pos_arous_dir, files, decisions, files_dir):
#     def not_angry_music_remix(self, neg_arous_dir, files, decisions, files_dir):
#     def not_relaxed_music_remix(self, pos_arous_dir, files, decisions, files_dir):
#     def remix(self, files, decisions, files_dir):
# def main():  
#         K = 0                                         
#     C = best_estimator['C'][max_score]    
# 
# Path: apicultor/sonification/Sonification.py
# def write_file(filename, fs, data):           
#     write(filename+'.wav', fs, data) 
#     call(['ffmpeg', '-i', filename+'.wav', filename+'.ogg', '-y'])
#     call(['rm', '-f', filename+'.wav'])


# Path: apicultor/machine_learning/SoundSimilarity.py
from ..emotion.MusicEmotionMachine import scratch_music
from ..utils.data import *
from colorama import Fore
from sklearn import preprocessing
from ..utils.algorithms import *
from ..sonification.Sonification import write_file
from soundfile import read
from sklearn.decomposition.pca import PCA                                      
from sklearn.cluster import AffinityPropagation
from collections import defaultdict
from random import choice
import time
import numpy as np                                                      
import matplotlib.pyplot as plt                                   
import os, sys                                                      
import shutil
import librosa
import logging

    :param descriptor: descriptor used for similarity                                       
    :param euclidean_labels: groups of clusters                                             
    :param files: the .json files (use get_files)                                           
    """  
    groups = [[] for i in range(len(np.unique(euclidean_labels)))]
    for i, x in enumerate(euclidean_labels):
        groups[x].append([files[i], x])
                
    for c in range(len(groups)):
        if not os.path.exists(files_dir+'/tempo/'+str(c)):
            os.makedirs(files_dir+'/tempo/'+str(c))
            os.makedirs(files_dir+'/tempo/'+str(c)+'/remix')
        for t in groups[c]:
            for s in list(os.walk(files_dir+'/tempo', topdown=False))[-1][-1]:
                 if str(t[0]).split('.json')[0] == s.split('tempo.ogg')[0]:
                     shutil.copy(files_dir+'/tempo/'+s, files_dir+'/tempo/'+str(c)+'/'+s)     
                     print(str().join((str(t)))) 
        try:
            simil_audio = [read(files_dir+'/tempo/'+str(c)+'/'+f)[0] for f in list(os.walk(files_dir+'/tempo/'+str(c), topdown = False))[-1][-1]]
            audio0 = scratch_music(choice(simil_audio))
            audio1 = scratch_music(choice(simil_audio)) 
            del simil_audio                               
            audio_N = min([len(i) for i in [audio0, audio1]])  
            audio_samples = [i[:audio_N]/i.max() for i in [audio0, audio1]]                                               
            simil_x = np.array(audio_samples).sum(axis=0) 
            del audio_samples
            simil_x = 0.5*simil_x/simil_x.max()      
            h, p = librosa.decompose.hpss(librosa.core.stft(simil_x))
            del simil_x, h
            p = librosa.istft(p)                                                

            write_file(files_dir+'/tempo/'+str(c)+'/remix/'+'similarity_mix_bpm', 44100, p)  