# Path: brain.py
# def _project(audio_id, sound_to_face, NAP, video_producer):
#     stride = IO.VIDEO_SAMPLE_TIME / (IO.NAP_RATE/IO.NAP_STRIDE)
#     length = np.floor(NAP.shape[0]*.8).astype('int')
#     NAP = NAP[:length:stride]
#     try: 
#         face_id = np.random.choice(sound_to_face[audio_id])
#         tarantino = utils.load_esn(video_producer[(audio_id, face_id)])
#         return tarantino(NAP)
#     except:
#         matches = filter(lambda key: key[0] == audio_id, video_producer.keys())
#         if len(matches):
#             tarantino = utils.load_esn(video_producer[random.choice(matches)])
#         else:
#             tarantino = utils.load_esn(video_producer[random.choice(video_producer.keys())])
#         return tarantino(NAP)
# 
# def _extract_NAP(segstart, segend, soundfile, suffix='cochlear'):
#     new_sentence = utils.csv_to_array(soundfile + suffix)
#     audio_segments = utils.get_segments(soundfile)
#     segstart_norm = int(np.rint(new_sentence.shape[0]*segstart/audio_segments[-1]))
#     segend_norm = int(np.rint(new_sentence.shape[0]*segend/audio_segments[-1]))
#     return utils.trim_right(new_sentence[segstart_norm:segend_norm])
# 
# def _three_amigos(context, host):
#     stateQ = context.socket(zmq.SUB)
#     stateQ.connect('tcp://{}:{}'.format(host, IO.STATE))
#     stateQ.setsockopt(zmq.SUBSCRIBE, b'') 
# 
#     eventQ = context.socket(zmq.SUB)
#     eventQ.connect('tcp://{}:{}'.format(host, IO.EVENT))
#     eventQ.setsockopt(zmq.SUBSCRIBE, b'') 
# 
#     brainQ = context.socket(zmq.PUSH)
#     brainQ.connect('tcp://{}:{}'.format(host, IO.BRAIN))
# 
#     return stateQ, eventQ, brainQ


import multiprocessing as mp
import sys
import glob
import cPickle as pickle
import time
import os
import itertools
import random
import numpy as np
import zmq
import utils
import IO
import association
import my_sai_test as mysai
import myCsoundAudioOptions
        import matplotlib.pyplot as plt
        import matplotlib.pyplot as plt
from uuid import uuid4
from collections import deque
from subprocess import call
from collections import namedtuple
from scipy.stats import itemfreq
from scipy.cluster.vq import kmeans, vq
from brain import _project, _extract_NAP, _three_amigos
                        if dur <= 0: dur = totaldur
                        voice1 = 'playfile {} {} {} {} {} {} {} {} {}'.format(voiceChannel, voiceType1, start, soundfile, speed, segstart, segend, amp, maxamp)
                        #start += dur # if we want to create a 'score section' for Csound, update start time to make segments into a contiguous sentence
                        wordSpacing1 = wordSpace1 + np.random.random()*wordSpaceDev1
                        nextTime1 += (dur/speed)+wordSpacing1
                        #print 'voice 2 ready to play', secondaryStream[i], i
                        if enableVoice2:
                            word_id2 = secondaryStream[i]
                            #print 'voice 2 playing', secondaryStream[i]
                            soundfile2 = np.random.choice(wavs[word_id2])
                            voiceChannel2 = 2
                            start2 = 0.7 #  set delay between voice 1 and 2
                            speed2 = 0.7
                            amp2 = -10 # voice amplitude in dB
                            try:
                                segstart2, segend2 = wav_audio_ids[(soundfile2, word_id2)]
                                dur2 = segend2-segstart2
                                #totalDur2, maxamp2 = utils.getSoundParmFromFile(soundfile2)
                                _,totalDur2,maxamp2,_ = utils.getSoundInfo(soundfile)
                                if dur2 <= 0: dur2 = totalDur2
                                voice2 = 'playfile {} {} {} {} {} {} {} {} {}'.format(voiceChannel2, voiceType2, start2, soundfile2, speed2, segstart2, segend2, amp2, maxamp2)
                                wordSpacing2 = wordSpace2 + np.random.random()*wordSpaceDev2
                                nextTime2 += (dur2/speed2)+wordSpacing2
                            except:
                                voice2 = ''
                                utils.print_exception('VOICE 2 tried to access an illegal soundfile/audio_id combination.')
                            #enableVoice2 = 0
                        # trig another word in voice 2 only if word 2 has finished playing (and sync to start of voice 1)
                        if nextTime1 > nextTime2: enableVoice2 = 1 


# Path: brain.py
# def _project(audio_id, sound_to_face, NAP, video_producer):
#     stride = IO.VIDEO_SAMPLE_TIME / (IO.NAP_RATE/IO.NAP_STRIDE)
#     length = np.floor(NAP.shape[0]*.8).astype('int')
#     NAP = NAP[:length:stride]
#     try: 
#         face_id = np.random.choice(sound_to_face[audio_id])
#         tarantino = utils.load_esn(video_producer[(audio_id, face_id)])
#         return tarantino(NAP)
#     except:
#         matches = filter(lambda key: key[0] == audio_id, video_producer.keys())
#         if len(matches):
#             tarantino = utils.load_esn(video_producer[random.choice(matches)])
#         else:
#             tarantino = utils.load_esn(video_producer[random.choice(video_producer.keys())])
#         return tarantino(NAP)
# 
# def _extract_NAP(segstart, segend, soundfile, suffix='cochlear'):
#     new_sentence = utils.csv_to_array(soundfile + suffix)
#     audio_segments = utils.get_segments(soundfile)
#     segstart_norm = int(np.rint(new_sentence.shape[0]*segstart/audio_segments[-1]))
#     segend_norm = int(np.rint(new_sentence.shape[0]*segend/audio_segments[-1]))
#     return utils.trim_right(new_sentence[segstart_norm:segend_norm])
# 
# def _three_amigos(context, host):
#     stateQ = context.socket(zmq.SUB)
#     stateQ.connect('tcp://{}:{}'.format(host, IO.STATE))
#     stateQ.setsockopt(zmq.SUBSCRIBE, b'') 
# 
#     eventQ = context.socket(zmq.SUB)
#     eventQ.connect('tcp://{}:{}'.format(host, IO.EVENT))
#     eventQ.setsockopt(zmq.SUBSCRIBE, b'') 
# 
#     brainQ = context.socket(zmq.PUSH)
#     brainQ.connect('tcp://{}:{}'.format(host, IO.BRAIN))
# 
#     return stateQ, eventQ, brainQ


# Path: altbrain.py
import multiprocessing as mp
import sys
import glob
import cPickle as pickle
import time
import os
import itertools
import random
import numpy as np
import zmq
import utils
import IO
import association
import my_sai_test as mysai
import myCsoundAudioOptions
        import matplotlib.pyplot as plt
        import matplotlib.pyplot as plt
from uuid import uuid4
from collections import deque
from subprocess import call
from collections import namedtuple
from scipy.stats import itemfreq
from scipy.cluster.vq import kmeans, vq
from brain import _project, _extract_NAP, _three_amigos

                        if dur <= 0: dur = totaldur
                        voice1 = 'playfile {} {} {} {} {} {} {} {} {}'.format(voiceChannel, voiceType1, start, soundfile, speed, segstart, segend, amp, maxamp)
                        #start += dur # if we want to create a 'score section' for Csound, update start time to make segments into a contiguous sentence
                        wordSpacing1 = wordSpace1 + np.random.random()*wordSpaceDev1
                        nextTime1 += (dur/speed)+wordSpacing1
                        #print 'voice 2 ready to play', secondaryStream[i], i
                        if enableVoice2:
                            word_id2 = secondaryStream[i]
                            #print 'voice 2 playing', secondaryStream[i]
                            soundfile2 = np.random.choice(wavs[word_id2])
                            voiceChannel2 = 2
                            start2 = 0.7 #  set delay between voice 1 and 2
                            speed2 = 0.7
                            amp2 = -10 # voice amplitude in dB
                            try:
                                segstart2, segend2 = wav_audio_ids[(soundfile2, word_id2)]
                                dur2 = segend2-segstart2
                                #totalDur2, maxamp2 = utils.getSoundParmFromFile(soundfile2)
                                _,totalDur2,maxamp2,_ = utils.getSoundInfo(soundfile)
                                if dur2 <= 0: dur2 = totalDur2
                                voice2 = 'playfile {} {} {} {} {} {} {} {} {}'.format(voiceChannel2, voiceType2, start2, soundfile2, speed2, segstart2, segend2, amp2, maxamp2)
                                wordSpacing2 = wordSpace2 + np.random.random()*wordSpaceDev2
                                nextTime2 += (dur2/speed2)+wordSpacing2
                            except:
                                voice2 = ''
                                utils.print_exception('VOICE 2 tried to access an illegal soundfile/audio_id combination.')
                            #enableVoice2 = 0
                        # trig another word in voice 2 only if word 2 has finished playing (and sync to start of voice 1)
                        if nextTime1 > nextTime2: enableVoice2 = 1 


                        projection = _project(audio_id, sound_to_face, NAP, video_producer)