9 self._name = 'xml_node'
11 self._attribute_dict = {}
13 def get_parent (self):
17 return self._parent.get_typed_children (self.__class__)[0] == self
28 if not self._children:
31 return ''.join ([c.get_text () for c in self._children])
33 def message (self, msg):
38 print ' In: <%s %s>' % (p._name, ' '.join (['%s=%s' % item for item in p._attribute_dict.items()]))
41 def get_typed_children (self, klass):
42 return [c for c in self._children if isinstance(c, klass)]
44 def get_named_children (self, nm):
45 return self.get_typed_children (class_dict[nm])
47 def get_named_child (self, nm):
48 return self.get_maybe_exist_named_child (nm)
50 def get_children (self, predicate):
51 return [c for c in self._children if predicate(c)]
53 def get_all_children (self):
56 def get_maybe_exist_named_child (self, name):
57 return self.get_maybe_exist_typed_child (class_dict[name])
59 def get_maybe_exist_typed_child (self, klass):
60 cn = self.get_typed_children (klass)
66 raise "More than 1 child", klass
68 def get_unique_typed_child (self, klass):
69 cn = self.get_typed_children(klass)
72 raise 'Child is not unique for', (klass, 'found', cn)
76 class Music_xml_node (Xml_node):
78 Xml_node.__init__ (self)
79 self.duration = Rational (0)
80 self.start = Rational (0)
83 class Duration (Music_xml_node):
84 def get_length (self):
85 dur = int (self.get_text ()) * Rational (1,4)
88 class Hash_comment (Music_xml_node):
91 class Pitch (Music_xml_node):
93 ch = self.get_unique_typed_child (class_dict[u'step'])
94 step = ch.get_text ().strip ()
96 def get_octave (self):
97 ch = self.get_unique_typed_child (class_dict[u'octave'])
99 step = ch.get_text ().strip ()
102 def get_alteration (self):
103 ch = self.get_maybe_exist_typed_child (class_dict[u'alter'])
106 alter = int (ch.get_text ().strip ())
109 class Measure_element (Music_xml_node):
110 def get_voice_id (self):
111 voice_id = self.get_maybe_exist_named_child ('voice')
113 return voice_id.get_text ()
118 cn = self._parent.get_typed_children (self.__class__)
119 cn = [c for c in cn if c.get_voice_id () == self.get_voice_id ()]
122 class Attributes (Measure_element):
124 Measure_element.__init__ (self)
127 def set_attributes_from_previous (self, dict):
128 self._dict.update (dict)
130 def read_self (self):
131 for c in self.get_all_children ():
132 self._dict[c.get_name()] = c
134 def get_named_attribute (self, name):
135 return self._dict[name]
137 def get_measure_length (self):
138 (n,d) = self.get_time_signature ()
139 return Rational (n,d)
141 def get_time_signature (self):
142 "return time sig as a (beat, beat-type) tuple"
145 mxl = self.get_named_attribute ('time')
147 beats = mxl.get_maybe_exist_named_child ('beats')
148 type = mxl.get_maybe_exist_named_child ('beat-type')
149 return (int (beats.get_text ()),
150 int (type.get_text ()))
152 print 'error: requested time signature, but time sig unknown'
155 def get_clef_sign (self):
156 mxl = self.get_named_attribute ('clef')
157 sign = mxl.get_maybe_exist_named_child ('sign')
159 return sign.get_text ()
161 print 'clef requested, but unknow'
164 def get_key_signature (self):
165 "return (fifths, mode) tuple"
167 key = self.get_named_attribute ('key')
168 mode_node = self.get_maybe_exist_named_child ('mode')
171 mode = mode_node.get_text ()
173 fifths = int (key.get_maybe_exist_named_child ('fifths').get_text ())
174 return (fifths, mode)
177 class Note (Measure_element):
179 Measure_element.__init__ (self)
180 self.instrument_name = ''
182 def get_duration_log (self):
183 ch = self.get_maybe_exist_typed_child (class_dict[u'type'])
186 log = ch.get_text ().strip()
198 def get_factor (self):
201 def get_pitches (self):
202 return self.get_typed_children (class_dict[u'pitch'])
204 class Part_list (Music_xml_node):
206 Music_xml_node.__init__ (self)
207 self._id_instrument_name_dict = {}
209 def generate_id_instrument_dict (self):
211 ## not empty to make sure this happens only once.
213 for score_part in self.get_named_children ('score-part'):
214 for instr in score_part.get_named_children ('score-instrument'):
216 name = instr.get_named_child ("instrument-name")
217 mapping[id] = name.get_text ()
219 self._id_instrument_name_dict = mapping
221 def get_instrument (self, id):
222 if not self._id_instrument_name_dict:
223 self.generate_id_instrument_dict()
226 return self._id_instrument_name_dict[id]
228 print "Opps, couldn't find instrument for ID=", id
231 class Measure(Music_xml_node):
232 def get_notes (self):
233 return self.get_typed_children (class_dict[u'note'])
236 class Musicxml_voice:
240 self._start_staff = None
242 def add_element (self, e):
243 self._elements.append (e)
244 if (isinstance (e, Note)
245 and e.get_maybe_exist_typed_child (Staff)):
246 name = e.get_maybe_exist_typed_child (Staff).get_text ()
248 if not self._start_staff:
249 self._start_staff = name
250 self._staves[name] = True
252 def insert (self, idx, e):
253 self._elements.insert (idx, e)
257 class Part (Music_xml_node):
259 Music_xml_node.__init__ (self)
262 def get_part_list (self):
264 while n and n.get_name() != 'score-partwise':
267 return n.get_named_child ('part-list')
269 def interpret (self):
270 """Set durations and starting points."""
272 part_list = self.get_part_list ()
275 factor = Rational (1)
277 attributes_object = None
278 measures = self.get_typed_children (Measure)
281 measure_start_moment = now
282 measure_position = Rational (0)
283 for n in m.get_all_children ():
286 if n.__class__ == Attributes:
287 n.set_attributes_from_previous (attributes_dict)
289 attributes_dict = n._dict.copy ()
290 attributes_object = n
292 factor = Rational (1,
293 int (attributes_dict['divisions'].get_text ()))
294 elif (n.get_maybe_exist_typed_child (Duration)
295 and not n.get_maybe_exist_typed_child (Chord)):
297 mxl_dur = n.get_maybe_exist_typed_child (Duration)
298 dur = mxl_dur.get_length () * factor
300 if n.get_name() == 'backup':
302 if n.get_maybe_exist_typed_child (Grace):
305 rest = n.get_maybe_exist_typed_child (Rest)
307 and attributes_object
308 and attributes_object.get_measure_length () == dur):
310 rest._is_whole_measure = True
314 n._measure_position = measure_position
317 measure_position += dur
318 if n._name == 'note':
319 instrument = n.get_maybe_exist_named_child ('instrument')
321 n.instrument_name = part_list.get_instrument (instrument.id)
323 if attributes_object:
324 length = attributes_object.get_measure_length ()
325 new_now = measure_start_moment + length
328 problem = 'incomplete'
332 m.message ('%s measure? Expected: %s, Difference: %s' % (problem, now, new_now - now))
336 def extract_voices (part):
338 measures = part.get_typed_children (Measure)
341 elements.extend (m.get_all_children ())
345 voice_id = n.get_maybe_exist_typed_child (class_dict['voice'])
347 if not (voice_id or isinstance (n, Attributes)):
350 if isinstance (n, Attributes) and not start_attr:
354 if isinstance (n, Attributes):
355 for v in voices.values ():
359 id = voice_id.get_text ()
360 if not voices.has_key (id):
361 voices[id] = Musicxml_voice()
363 voices[id].add_element (n)
366 for (k,v) in voices.items ():
367 v.insert (0, start_attr)
369 part._voices = voices
371 def get_voices (self):
374 class Notations (Music_xml_node):
376 ts = self.get_named_children ('tied')
377 starts = [t for t in ts if t.type == 'start']
383 def get_tuplet (self):
384 return self.get_maybe_exist_typed_child (Tuplet)
386 class Time_modification(Music_xml_node):
387 def get_fraction (self):
388 b = self.get_maybe_exist_typed_child (class_dict['actual-notes'])
389 a = self.get_maybe_exist_typed_child (class_dict['normal-notes'])
390 return (int(a.get_text ()), int (b.get_text ()))
392 class Accidental (Music_xml_node):
394 Music_xml_node.__init__ (self)
395 self.editorial = False
396 self.cautionary = False
399 class Tuplet(Music_xml_node):
402 class Slur (Music_xml_node):
406 class Beam (Music_xml_node):
408 return self.get_text ()
409 def is_primary (self):
410 return self.number == "1"
412 class Chord (Music_xml_node):
415 class Dot (Music_xml_node):
418 class Alter (Music_xml_node):
421 class Rest (Music_xml_node):
423 Music_xml_node.__init__ (self)
424 self._is_whole_measure = False
425 def is_whole_measure (self):
426 return self._is_whole_measure
428 class Mode (Music_xml_node):
430 class Tied (Music_xml_node):
433 class Type (Music_xml_node):
435 class Grace (Music_xml_node):
437 class Staff (Music_xml_node):
440 class Instrument (Music_xml_node):
443 ## need this, not all classes are instantiated
444 ## for every input file.
446 '#comment': Hash_comment,
447 'accidental': Accidental,
449 'attributes': Attributes,
453 'duration': Duration,
455 'instrument': Instrument,
458 'notations': Notations,
465 'time-modification': Time_modification,
468 'part-list': Part_list,
472 def name2class_name (name):
473 name = name.replace ('-', '_')
474 name = name.replace ('#', 'hash_')
475 name = name[0].upper() + name[1:].lower()
479 def get_class (name):
481 return class_dict[name]
483 class_name = name2class_name (name)
484 klass = new.classobj (class_name, (Music_xml_node,) , {})
485 class_dict[name] = klass
488 def lxml_demarshal_node (node):
493 klass = get_class (name)
496 py_node._original = node
498 py_node._data = node.text
499 py_node._children = [lxml_demarshal_node (cn) for cn in node.getchildren()]
500 py_node._children = filter (lambda x: x, py_node._children)
502 for c in py_node._children:
505 for (k,v) in node.items ():
506 py_node.__dict__[k] = v
507 py_node._attribute_dict[k] = v
511 def minidom_demarshal_node (node):
514 klass = get_class (name)
517 py_node._children = [minidom_demarshal_node (cn) for cn in node.childNodes]
518 for c in py_node._children:
522 for (nm, value) in node.attributes.items():
523 py_node.__dict__[nm] = value
524 py_node._attribute_dict[nm] = value
527 if node.nodeType == node.TEXT_NODE and node.data:
528 py_node._data = node.data
530 py_node._original = node
534 if __name__ == '__main__':
537 tree = lxml.etree.parse ('beethoven.xml')
538 mxl_tree = lxml_demarshal_node (tree.getroot ())
539 ks = class_dict.keys()