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):
45 return [c for c in self._children if isinstance(c, klass)]
47 def get_named_children (self, nm):
48 return self.get_typed_children (class_dict.get (nm))
50 def get_named_child (self, nm):
51 return self.get_maybe_exist_named_child (nm)
53 def get_children (self, predicate):
54 return [c for c in self._children if predicate(c)]
56 def get_all_children (self):
59 def get_maybe_exist_named_child (self, name):
60 return self.get_maybe_exist_typed_child (class_dict[name])
62 def get_maybe_exist_typed_child (self, klass):
63 cn = self.get_typed_children (klass)
69 raise "More than 1 child", klass
71 def get_unique_typed_child (self, klass):
72 cn = self.get_typed_children(klass)
75 raise 'Child is not unique for', (klass, 'found', cn)
79 class Music_xml_node (Xml_node):
81 Xml_node.__init__ (self)
82 self.duration = Rational (0)
83 self.start = Rational (0)
86 class Duration (Music_xml_node):
87 def get_length (self):
88 dur = int (self.get_text ()) * Rational (1,4)
91 class Hash_comment (Music_xml_node):
94 class Pitch (Music_xml_node):
96 ch = self.get_unique_typed_child (class_dict[u'step'])
97 step = ch.get_text ().strip ()
99 def get_octave (self):
100 ch = self.get_unique_typed_child (class_dict[u'octave'])
102 step = ch.get_text ().strip ()
105 def get_alteration (self):
106 ch = self.get_maybe_exist_typed_child (class_dict[u'alter'])
109 alter = int (ch.get_text ().strip ())
112 class Measure_element (Music_xml_node):
113 def get_voice_id (self):
114 voice_id = self.get_maybe_exist_named_child ('voice')
116 return voice_id.get_text ()
121 cn = self._parent.get_typed_children (self.__class__)
122 cn = [c for c in cn if c.get_voice_id () == self.get_voice_id ()]
125 class Attributes (Measure_element):
127 Measure_element.__init__ (self)
130 def set_attributes_from_previous (self, dict):
131 self._dict.update (dict)
133 def read_self (self):
134 for c in self.get_all_children ():
135 self._dict[c.get_name()] = c
137 def get_named_attribute (self, name):
138 return self._dict[name]
140 def get_measure_length (self):
141 (n,d) = self.get_time_signature ()
142 return Rational (n,d)
144 def get_time_signature (self):
145 "return time sig as a (beat, beat-type) tuple"
148 mxl = self.get_named_attribute ('time')
150 beats = mxl.get_maybe_exist_named_child ('beats')
151 type = mxl.get_maybe_exist_named_child ('beat-type')
152 return (int (beats.get_text ()),
153 int (type.get_text ()))
155 print 'error: requested time signature, but time sig unknown'
158 def get_clef_sign (self):
159 mxl = self.get_named_attribute ('clef')
160 sign = mxl.get_maybe_exist_named_child ('sign')
162 return sign.get_text ()
164 print 'clef requested, but unknow'
167 def get_key_signature (self):
168 "return (fifths, mode) tuple"
170 key = self.get_named_attribute ('key')
171 mode_node = key.get_maybe_exist_named_child ('mode')
174 mode = mode_node.get_text ()
176 fifths = int (key.get_maybe_exist_named_child ('fifths').get_text ())
177 return (fifths, mode)
180 class Note (Measure_element):
182 Measure_element.__init__ (self)
183 self.instrument_name = ''
185 def get_duration_log (self):
186 ch = self.get_maybe_exist_typed_child (class_dict[u'type'])
189 log = ch.get_text ().strip()
201 def get_factor (self):
204 def get_pitches (self):
205 return self.get_typed_children (class_dict[u'pitch'])
207 class Part_list (Music_xml_node):
209 Music_xml_node.__init__ (self)
210 self._id_instrument_name_dict = {}
212 def generate_id_instrument_dict (self):
214 ## not empty to make sure this happens only once.
216 for score_part in self.get_named_children ('score-part'):
217 for instr in score_part.get_named_children ('score-instrument'):
219 name = instr.get_named_child ("instrument-name")
220 mapping[id] = name.get_text ()
222 self._id_instrument_name_dict = mapping
224 def get_instrument (self, id):
225 if not self._id_instrument_name_dict:
226 self.generate_id_instrument_dict()
229 return self._id_instrument_name_dict[id]
231 print "Opps, couldn't find instrument for ID=", id
234 class Measure(Music_xml_node):
235 def get_notes (self):
236 return self.get_typed_children (class_dict[u'note'])
239 class Musicxml_voice:
243 self._start_staff = None
245 def add_element (self, e):
246 self._elements.append (e)
247 if (isinstance (e, Note)
248 and e.get_maybe_exist_typed_child (Staff)):
249 name = e.get_maybe_exist_typed_child (Staff).get_text ()
251 if not self._start_staff:
252 self._start_staff = name
253 self._staves[name] = True
255 def insert (self, idx, e):
256 self._elements.insert (idx, e)
260 class Part (Music_xml_node):
262 Music_xml_node.__init__ (self)
265 def get_part_list (self):
267 while n and n.get_name() != 'score-partwise':
270 return n.get_named_child ('part-list')
272 def interpret (self):
273 """Set durations and starting points."""
275 part_list = self.get_part_list ()
278 factor = Rational (1)
280 attributes_object = None
281 measures = self.get_typed_children (Measure)
282 last_moment = Rational (-1)
283 last_measure_position = Rational (-1)
285 measure_start_moment = now
286 measure_position = Rational (0)
287 for n in m.get_all_children ():
290 if n.__class__ == Attributes:
291 n.set_attributes_from_previous (attributes_dict)
293 attributes_dict = n._dict.copy ()
294 attributes_object = n
296 factor = Rational (1,
297 int (attributes_dict['divisions'].get_text ()))
300 if (n.get_maybe_exist_typed_child (Duration)):
301 mxl_dur = n.get_maybe_exist_typed_child (Duration)
302 dur = mxl_dur.get_length () * factor
304 if n.get_name() == 'backup':
306 if n.get_maybe_exist_typed_child (Grace):
309 rest = n.get_maybe_exist_typed_child (Rest)
311 and attributes_object
312 and attributes_object.get_measure_length () == dur):
314 rest._is_whole_measure = True
316 if (dur > Rational (0)
317 and n.get_maybe_exist_typed_child (Chord)):
319 measure_position = last_measure_position
322 last_measure_position = measure_position
325 n._measure_position = measure_position
328 measure_position += dur
329 if n._name == 'note':
330 instrument = n.get_maybe_exist_named_child ('instrument')
332 n.instrument_name = part_list.get_instrument (instrument.id)
334 if attributes_object:
335 length = attributes_object.get_measure_length ()
336 new_now = measure_start_moment + length
339 problem = 'incomplete'
343 ## only for verbose operation.
344 if problem <> 'incomplete':
345 m.message ('%s measure? Expected: %s, Difference: %s' % (problem, now, new_now - now))
349 def extract_voices (part):
351 measures = part.get_typed_children (Measure)
354 elements.extend (m.get_all_children ())
358 voice_id = n.get_maybe_exist_typed_child (class_dict['voice'])
360 # TODO: If the first element of a voice is a dynamics entry,
361 # then voice_id is not yet set! Thus it will currently be ignored
362 if not (voice_id or isinstance (n, Attributes) or isinstance (n, Direction) ):
365 if isinstance (n, Attributes) and not start_attr:
369 if isinstance (n, Attributes) or isinstance (n, Direction):
370 for v in voices.values ():
374 id = voice_id.get_text ()
375 if not voices.has_key (id):
376 voices[id] = Musicxml_voice()
378 voices[id].add_element (n)
381 for (k,v) in voices.items ():
382 v.insert (0, start_attr)
384 part._voices = voices
386 def get_voices (self):
389 class Notations (Music_xml_node):
391 ts = self.get_named_children ('tied')
392 starts = [t for t in ts if t.type == 'start']
398 def get_tuplet (self):
399 return self.get_maybe_exist_typed_child (Tuplet)
401 class Time_modification(Music_xml_node):
402 def get_fraction (self):
403 b = self.get_maybe_exist_typed_child (class_dict['actual-notes'])
404 a = self.get_maybe_exist_typed_child (class_dict['normal-notes'])
405 return (int(a.get_text ()), int (b.get_text ()))
407 class Accidental (Music_xml_node):
409 Music_xml_node.__init__ (self)
410 self.editorial = False
411 self.cautionary = False
414 class Tuplet(Music_xml_node):
417 class Slur (Music_xml_node):
421 class Beam (Music_xml_node):
423 return self.get_text ()
424 def is_primary (self):
425 return self.number == "1"
427 class Chord (Music_xml_node):
430 class Dot (Music_xml_node):
433 class Alter (Music_xml_node):
436 class Rest (Music_xml_node):
438 Music_xml_node.__init__ (self)
439 self._is_whole_measure = False
440 def is_whole_measure (self):
441 return self._is_whole_measure
443 class Mode (Music_xml_node):
445 class Tied (Music_xml_node):
448 class Type (Music_xml_node):
450 class Grace (Music_xml_node):
452 class Staff (Music_xml_node):
455 class Instrument (Music_xml_node):
458 class Fermata (Music_xml_node):
460 class Dynamics (Music_xml_node):
462 class Articulations (Music_xml_node):
464 class Accent (Music_xml_node):
466 class Staccato (Music_xml_node):
468 class Tenuto (Music_xml_node):
470 class Tremolo (Music_xml_node):
472 class Technical (Music_xml_node):
474 class Ornaments (Music_xml_node):
478 class Direction (Music_xml_node):
480 class DirType (Music_xml_node):
482 class Wedge (Music_xml_node):
486 ## need this, not all classes are instantiated
487 ## for every input file.
489 '#comment': Hash_comment,
490 'accidental': Accidental,
492 'attributes': Attributes,
496 'duration': Duration,
498 'instrument': Instrument,
501 'notations': Notations,
508 'time-modification': Time_modification,
511 'part-list': Part_list,
514 'articulations': Articulations,
516 'staccato': Staccato,
519 'technical': Technical,
520 'ornaments': Ornaments,
521 'direction': Direction,
522 'direction-type': DirType,
523 'dynamics': Dynamics,
527 def name2class_name (name):
528 name = name.replace ('-', '_')
529 name = name.replace ('#', 'hash_')
530 name = name[0].upper() + name[1:].lower()
534 def get_class (name):
536 return class_dict[name]
538 class_name = name2class_name (name)
539 klass = new.classobj (class_name, (Music_xml_node,) , {})
540 class_dict[name] = klass
543 def lxml_demarshal_node (node):
548 klass = get_class (name)
551 py_node._original = node
553 py_node._data = node.text
554 py_node._children = [lxml_demarshal_node (cn) for cn in node.getchildren()]
555 py_node._children = filter (lambda x: x, py_node._children)
557 for c in py_node._children:
560 for (k,v) in node.items ():
561 py_node.__dict__[k] = v
562 py_node._attribute_dict[k] = v
566 def minidom_demarshal_node (node):
569 klass = get_class (name)
572 py_node._children = [minidom_demarshal_node (cn) for cn in node.childNodes]
573 for c in py_node._children:
577 for (nm, value) in node.attributes.items():
578 py_node.__dict__[nm] = value
579 py_node._attribute_dict[nm] = value
582 if node.nodeType == node.TEXT_NODE and node.data:
583 py_node._data = node.data
585 py_node._original = node
589 if __name__ == '__main__':
592 tree = lxml.etree.parse ('beethoven.xml')
593 mxl_tree = lxml_demarshal_node (tree.getroot ())
594 ks = class_dict.keys()