Beispiel #1
0
 def procesado(x):
     """ Función principal para el procesado del audio a analizar para cada
     ciclo de ejecución, 'x'. """
     # Manejo de datos temporales.
     ahora = tiempo() # instante de arranque para obtener la duración del ciclo
     print('\nCalculando ...')
     inicio = localtime(tiempo()-len(x)/fs) # tiempo de inicio del audio a analizar
     fin = localtime() # tiempo final del audio a analizar
     t_inic = np.array([inicio.tm_hour, inicio.tm_min, inicio.tm_sec])
     dd = inicio.tm_mday
     mn = inicio.tm_mon
     yy = inicio.tm_year
     # Procesamiento de la señal de audio.
     xA = filt_A(x.reshape(-1)) # ponderación 'A'
     xA_filt = filt_oct(xA) # filtrado por octavas
     # Cálculo de niveles de presión con compensación.
     niv_y = np.transpose(niveles(rms_t(xA_filt), vcal, ncal)) + ajuste
     # Agregado de niveles globales.
     glob_y = np.apply_along_axis(sum_db, 1, niv_y).reshape(niv_y.shape[0],1)
     niv_y = np.hstack((niv_y, glob_y))
     # Agregado de tiempos de inicio para la matriz de salida.
     t = agregar_t(t_inic)
     mat = np.hstack((t, niv_y))
     # Escritura de la matriz de salida en el archivo de volcado '.npy'.
     if not inicio.tm_mday == fin.tm_mday: # si hubo cambio de día, separo los resultados
         separar(yy, mn, dd, fin, mat)
     else:
         escribir(yy, mn, dd, mat) # si no escribo directo la matriz
     # Impresión en consola de tiempo de ejecución y nivel global del ciclo.
     print('\nEjecución de ciclo completa. \nTiempo de ejecución : ' + str(np.around(tiempo() - ahora, 2)) + ' s\n')
     print('Nivel global = ' + str(np.around(glob_y, 2)) +' dBA')
     return
def tarea_generar_plan_ple(parametros_tarea, estadisticas_tarea):
    print("INICIO generación plan PLE con id {}".format(parametros_tarea["id_plan_estudios"]))

    estadisticas = EstadisticasDTO()
    estadisticas.cargar_desde_JSON(estadisticas_tarea)
    inicio = tiempo()
    estadisticas.fecha_inicio_generacion = get_str_fecha_y_hora_actual()

    parametros = Parametros()
    parametros.actualizar_valores_desde_JSON(parametros_tarea)

    generar_y_ejecutar_codigo_PULP(parametros)

    estadisticas.fecha_fin_generacion = get_str_fecha_y_hora_actual()
    estadisticas.segundos_total_generacion = float(tiempo() - inicio)
    estadisticas.tiempo_total_generacion = convertir_tiempo(tiempo() - inicio)

    print("FIN generación plan PLE con id {}".format(parametros_tarea["id_plan_estudios"]))

    print("Se invoca al guardado para el plan PLE con id {}".format(parametros_tarea["id_plan_estudios"]))
    from app.API_Rest.GeneradorPlanCarreras.broker_guardar_plan_generado import tarea_guadar_plan_de_estudios
    tarea_guadar_plan_de_estudios.delay(parametros.generar_parametros_json(), estadisticas.get_JSON())
def archivo_existe(nombre):
    if  os.path.isfile(nombre):  
        print("Abriendo...")
        tiempo(2)
    else:
        print("no existe el archivo con nombre {}".format(nombre))    
# WHAT TO ANALYSE
# ===============
# comma separated list: {'KF100', KF1000', 'GSANG', 'ENDO100','DJTECJTOOLS60'}
collection = ['KF100', 'KF1000', 'GSANG', 'ENDO100','DJTECHTOOLS60']
# comma separated list: {'edm', 'non-edm'}
genre = ['edm']
# comma separated list: {'major', 'minor'}
modality = ['minor', 'major'] 
# Limit the analysis to n RANDOM songs. 0 analyses all the collection:
limit_analysis = 0
verbose = True
results_to_file = True

#create directory and unique time identifier
if results_to_file:
    uniqueTime = str(int(tiempo()))
    temp_folder = '/Users/angel/KeyDetection_'+uniqueTime
    os.mkdir(temp_folder)

# retrieve filenames according to the desired settings...
allfiles = os.listdir(audio_folder)
if '.DS_Store' in allfiles: 
    allfiles.remove('.DS_Store')

for item in collection:
    collection[collection.index(item)] = ' > ' + item + ' =='

for item in genre:
    genre[genre.index(item)] = ' < ' + item + ' > '

for item in modality:
# WHAT TO ANALYSE
# ===============
# comma separated list: {'KF100', KF1000', 'GSANG', 'ENDO100','DJTECJTOOLS60'}
collection = ['KF100', 'KF1000', 'GSANG', 'ENDO100', 'DJTECHTOOLS60']
# comma separated list: {'edm', 'non-edm'}
genre = ['edm']
# comma separated list: {'major', 'minor'}
modality = ['minor', 'major']
# Limit the analysis to n RANDOM songs. 0 analyses all the collection:
limit_analysis = 0
verbose = True
results_to_file = True

#create directory and unique time identifier
if results_to_file:
    uniqueTime = str(int(tiempo()))
    temp_folder = '/Users/angel/KeyDetection_' + uniqueTime
    os.mkdir(temp_folder)

# retrieve filenames according to the desired settings...
allfiles = os.listdir(audio_folder)
if '.DS_Store' in allfiles:
    allfiles.remove('.DS_Store')

for item in collection:
    collection[collection.index(item)] = ' > ' + item + ' =='

for item in genre:
    genre[genre.index(item)] = ' < ' + item + ' > '

for item in modality:
Beispiel #6
0
def key_detector():
    reloj()
    # create directory to write the results with an unique time id:
    if results_to_file or results_to_csv:
        uniqueTime = str(int(tiempo()))
        wd = os.getcwd()
        temp_folder = wd + '/KeyDetection_'+uniqueTime
        os.mkdir(temp_folder)
    if results_to_csv:
        import csv
        csvFile = open(temp_folder + '/Estimation_&_PCP.csv', 'w')
        lineWriter = csv.writer(csvFile, delimiter=',')
    # retrieve files and filenames according to the desired settings:
    if analysis_mode == 'title':
        allfiles = os.listdir(audio_folder)
        if '.DS_Store' in allfiles: allfiles.remove('.DS_Store')
        for item in collection: collection[collection.index(item)] = ' > ' + item + '.'
        for item in genre: genre[genre.index(item)] = ' < ' + item + ' > '
        for item in modality:modality[modality.index(item)] = ' ' + item + ' < '
        analysis_files = []
        for item in allfiles:
            if any(e1 for e1 in collection if e1 in item):
                if any(e2 for e2 in genre if e2 in item):
                    if any(e3 for e3 in modality if e3 in item):
                        analysis_files.append(item)
        song_instances = len(analysis_files)
        print song_instances, 'songs matching the selected criteria:'
        print collection, genre, modality
        if limit_analysis == 0:
            pass
        elif limit_analysis < song_instances:
            analysis_files = sample(analysis_files, limit_analysis)
            print "taking", limit_analysis, "random samples...\n"
    else:
        analysis_files = os.listdir(audio_folder)
        if '.DS_Store' in analysis_files:
            analysis_files.remove('.DS_Store')
        print len(analysis_files), '\nsongs in folder.\n'
        groundtruth_files = os.listdir(groundtruth_folder)
        if '.DS_Store' in groundtruth_files:
            groundtruth_files.remove('.DS_Store')
    # ANALYSIS
    # ========
    if verbose:
        print "ANALYSING INDIVIDUAL SONGS..."
        print "============================="
    if confusion_matrix:
        matrix = 24 * 24 * [0]
    mirex_scores = []
    for item in analysis_files:
        # INSTANTIATE ESSENTIA ALGORITHMS
        # ===============================
        loader = estd.MonoLoader(filename=audio_folder+'/'+item,
        						 sampleRate=sample_rate)
        cut    = estd.FrameCutter(frameSize=window_size,
                                  hopSize=hop_size)
        window = estd.Windowing(size=window_size,
                                type=window_type)
        rfft   = estd.Spectrum(size=window_size)
        sw     = estd.SpectralWhitening(maxFrequency=max_frequency,
                                        sampleRate=sample_rate)
        speaks = estd.SpectralPeaks(magnitudeThreshold=magnitude_threshold,
                                    maxFrequency=max_frequency,
                                    minFrequency=min_frequency,
                                    maxPeaks=max_peaks,
                                    sampleRate=sample_rate)
        hpcp   = estd.HPCP(bandPreset=band_preset,
                           harmonics=harmonics,
                           maxFrequency=max_frequency,
                           minFrequency=min_frequency,
                           nonLinear=non_linear,
                           normalized=normalize,
                           referenceFrequency=reference_frequency,
                           sampleRate=sample_rate,
                           size=hpcp_size,
                           splitFrequency=split_frequency,
                           weightType=weight_type,
                           windowSize=weight_window_size)
        key    = estd.Key(numHarmonics=num_harmonics,
                          pcpSize=hpcp_size,
                          profileType=profile_type,
                          slope=slope,
                          usePolyphony=use_polyphony,
                          useThreeChords=use_three_chords)
        # ACTUAL ANALYSIS
        # ===============
        audio = loader()
        duration = len(audio)
        if skip_first_minute and duration > (sample_rate*60):
            audio = audio[sample_rate*60:]
            duration = len(audio)
        if first_n_secs > 0:
            if duration > (first_n_secs * sample_rate):
                audio = audio[:first_n_secs * sample_rate]
                duration = len(audio)
        if avoid_edges > 0:
            initial_sample = (avoid_edges * duration) / 100
            final_sample = duration - initial_sample
            audio = audio[initial_sample:final_sample]
            duration = len(audio)
        number_of_frames = duration / hop_size
        chroma = []
        for bang in range(number_of_frames):
            spek = rfft(window(cut(audio)))
            p1, p2 = speaks(spek) # p1 are frequencies; p2 magnitudes
            if spectral_whitening:
                p2 = sw(spek, p1, p2)
            vector = hpcp(p1,p2)
            sum_vector = np.sum(vector)
            if sum_vector > 0:
                if shift_spectrum == False or shift_scope == 'average':
                    chroma.append(vector)
                elif shift_spectrum and shift_scope == 'frame':
                    vector = shift_vector(vector, hpcp_size)
                    chroma.append(vector)
                else:
                    print "shift_scope must be set to 'frame' or 'average'"
        chroma = np.mean(chroma, axis=0)
        if shift_spectrum and shift_scope == 'average':
            chroma = shift_vector(chroma, hpcp_size)
        estimation = key(chroma.tolist())
        result = estimation[0] + ' ' + estimation[1]
        confidence = estimation[2]
        if results_to_csv:
            chroma = list(chroma)
        # MIREX EVALUATION:
        # ================
        if analysis_mode == 'title':
            ground_truth = item[item.find(' = ')+3:item.rfind(' < ')]
            if verbose and confidence < confidence_threshold:
                print item[:item.rfind(' = ')]
                print 'G:', ground_truth, '|| P:',
            if results_to_csv:
                title = item[:item.rfind(' = ')]
                lineWriter.writerow([title, ground_truth, chroma[0], chroma[1], chroma[2], chroma[3], chroma[4], chroma[5], chroma[6], chroma[7], chroma[8], chroma[9], chroma[10], chroma[11], chroma[12], chroma[13], chroma[14], chroma[15], chroma[16], chroma[17], chroma[18], chroma[19], chroma[20], chroma[21], chroma[22], chroma[23], chroma[24], chroma[25], chroma[26], chroma[27], chroma[28], chroma[29], chroma[30], chroma[31], chroma[32], chroma[33], chroma[34], chroma[35], result])
            ground_truth = key_to_list(ground_truth)
            estimation = key_to_list(result)
            score = mirex_score(ground_truth, estimation)
            mirex_scores.append(score)
        else:
            filename_to_match = item[:item.rfind('.')] + '.txt'
            print filename_to_match
            if filename_to_match in groundtruth_files:
                groundtruth_file = open(groundtruth_folder+'/'+filename_to_match, 'r')
                ground_truth = groundtruth_file.readline()
                if "\t" in ground_truth:
                    ground_truth = re.sub("\t", " ", ground_truth)
                if results_to_csv:
                    lineWriter.writerow([filename_to_match, chroma[0], chroma[1], chroma[2], chroma[3], chroma[4], chroma[5], chroma[6], chroma[7], chroma[8], chroma[9], chroma[10], chroma[11], chroma[12], chroma[13], chroma[14], chroma[15], chroma[16], chroma[17], chroma[18], chroma[19], chroma[20], chroma[21], chroma[22], chroma[23], chroma[24], chroma[25], chroma[26], chroma[27], chroma[28], chroma[29], chroma[30], chroma[31], chroma[32], chroma[33], chroma[34], chroma[35], result])
                ground_truth = key_to_list(ground_truth)
                estimation = key_to_list(result)
                score = mirex_score(ground_truth, estimation)
                mirex_scores.append(score)
            else:
                print "FILE NOT FOUND... Skipping it from evaluation.\n"
                continue
        # CONFUSION MATRIX:
        # ================
        if confusion_matrix:
            xpos = (ground_truth[0] + (ground_truth[0] * 24)) + (-1*(ground_truth[1]-1) * 24 * 12)
            ypos = ((estimation[0] - ground_truth[0]) + (-1 * (estimation[1]-1) * 12))
            matrix[(xpos+ypos)] =+ matrix[(xpos+ypos)] + 1
        if verbose and confidence < confidence_threshold:
            print result, '(%.2f)' % confidence, '|| SCORE:', score, '\n'
        # WRITE RESULTS TO FILE:
        # =====================
        if results_to_file:
            with open(temp_folder + '/' + item[:-3]+'txt', 'w') as textfile:
                textfile.write(result)
                textfile.close()
    if results_to_csv:
        csvFile.close()
    print len(mirex_scores), "files analysed in", reloj(), "secs.\n"
    if confusion_matrix:
        matrix = np.matrix(matrix)
        matrix = matrix.reshape(24,24)
        print matrix
        if results_to_file:
            np.savetxt(temp_folder + '/_confusion_matrix.csv', matrix, fmt='%i', delimiter=',', header='C,C#,D,Eb,E,F,F#,G,G#,A,Bb,B,Cm,C#m,Dm,Ebm,Em,Fm,F#m,Gm,G#m,Am,Bbm,Bm')
    # MIREX RESULTS
    # =============
    evaluation_results = mirex_evaluation(mirex_scores)
    # WRITE INFO TO FILE
    # ==================
    if results_to_file:
        settings = "SETTINGS\n========\nAvoid edges ('%' of duration disregarded at both ends (0 = complete)) = "+str(avoid_edges)+"\nfirst N secs = "+str(first_n_secs)+"\nshift spectrum to fit tempered scale = "+str(shift_spectrum)+"\nspectral whitening = "+str(spectral_whitening)+"\nsample rate = "+str(sample_rate)+"\nwindow size = "+str(window_size)+"\nhop size = "+str(hop_size)+"\nmagnitude threshold = "+str(magnitude_threshold)+"\nminimum frequency = "+str(min_frequency)+"\nmaximum frequency = "+str(max_frequency)+"\nmaximum peaks = "+str(max_peaks)+"\nband preset = "+str(band_preset)+"\nsplit frequency = "+str(split_frequency)+"\nharmonics = "+str(harmonics)+"\nnon linear = "+str(non_linear)+"\nnormalize = "+str(normalize)+"\nreference frequency = "+str(reference_frequency)+"\nhpcp size = "+str(hpcp_size)+"\nweigth type = "+weight_type+"\nweight window size in semitones = "+str(weight_window_size)+"\nharmonics key = "+str(num_harmonics)+"\nslope = "+str(slope)+"\nprofile = "+profile_type+"\npolyphony = "+str(use_polyphony)+"\nuse three chords = "+str(use_three_chords)
        results_for_file = "\n\nEVALUATION RESULTS\n==================\nCorrect: "+str(evaluation_results[0])+"\nFifth:  "+str(evaluation_results[1])+"\nRelative: "+str(evaluation_results[2])+"\nParallel: "+str(evaluation_results[3])+"\nError: "+str(evaluation_results[4])+"\nWeighted: "+str(evaluation_results[5])
        write_to_file = open(temp_folder + '/_SUMMARY.txt', 'w')
        write_to_file.write(settings)
        write_to_file.write(results_for_file)
        if analysis_mode == 'title':
            corpus = "\n\nANALYSIS CORPUS\n===============\n" + str(collection) + '\n' + str(genre) + '\n' + str(modality) + '\n\n' + str(len(mirex_scores)) + " files analysed.\n"
            write_to_file.write(corpus)
        write_to_file.close()
Beispiel #7
0
               (subrayar, sColor, v,
               dConc.get(sConc, {'des':'NO TENGO DESCRIPCION'})['des'] + '-' + sNuc,
               FG.formateaNumero(dicc[v][0]), FG.formateaNumero(dicc[v][1], 2),
               FG.formateaNumero(dicc[v][2], 2), sObs, CO.FIN)

    return st


# FIN funcion mostrarConceptos

# Inicio principal
sConc = '563'
dConc = CC.creaDicConceptos()
# 1:mes(1-12); 2:dia(1-31); 3:hora(0-23); 4:min(0-59); 5:seg(0-60);
# 6:dia sem(0 a 6 (o lunes)); 7:dia a#o(1-366); 8:Verano(-1,0,1,-1)
sMes = str(tiempo()[1])
sAno = str(tiempo()[0])
if not bMovil:
    if 1 < len(sys.argv):
        mes = sys.argv[1]
        if not mes.isdigit() or 1 > int(mes) or 12 < int(mes):
            print("%sEl primer prametro deberia ser el mes y esta errado.%s" %
                  (CO.ROJO, CO.FIN))
            sys.exit()
        if 2 < len(sys.argv):
            nombArchivo = sys.argv[2]
        else:
            nombArchivo = 'IPAS'
        if 3 < len(sys.argv) and sys.argv[3].isdigit():
            ano = sys.argv[3]
        else:
Beispiel #8
0
def key_detector():
    reloj()
    # create directory to write the results with an unique time id:
    if results_to_file or results_to_csv:
        uniqueTime = str(int(tiempo()))
        wd = os.getcwd()
        temp_folder = wd + '/KeyDetection_' + uniqueTime
        os.mkdir(temp_folder)
    if results_to_csv:
        import csv
        csvFile = open(temp_folder + '/Estimation_&_PCP.csv', 'w')
        lineWriter = csv.writer(csvFile, delimiter=',')
    # retrieve files and filenames according to the desired settings:
    if analysis_mode == 'title':
        allfiles = os.listdir(audio_folder)
        if '.DS_Store' in allfiles: allfiles.remove('.DS_Store')
        for item in collection:
            collection[collection.index(item)] = ' > ' + item + '.'
        for item in genre:
            genre[genre.index(item)] = ' < ' + item + ' > '
        for item in modality:
            modality[modality.index(item)] = ' ' + item + ' < '
        analysis_files = []
        for item in allfiles:
            if any(e1 for e1 in collection if e1 in item):
                if any(e2 for e2 in genre if e2 in item):
                    if any(e3 for e3 in modality if e3 in item):
                        analysis_files.append(item)
        song_instances = len(analysis_files)
        print song_instances, 'songs matching the selected criteria:'
        print collection, genre, modality
        if limit_analysis == 0:
            pass
        elif limit_analysis < song_instances:
            analysis_files = sample(analysis_files, limit_analysis)
            print "taking", limit_analysis, "random samples...\n"
    else:
        analysis_files = os.listdir(audio_folder)
        if '.DS_Store' in analysis_files:
            analysis_files.remove('.DS_Store')
        print len(analysis_files), '\nsongs in folder.\n'
        groundtruth_files = os.listdir(groundtruth_folder)
        if '.DS_Store' in groundtruth_files:
            groundtruth_files.remove('.DS_Store')
    # ANALYSIS
    # ========
    if verbose:
        print "ANALYSING INDIVIDUAL SONGS..."
        print "============================="
    if confusion_matrix:
        matrix = 24 * 24 * [0]
    mirex_scores = []
    for item in analysis_files:
        # INSTANTIATE ESSENTIA ALGORITHMS
        # ===============================
        loader = estd.MonoLoader(filename=audio_folder + '/' + item,
                                 sampleRate=sample_rate)
        cut = estd.FrameCutter(frameSize=window_size, hopSize=hop_size)
        window = estd.Windowing(size=window_size, type=window_type)
        rfft = estd.Spectrum(size=window_size)
        sw = estd.SpectralWhitening(maxFrequency=max_frequency,
                                    sampleRate=sample_rate)
        speaks = estd.SpectralPeaks(magnitudeThreshold=magnitude_threshold,
                                    maxFrequency=max_frequency,
                                    minFrequency=min_frequency,
                                    maxPeaks=max_peaks,
                                    sampleRate=sample_rate)
        hpcp = estd.HPCP(bandPreset=band_preset,
                         harmonics=harmonics,
                         maxFrequency=max_frequency,
                         minFrequency=min_frequency,
                         nonLinear=non_linear,
                         normalized=normalize,
                         referenceFrequency=reference_frequency,
                         sampleRate=sample_rate,
                         size=hpcp_size,
                         splitFrequency=split_frequency,
                         weightType=weight_type,
                         windowSize=weight_window_size)
        key = estd.Key(numHarmonics=num_harmonics,
                       pcpSize=hpcp_size,
                       profileType=profile_type,
                       slope=slope,
                       usePolyphony=use_polyphony,
                       useThreeChords=use_three_chords)
        # ACTUAL ANALYSIS
        # ===============
        audio = loader()
        duration = len(audio)
        if skip_first_minute and duration > (sample_rate * 60):
            audio = audio[sample_rate * 60:]
            duration = len(audio)
        if first_n_secs > 0:
            if duration > (first_n_secs * sample_rate):
                audio = audio[:first_n_secs * sample_rate]
                duration = len(audio)
        if avoid_edges > 0:
            initial_sample = (avoid_edges * duration) / 100
            final_sample = duration - initial_sample
            audio = audio[initial_sample:final_sample]
            duration = len(audio)
        number_of_frames = duration / hop_size
        chroma = []
        for bang in range(number_of_frames):
            spek = rfft(window(cut(audio)))
            p1, p2 = speaks(spek)  # p1 are frequencies; p2 magnitudes
            if spectral_whitening:
                p2 = sw(spek, p1, p2)
            vector = hpcp(p1, p2)
            sum_vector = np.sum(vector)
            if sum_vector > 0:
                if shift_spectrum == False or shift_scope == 'average':
                    chroma.append(vector)
                elif shift_spectrum and shift_scope == 'frame':
                    vector = shift_vector(vector, hpcp_size)
                    chroma.append(vector)
                else:
                    print "shift_scope must be set to 'frame' or 'average'"
        chroma = np.mean(chroma, axis=0)
        if shift_spectrum and shift_scope == 'average':
            chroma = shift_vector(chroma, hpcp_size)
        estimation = key(chroma.tolist())
        result = estimation[0] + ' ' + estimation[1]
        confidence = estimation[2]
        if results_to_csv:
            chroma = list(chroma)
        # MIREX EVALUATION:
        # ================
        if analysis_mode == 'title':
            ground_truth = item[item.find(' = ') + 3:item.rfind(' < ')]
            if verbose and confidence < confidence_threshold:
                print item[:item.rfind(' = ')]
                print 'G:', ground_truth, '|| P:',
            if results_to_csv:
                title = item[:item.rfind(' = ')]
                lineWriter.writerow([
                    title, ground_truth, chroma[0], chroma[1], chroma[2],
                    chroma[3], chroma[4], chroma[5], chroma[6], chroma[7],
                    chroma[8], chroma[9], chroma[10], chroma[11], chroma[12],
                    chroma[13], chroma[14], chroma[15], chroma[16], chroma[17],
                    chroma[18], chroma[19], chroma[20], chroma[21], chroma[22],
                    chroma[23], chroma[24], chroma[25], chroma[26], chroma[27],
                    chroma[28], chroma[29], chroma[30], chroma[31], chroma[32],
                    chroma[33], chroma[34], chroma[35], result
                ])
            ground_truth = key_to_list(ground_truth)
            estimation = key_to_list(result)
            score = mirex_score(ground_truth, estimation)
            mirex_scores.append(score)
        else:
            filename_to_match = item[:item.rfind('.')] + '.txt'
            print filename_to_match
            if filename_to_match in groundtruth_files:
                groundtruth_file = open(
                    groundtruth_folder + '/' + filename_to_match, 'r')
                ground_truth = groundtruth_file.readline()
                if "\t" in ground_truth:
                    ground_truth = re.sub("\t", " ", ground_truth)
                if results_to_csv:
                    lineWriter.writerow([
                        filename_to_match, chroma[0], chroma[1], chroma[2],
                        chroma[3], chroma[4], chroma[5], chroma[6], chroma[7],
                        chroma[8], chroma[9], chroma[10], chroma[11],
                        chroma[12], chroma[13], chroma[14], chroma[15],
                        chroma[16], chroma[17], chroma[18], chroma[19],
                        chroma[20], chroma[21], chroma[22], chroma[23],
                        chroma[24], chroma[25], chroma[26], chroma[27],
                        chroma[28], chroma[29], chroma[30], chroma[31],
                        chroma[32], chroma[33], chroma[34], chroma[35], result
                    ])
                ground_truth = key_to_list(ground_truth)
                estimation = key_to_list(result)
                score = mirex_score(ground_truth, estimation)
                mirex_scores.append(score)
            else:
                print "FILE NOT FOUND... Skipping it from evaluation.\n"
                continue
        # CONFUSION MATRIX:
        # ================
        if confusion_matrix:
            xpos = (ground_truth[0] +
                    (ground_truth[0] * 24)) + (-1 *
                                               (ground_truth[1] - 1) * 24 * 12)
            ypos = ((estimation[0] - ground_truth[0]) +
                    (-1 * (estimation[1] - 1) * 12))
            matrix[(xpos + ypos)] = +matrix[(xpos + ypos)] + 1
        if verbose and confidence < confidence_threshold:
            print result, '(%.2f)' % confidence, '|| SCORE:', score, '\n'
        # WRITE RESULTS TO FILE:
        # =====================
        if results_to_file:
            with open(temp_folder + '/' + item[:-3] + 'txt', 'w') as textfile:
                textfile.write(result)
                textfile.close()
    if results_to_csv:
        csvFile.close()
    print len(mirex_scores), "files analysed in", reloj(), "secs.\n"
    if confusion_matrix:
        matrix = np.matrix(matrix)
        matrix = matrix.reshape(24, 24)
        print matrix
        if results_to_file:
            np.savetxt(
                temp_folder + '/_confusion_matrix.csv',
                matrix,
                fmt='%i',
                delimiter=',',
                header=
                'C,C#,D,Eb,E,F,F#,G,G#,A,Bb,B,Cm,C#m,Dm,Ebm,Em,Fm,F#m,Gm,G#m,Am,Bbm,Bm'
            )
    # MIREX RESULTS
    # =============
    evaluation_results = mirex_evaluation(mirex_scores)
    # WRITE INFO TO FILE
    # ==================
    if results_to_file:
        settings = "SETTINGS\n========\nAvoid edges ('%' of duration disregarded at both ends (0 = complete)) = " + str(
            avoid_edges
        ) + "\nfirst N secs = " + str(
            first_n_secs
        ) + "\nshift spectrum to fit tempered scale = " + str(
            shift_spectrum
        ) + "\nspectral whitening = " + str(
            spectral_whitening
        ) + "\nsample rate = " + str(sample_rate) + "\nwindow size = " + str(
            window_size
        ) + "\nhop size = " + str(hop_size) + "\nmagnitude threshold = " + str(
            magnitude_threshold
        ) + "\nminimum frequency = " + str(
            min_frequency
        ) + "\nmaximum frequency = " + str(
            max_frequency
        ) + "\nmaximum peaks = " + str(max_peaks) + "\nband preset = " + str(
            band_preset
        ) + "\nsplit frequency = " + str(
            split_frequency
        ) + "\nharmonics = " + str(harmonics) + "\nnon linear = " + str(
            non_linear
        ) + "\nnormalize = " + str(
            normalize
        ) + "\nreference frequency = " + str(
            reference_frequency
        ) + "\nhpcp size = " + str(
            hpcp_size
        ) + "\nweigth type = " + weight_type + "\nweight window size in semitones = " + str(
            weight_window_size
        ) + "\nharmonics key = " + str(num_harmonics) + "\nslope = " + str(
            slope) + "\nprofile = " + profile_type + "\npolyphony = " + str(
                use_polyphony) + "\nuse three chords = " + str(
                    use_three_chords)
        results_for_file = "\n\nEVALUATION RESULTS\n==================\nCorrect: " + str(
            evaluation_results[0]) + "\nFifth:  " + str(
                evaluation_results[1]) + "\nRelative: " + str(
                    evaluation_results[2]) + "\nParallel: " + str(
                        evaluation_results[3]) + "\nError: " + str(
                            evaluation_results[4]) + "\nWeighted: " + str(
                                evaluation_results[5])
        write_to_file = open(temp_folder + '/_SUMMARY.txt', 'w')
        write_to_file.write(settings)
        write_to_file.write(results_for_file)
        if analysis_mode == 'title':
            corpus = "\n\nANALYSIS CORPUS\n===============\n" + str(
                collection) + '\n' + str(
                    genre) + '\n' + str(modality) + '\n\n' + str(
                        len(mirex_scores)) + " files analysed.\n"
            write_to_file.write(corpus)
        write_to_file.close()