Skip to content

Instantly share code, notes, and snippets.

@beng
Last active December 27, 2015 06:49
Show Gist options
  • Save beng/7284722 to your computer and use it in GitHub Desktop.
Save beng/7284722 to your computer and use it in GitHub Desktop.
markov chain to preserve groupings
import pickle
import music21
from redis import Redis
from markov import MarkovChain
r = Redis(db=2)
def music_obj(path):
return music21.converter.parse(path)
def parse(mobj, traits=['chord']):
"""Given a music21 object and a list of traits,
extract those traits from the music21 object, while:
-preserving order
-keeping a nested list of each trait(s) due to chords
>>> [[A4], [B5], [B5, C#4, F#3]]
"""
_mobj = filter(lambda x: type(x).__name__.lower() in traits, mobj.recurse())
elements = [[pitch for pitch in element.pitches] for element in _mobj]
return map(lambda pitches:
map(lambda pitch: {
'note': pitch.nameWithOctave,
'duration': pitch.duration.type,
'quarter_length': pitch.duration.quarterLength
}, pitches),
elements)
def extract_notes(mapping):
return map(lambda traits: map(lambda key: key['note'], traits) , mapping)
def generate_markov(corpus, size, nodes):
def markov_pitch():
# we use `::` to denote grouping of pairs, ie chords, individual notes
# we use `:` to denote separation between groupings
return ':'.join([next(walk_corpus()) for k in xrange(size)]).split('::')
def walk_corpus():
chain = MarkovChain(nodes)
chain.add_sequence(corpus)
return chain.walk()
return map(lambda x: x.split(':'), markov_pitch())
def cache_set(name, key, value, serialize=None):
if serialize:
value = pickle.dumps(value)
return r.hset(name, key, value)
def cache_get(name):
cache = r.hgetall(name)
mapping = {}
for k, v in cache.items():
try:
mapping[k] = pickle.loads(v)
except Exception:
print "can de-pickle, loading as is"
mapping[k] = v
return mapping
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment