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)
279 last_moment = Rational (-1)
280 last_measure_position = Rational (-1)
282 measure_start_moment = now
283 measure_position = Rational (0)
284 for n in m.get_all_children ():
287 if n.__class__ == Attributes:
288 n.set_attributes_from_previous (attributes_dict)
290 attributes_dict = n._dict.copy ()
291 attributes_object = n
293 factor = Rational (1,
294 int (attributes_dict['divisions'].get_text ()))
297 if (n.get_maybe_exist_typed_child (Duration)):
298 mxl_dur = n.get_maybe_exist_typed_child (Duration)
299 dur = mxl_dur.get_length () * factor
301 if n.get_name() == 'backup':
303 if n.get_maybe_exist_typed_child (Grace):
306 rest = n.get_maybe_exist_typed_child (Rest)
308 and attributes_object
309 and attributes_object.get_measure_length () == dur):
311 rest._is_whole_measure = True
313 if (dur > Rational (0)
314 and n.get_maybe_exist_typed_child (Chord)):
316 measure_position = last_measure_position
319 last_measure_position = measure_position
322 n._measure_position = measure_position
325 measure_position += dur
326 if n._name == 'note':
327 instrument = n.get_maybe_exist_named_child ('instrument')
329 n.instrument_name = part_list.get_instrument (instrument.id)
331 if attributes_object:
332 length = attributes_object.get_measure_length ()
333 new_now = measure_start_moment + length
336 problem = 'incomplete'
340 ## only for verbose operation.
341 if problem <> 'incomplete':
342 m.message ('%s measure? Expected: %s, Difference: %s' % (problem, now, new_now - now))
346 def extract_voices (part):
348 measures = part.get_typed_children (Measure)
351 elements.extend (m.get_all_children ())
355 voice_id = n.get_maybe_exist_typed_child (class_dict['voice'])
357 if not (voice_id or isinstance (n, Attributes)):
360 if isinstance (n, Attributes) and not start_attr:
364 if isinstance (n, Attributes):
365 for v in voices.values ():
369 id = voice_id.get_text ()
370 if not voices.has_key (id):
371 voices[id] = Musicxml_voice()
373 voices[id].add_element (n)
376 for (k,v) in voices.items ():
377 v.insert (0, start_attr)
379 part._voices = voices
381 def get_voices (self):
384 class Notations (Music_xml_node):
386 ts = self.get_named_children ('tied')
387 starts = [t for t in ts if t.type == 'start']
393 def get_tuplet (self):
394 return self.get_maybe_exist_typed_child (Tuplet)
396 class Time_modification(Music_xml_node):
397 def get_fraction (self):
398 b = self.get_maybe_exist_typed_child (class_dict['actual-notes'])
399 a = self.get_maybe_exist_typed_child (class_dict['normal-notes'])
400 return (int(a.get_text ()), int (b.get_text ()))
402 class Accidental (Music_xml_node):
404 Music_xml_node.__init__ (self)
405 self.editorial = False
406 self.cautionary = False
409 class Tuplet(Music_xml_node):
412 class Slur (Music_xml_node):
416 class Beam (Music_xml_node):
418 return self.get_text ()
419 def is_primary (self):
420 return self.number == "1"
422 class Chord (Music_xml_node):
425 class Dot (Music_xml_node):
428 class Alter (Music_xml_node):
431 class Rest (Music_xml_node):
433 Music_xml_node.__init__ (self)
434 self._is_whole_measure = False
435 def is_whole_measure (self):
436 return self._is_whole_measure
438 class Mode (Music_xml_node):
440 class Tied (Music_xml_node):
443 class Type (Music_xml_node):
445 class Grace (Music_xml_node):
447 class Staff (Music_xml_node):
450 class Instrument (Music_xml_node):
453 ## need this, not all classes are instantiated
454 ## for every input file.
456 '#comment': Hash_comment,
457 'accidental': Accidental,
459 'attributes': Attributes,
463 'duration': Duration,
465 'instrument': Instrument,
468 'notations': Notations,
475 'time-modification': Time_modification,
478 'part-list': Part_list,
482 def name2class_name (name):
483 name = name.replace ('-', '_')
484 name = name.replace ('#', 'hash_')
485 name = name[0].upper() + name[1:].lower()
489 def get_class (name):
491 return class_dict[name]
493 class_name = name2class_name (name)
494 klass = new.classobj (class_name, (Music_xml_node,) , {})
495 class_dict[name] = klass
498 def lxml_demarshal_node (node):
503 klass = get_class (name)
506 py_node._original = node
508 py_node._data = node.text
509 py_node._children = [lxml_demarshal_node (cn) for cn in node.getchildren()]
510 py_node._children = filter (lambda x: x, py_node._children)
512 for c in py_node._children:
515 for (k,v) in node.items ():
516 py_node.__dict__[k] = v
517 py_node._attribute_dict[k] = v
521 def minidom_demarshal_node (node):
524 klass = get_class (name)
527 py_node._children = [minidom_demarshal_node (cn) for cn in node.childNodes]
528 for c in py_node._children:
532 for (nm, value) in node.attributes.items():
533 py_node.__dict__[nm] = value
534 py_node._attribute_dict[nm] = value
537 if node.nodeType == node.TEXT_NODE and node.data:
538 py_node._data = node.data
540 py_node._original = node
544 if __name__ == '__main__':
547 tree = lxml.etree.parse ('beethoven.xml')
548 mxl_tree = lxml_demarshal_node (tree.getroot ())
549 ks = class_dict.keys()