/
carnatic_util.py
67 lines (50 loc) · 1.43 KB
/
carnatic_util.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/usr/bin/evn python
import util
"""A module to help read and carnatic notation"""
def ConvertString(s):
""" Converts a string of the form
g , g, r , , ,
[(g, 8), (g, 8), (r, 16)]
(assuming tempo = 4) """
return ConvertLengthToTempo(CollectNotes(s))
def CollectNotes(s):
""" Collects notes and ,s to form (notes, length)
Converts
g , g, r , , ,
to [(g, 2) (g, 2) (r, 4)]"""
standard_length = 1
li = s.split()
notes = []
previous_note = ''
previous_length = 0
for c in li:
if c != ',':
notes.append((c, standard_length))
if c == ',':
try:
(previous_note, previous_length) = notes[-1]
except IndexError:
print "Does the piece start with a , ? Error."
return
notes[-1] = (previous_note, previous_length+standard_length)
return notes
def ConvertLengthToTempo(notes):
# find the least common multiple of all the lengths
note_lengths = [b for (a, b) in notes]
lcm = util.lcm_many(*note_lengths)
tempo_notes = []
for (a, b) in notes:
tempo_notes.append((a, lcm/b))
return tempo_notes
def PreProcessScore(s):
""" Remove all the | and the || """
s = s.replace("|", " ")
s = s.replace(" ", " ")
return s
def ReadFromFile(f):
""" Reads music from a file handle, preprocesses,
converts the notes into tempo format and returns"""
s = f.read()
s = PreProcessScore(s)
l = ConvertString(s)
return l