# nbi:hide_in
# from IPython.display import Audio
# import numpy as np
# # nbi:hide_in
# signal = np.random.random(750)
# Audio(signal, rate=250)
# nbi:hide_in
from music21 import *
import os
from collections import defaultdict
from pprint import *
import numpy as np
from ipywidgets import interact


PITCHES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
OCTAVES = 7 #1 through 7
base_dir = 'wikifonia_en_chords_lyrics'

""" 
Generates transitiion matrix for first 10 C Major pieces
Currently filters for CM, can add in transposition later
"""
def generateTransitionMatrix(base_dir, load=True):
    path = 'widgets/pitch_to_pitch.npy'
    if load:
        with open(path, 'rb') as f:
            a = np.load(f)
        return a
matrix = generateTransitionMatrix(base_dir, load=True)

def all_notes():
    notes = []
    for o in range(OCTAVES):
        for p in PITCHES:

            notes.append(p + str(o+1))
    return notes
ALL_NOTES = all_notes()
ALL_NOTES[36]

def noteToIndex(n):
    return int(n.pitch.ps)-24

def getNext(matrix, n):
    idx = noteToIndex(n)
    transitions = matrix[idx,:]
    choice = np.random.choice(a=ALL_NOTES, p=transitions)
    return note.Note(choice)

def generateMelodyHelper(matrix, length):
    notes = []
    s = stream.Stream()
    start_note = note.Note('C4')
    n = start_note
    for i in range(length):
        s.append(n)
        n = getNext(matrix, n)
    return s


def generateMelody(length, random_seed):
    np.random.seed(random_seed)
    s = generateMelodyHelper(matrix, length)
    for i in s:
        print(i)

interact(generateMelody, length=(5, 15), random_seed=(0,100));
# nbi:hide_in