-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnote.py
164 lines (146 loc) · 5.22 KB
/
note.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
from collections import deque
from logging import getLogger
import re
from error import VmccError
logger = getLogger(__name__)
_REGEX_NOTE = re.compile(''.join([
r'(?:'
r'(?P<signature>[cdfg](?:[ie]s)?|[ea](?:i?s)?|h(?:is)?|b)(?P<octave>[0-9]*)',
r'|(?P<octaveset>o[0-9]+)|(?P<octaveinc><)|(?P<octavedec>>)|(?P<repeat>-)|(?P<tacet>\.)',
r'|(?P<lpar>\()|(?P<rpar>\)(?P<rpar_scale>[0-9]*))',
r')\s*',
]))
_KEY_MAP = {
'c': 0, 'd': 2, 'e': 4, 'f': 5, 'g': 7, 'a': 9, 'b': 10, 'h': 11,
}
_SCALE_NAMES = [
'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B',
]
def scale_name(scale_key, pitchbend=()):
octave = scale_key // 12
name = _SCALE_NAMES[scale_key % 12]
pitchbend = ''.join(['_%d' % bend for bend in pitchbend])
return '%s%d%s' % (name, octave, pitchbend)
class Note:
def __init__(self, signature, octave, length, pos):
self.signature = signature
self.octave = octave
self.length = length
self.pos = pos
@property
def displaytext(self):
return f"<{self.pos}:{self.length}@{self.signature}{self.octave}>"
@property
def is_normal(self):
return self.octave is not None
@property
def is_repeat(self):
return self.signature == '-'
@property
def is_tacet(self):
return self.signature == '.'
def __add__(self, other):
unifiable = False
if self.is_normal and other.is_repeat:
unifiable = True
elif self.is_tacet and other.is_tacet:
unifiable = True
if not unifiable:
return None
return Note(self.signature, self.octave, self.length + other.length, self.pos)
def get_key(self, env, default=None):
if not self.is_normal:
return default
signature = self.signature
key = self.octave * 12 + _KEY_MAP[signature[0]]
if signature.endswith('is'):
key += 1
elif signature.endswith('s'):
key -= 1
if key < env.lowest_key:
return env.lowest_key
if key > env.highest_key:
return env.highest_key
return key
@classmethod
def parse_melody(cls, env, text, lineno=None, chars=1):
if lineno is None:
lineno = env.lineno
textlen = len(text)
pos = 0
melody = deque()
par = None
while pos < textlen:
item = text[pos:]
# logger.debug("item:%s", item)
m = _REGEX_NOTE.match(item)
if not m:
raise VmccError(f"L{lineno}:{pos + chars}:'{item}' unrecognizable")
# logger.debug("note-parse: %s q: %s par: %s", m.group(), [n.displaytext for n in melody], par and [n.displaytext for n in par])
d = m.groupdict()
# logger.debug("d: %s", d)
signature = d['signature']
note_pos = pos + chars
pos += m.end()
if par is None:
scale = env.tick_unit
q = melody
else:
scale = None
q = par
if signature:
octavestr = d['octave']
octave = int(octavestr) if octavestr else env.octave
q.append(cls(signature, octave, scale, note_pos))
elif d['octaveinc']:
env.octave += 1
elif d['octavedec']:
env.octave -= 1
elif d['repeat']:
q.append(cls('-', None, scale, note_pos))
elif d['tacet']:
q.append(cls('.', None, scale, note_pos))
elif d['lpar']:
if par is not None:
raise VmccError(f"L{lineno}:{pos + chars}:'{item}' nested parentheses are not supported")
par = []
elif d['rpar']:
if par is None:
raise VmccError(f"L{lineno}:{pos + chars}:'{item}' unbalanced right parenthesis")
if not par:
raise VmccError(f"L{lineno}:{pos + chars}:'{item}' empty parentheses")
rpar_scale = d['rpar_scale']
if rpar_scale:
numerator = int(rpar_scale) or 1
else:
numerator = 1
resource = numerator * env.tick_unit
rest = len(par)
for note in par:
if rest == 1:
subscale = resource
else:
subscale = round(resource / rest)
note.length = subscale
melody.append(note)
resource -= subscale
rest -= 1
par = None
else:
octaveset = d['octaveset']
assert octaveset
env.octave = int(octaveset[2:])
assert par is None
# logger.debug(f"notes: {[n.displaytext for n in melody]}")
return melody
class Notes:
@classmethod
def unify(cls, notes):
unified_notes = deque([notes[0]])
for note in notes[1:]:
unified = unified_notes[-1] + note
if unified:
unified_notes[-1] = unified
else:
unified_notes.append(note)
return unified_notes