9 self._name = 'xml_node'
12 def get_parent (self):
16 return self._parent.get_typed_children (self.__class__)[0] == self
27 if not self._children:
30 return ''.join ([c.get_text () for c in self._children])
32 def message (self, msg):
37 print ' In: <%s %s>' % (p._name, ' '.join (['%s=%s' % item for item in p._original.attrib.items()]))
40 def get_typed_children (self, klass):
41 return [c for c in self._children if isinstance(c, klass)]
43 def get_named_children (self, nm):
44 return self.get_typed_children (class_dict[nm])
46 def get_named_child (self, nm):
47 return self.get_maybe_exist_named_child (nm)
49 def get_children (self, predicate):
50 return [c for c in self._children if predicate(c)]
52 def get_all_children (self):
55 def get_maybe_exist_named_child (self, name):
56 return self.get_maybe_exist_typed_child (class_dict[name])
58 def get_maybe_exist_typed_child (self, klass):
59 cn = self.get_typed_children (klass)
65 raise "More than 1 child", klass
67 def get_unique_typed_child (self, klass):
68 cn = self.get_typed_children(klass)
71 raise 'Child is not unique for', (klass, 'found', cn)
75 class Music_xml_node (Xml_node):
77 Xml_node.__init__ (self)
78 self.duration = Rational (0)
79 self.start = Rational (0)
82 class Duration (Music_xml_node):
83 def get_length (self):
84 dur = int (self.get_text ()) * Rational (1,4)
87 class Hash_comment (Music_xml_node):
90 class Pitch (Music_xml_node):
92 ch = self.get_unique_typed_child (class_dict[u'step'])
93 step = ch.get_text ().strip ()
95 def get_octave (self):
96 ch = self.get_unique_typed_child (class_dict[u'octave'])
98 step = ch.get_text ().strip ()
101 def get_alteration (self):
102 ch = self.get_maybe_exist_typed_child (class_dict[u'alter'])
105 alter = int (ch.get_text ().strip ())
108 class Measure_element (Music_xml_node):
109 def get_voice_id (self):
110 voice_id = self.get_maybe_exist_named_child ('voice')
112 return voice_id.get_text ()
117 cn = self._parent.get_typed_children (self.__class__)
118 cn = [c for c in cn if c.get_voice_id () == self.get_voice_id ()]
121 class Attributes (Measure_element):
123 Measure_element.__init__ (self)
126 def set_attributes_from_previous (self, dict):
127 self._dict.update (dict)
129 def read_self (self):
130 for c in self.get_all_children ():
131 self._dict[c.get_name()] = c
133 def get_named_attribute (self, name):
134 return self._dict[name]
136 def get_measure_length (self):
137 (n,d) = self.get_time_signature ()
138 return Rational (n,d)
140 def get_time_signature (self):
141 "return time sig as a (beat, beat-type) tuple"
144 mxl = self.get_named_attribute ('time')
146 beats = mxl.get_maybe_exist_named_child ('beats')
147 type = mxl.get_maybe_exist_named_child ('beat-type')
148 return (int (beats.get_text ()),
149 int (type.get_text ()))
151 print 'error: requested time signature, but time sig unknown'
154 def get_clef_sign (self):
155 mxl = self.get_named_attribute ('clef')
156 sign = mxl.get_maybe_exist_named_child ('sign')
158 return sign.get_text ()
160 print 'clef requested, but unknow'
163 def get_key_signature (self):
164 "return (fifths, mode) tuple"
166 key = self.get_named_attribute ('key')
167 mode_node = self.get_maybe_exist_named_child ('mode')
170 mode = mode_node.get_text ()
172 fifths = int (key.get_maybe_exist_named_child ('fifths').get_text ())
173 return (fifths, mode)
176 class Note (Measure_element):
178 Measure_element.__init__ (self)
179 self.instrument_name = ''
181 def get_duration_log (self):
182 ch = self.get_maybe_exist_typed_child (class_dict[u'type'])
185 log = ch.get_text ().strip()
197 def get_factor (self):
200 def get_pitches (self):
201 return self.get_typed_children (class_dict[u'pitch'])
203 class Part_list (Music_xml_node):
205 Music_xml_node.__init__ (self)
206 self._id_instrument_name_dict = {}
208 def generate_id_instrument_dict (self):
210 ## not empty to make sure this happens only once.
212 for score_part in self.get_named_children ('score-part'):
213 for instr in score_part.get_named_children ('score-instrument'):
215 name = instr.get_named_child ("instrument-name")
216 mapping[id] = name.get_text ()
218 self._id_instrument_name_dict = mapping
220 def get_instrument (self, id):
221 if not self._id_instrument_name_dict:
222 self.generate_id_instrument_dict()
225 return self._id_instrument_name_dict[id]
227 print "Opps, couldn't find instrument for ID=", id
230 class Measure(Music_xml_node):
231 def get_notes (self):
232 return self.get_typed_children (class_dict[u'note'])
235 class Musicxml_voice:
239 self._start_staff = None
241 def add_element (self, e):
242 self._elements.append (e)
243 if (isinstance (e, Note)
244 and e.get_maybe_exist_typed_child (Staff)):
245 name = e.get_maybe_exist_typed_child (Staff).get_text ()
247 if not self._start_staff:
248 self._start_staff = name
249 self._staves[name] = True
251 def insert (self, idx, e):
252 self._elements.insert (idx, e)
256 class Part (Music_xml_node):
260 def get_part_list (self):
262 while n and n.get_name() != 'score-partwise':
265 return n.get_named_child ('part-list')
267 def interpret (self):
268 """Set durations and starting points."""
270 part_list = self.get_part_list ()
273 factor = Rational (1)
275 attributes_object = None
276 measures = self.get_typed_children (Measure)
279 measure_start_moment = now
280 measure_position = Rational (0)
281 for n in m.get_all_children ():
284 if n.__class__ == Attributes:
285 n.set_attributes_from_previous (attributes_dict)
287 attributes_dict = n._dict.copy ()
288 attributes_object = n
290 factor = Rational (1,
291 int (attributes_dict['divisions'].get_text ()))
292 elif (n.get_maybe_exist_typed_child (Duration)
293 and not n.get_maybe_exist_typed_child (Chord)):
295 mxl_dur = n.get_maybe_exist_typed_child (Duration)
296 dur = mxl_dur.get_length () * factor
298 if n.get_name() == 'backup':
300 if n.get_maybe_exist_typed_child (Grace):
303 rest = n.get_maybe_exist_typed_child (Rest)
305 and attributes_object
306 and attributes_object.get_measure_length () == dur):
308 rest._is_whole_measure = True
312 n._measure_position = measure_position
315 measure_position += dur
316 if n._name == 'note':
317 instrument = n.get_maybe_exist_named_child ('instrument')
319 n.instrument_name = part_list.get_instrument (instrument.id)
321 if attributes_object:
322 length = attributes_object.get_measure_length ()
323 new_now = measure_start_moment + length
326 problem = 'incomplete'
330 m.message ('%s measure? Expected: %s, Difference: %s' % (problem, now, new_now - now))
334 def extract_voices (part):
336 measures = part.get_typed_children (Measure)
339 elements.extend (m.get_all_children ())
343 voice_id = n.get_maybe_exist_typed_child (class_dict['voice'])
345 if not (voice_id or isinstance (n, Attributes)):
348 if isinstance (n, Attributes) and not start_attr:
352 if isinstance (n, Attributes):
353 for v in voices.values ():
357 id = voice_id.get_text ()
358 if not voices.has_key (id):
359 voices[id] = Musicxml_voice()
361 voices[id].add_element (n)
364 for (k,v) in voices.items ():
365 v.insert (0, start_attr)
367 part._voices = voices
369 def get_voices (self):
372 class Notations (Music_xml_node):
374 ts = self.get_named_children ('tied')
375 starts = [t for t in ts if t.type == 'start']
381 def get_tuplet (self):
382 return self.get_maybe_exist_typed_child (Tuplet)
384 class Time_modification(Music_xml_node):
385 def get_fraction (self):
386 b = self.get_maybe_exist_typed_child (class_dict['actual-notes'])
387 a = self.get_maybe_exist_typed_child (class_dict['normal-notes'])
388 return (int(a.get_text ()), int (b.get_text ()))
390 class Accidental (Music_xml_node):
392 Music_xml_node.__init__ (self)
393 self.editorial = False
394 self.cautionary = False
397 class Tuplet(Music_xml_node):
400 class Slur (Music_xml_node):
404 class Beam (Music_xml_node):
406 return self.get_text ()
407 def is_primary (self):
408 return self.number == "1"
410 class Chord (Music_xml_node):
413 class Dot (Music_xml_node):
416 class Alter (Music_xml_node):
419 class Rest (Music_xml_node):
421 Music_xml_node.__init__ (self)
422 self._is_whole_measure = False
423 def is_whole_measure (self):
424 return self._is_whole_measure
426 class Mode (Music_xml_node):
428 class Tied (Music_xml_node):
431 class Type (Music_xml_node):
433 class Grace (Music_xml_node):
435 class Staff (Music_xml_node):
438 class Instrument (Music_xml_node):
441 ## need this, not all classes are instantiated
442 ## for every input file.
444 '#comment': Hash_comment,
445 'accidental': Accidental,
447 'attributes': Attributes,
451 'duration': Duration,
453 'instrument': Instrument,
456 'notations': Notations,
463 'time-modification': Time_modification,
466 'part-list': Part_list,
470 def name2class_name (name):
471 name = name.replace ('-', '_')
472 name = name.replace ('#', 'hash_')
473 name = name[0].upper() + name[1:].lower()
477 def get_class (name):
479 return class_dict[name]
481 class_name = name2class_name (name)
482 klass = new.classobj (class_name, (Music_xml_node,) , {})
483 class_dict[name] = klass
486 def lxml_demarshal_node (node):
491 klass = get_class (name)
494 py_node._original = node
496 py_node._data = node.text
497 py_node._children = [lxml_demarshal_node (cn) for cn in node.getchildren()]
498 py_node._children = filter (lambda x: x, py_node._children)
500 for c in py_node._children:
503 for (k,v) in node.items ():
504 py_node.__dict__[k] = v
508 def minidom_demarshal_node (node):
511 klass = get_class (name)
514 py_node._children = [minidom_demarshal_node (cn) for cn in node.childNodes]
515 for c in py_node._children:
519 for (nm, value) in node.attributes.items():
520 py_node.__dict__[nm] = value
523 if node.nodeType == node.TEXT_NODE and node.data:
524 py_node._data = node.data
526 py_node._original = node
530 if __name__ == '__main__':
533 tree = lxml.etree.parse ('beethoven.xml')
534 mxl_tree = lxml_demarshal_node (tree.getroot ())
535 ks = class_dict.keys()