from defs import paths as pt
from defs import features as ft
import winsound
import soundfile as sf
from defs import beats
from defs import wavs
import numpy as np
import librosa.display
import sklearn
import os


# vytvori remix nahravky
# klastruje MFCC parametry
# ramce seskupi podle kategorii
# slouci a ulozi do souboru
if not os.path.exists('data/remix'):
    os.makedirs('data/remix')
names = pt.listdir('data/_wavs')
path = 'data/'
stngs = wavs.Settings(sr=44100, frame_length=2048, hop_length=512)


for i, name in enumerate(names):
    if name == 'PHQ':
        rng = list([1.1, 11.1])
        bts = beats.BeatsData()
        bts.load_beats(path+pt.beat(name), stngs)
        bts.trim(bts.index4label(rng[0]), bts.index4label(rng[1]))
        wav = wavs.WavData(stngs, path+pt.wav(name))
        y = wav.load_wav([bts.time[0], bts.time[-1]])

        fts = ft.FeatsData()
        fts.load_feats(path + pt.feat(name))

        model = sklearn.cluster.KMeans(n_clusters=3)
        min_max_scaler = sklearn.preprocessing.MinMaxScaler(feature_range=(-1, 1))
        features_scaled = min_max_scaler.fit_transform(fts.mfcc.T)
        labels = model.fit_predict(features_scaled)

        sort_frm = np.argsort(labels)
        sort_smpl = librosa.frames_to_samples(sort_frm)
        intervals = np.column_stack((sort_smpl, sort_smpl+512))
        sort_y = librosa.effects.remix(y, intervals)

        sf.write('data/remix/remix.wav', sort_y, stngs.sr, 'PCM_24')
        # winsound.PlaySound(pt.clip('tst'), winsound.SND_FILENAME)

