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 (get_class (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 (get_class (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)
85 class Work (Xml_node):
86 def get_work_information (self, tag):
87 wt = self.get_maybe_exist_named_child (tag)
93 def get_work_title (self):
94 return self.get_work_information ('work-title')
95 def get_work_number (self):
96 return self.get_work_information ('work-number')
98 return self.get_work_information ('opus')
100 class Identification (Xml_node):
101 def get_rights (self):
102 rights = self.get_maybe_exist_named_child ('rights')
104 return rights.get_text ()
108 def get_creator (self, type):
109 creators = self.get_named_children ('creator')
110 # return the first creator tag that has type 'editor'
112 if hasattr (i, 'type') and i.type == type:
117 def get_composer (self):
118 c = self.get_creator ('composer')
121 creators = self.get_named_children ('creator')
122 # return the first creator tag that has no type at all
124 if not hasattr (i, 'type'):
127 def get_arranger (self):
128 return self.get_creator ('arranger')
129 def get_editor (self):
130 return self.get_creator ('editor')
132 return self.get_creator ('poet')
134 def get_encoding_information (self, type):
135 enc = self.get_named_children ('encoding')
137 children = enc[0].get_named_children (type)
139 return children[0].get_text ()
143 def get_encoding_software (self):
144 return self.get_encoding_information ('software')
145 def get_encoding_date (self):
146 return self.get_encoding_information ('encoding-date')
147 def get_encoding_person (self):
148 return self.get_encoding_information ('encoder')
149 def get_encoding_description (self):
150 return self.get_encoding_information ('encoding-description')
153 class Duration (Music_xml_node):
154 def get_length (self):
155 dur = int (self.get_text ()) * Rational (1,4)
158 class Hash_comment (Music_xml_node):
161 class Pitch (Music_xml_node):
163 ch = self.get_unique_typed_child (get_class (u'step'))
164 step = ch.get_text ().strip ()
166 def get_octave (self):
167 ch = self.get_unique_typed_child (get_class (u'octave'))
169 step = ch.get_text ().strip ()
172 def get_alteration (self):
173 ch = self.get_maybe_exist_typed_child (get_class (u'alter'))
176 alter = int (ch.get_text ().strip ())
179 class Measure_element (Music_xml_node):
180 def get_voice_id (self):
181 voice_id = self.get_maybe_exist_named_child ('voice')
183 return voice_id.get_text ()
188 cn = self._parent.get_typed_children (self.__class__)
189 cn = [c for c in cn if c.get_voice_id () == self.get_voice_id ()]
192 class Attributes (Measure_element):
194 Measure_element.__init__ (self)
197 def set_attributes_from_previous (self, dict):
198 self._dict.update (dict)
200 def read_self (self):
201 for c in self.get_all_children ():
202 self._dict[c.get_name()] = c
204 def get_named_attribute (self, name):
205 return self._dict.get (name)
207 def get_measure_length (self):
208 (n,d) = self.get_time_signature ()
209 return Rational (n,d)
211 def get_time_signature (self):
212 "return time sig as a (beat, beat-type) tuple"
215 mxl = self.get_named_attribute ('time')
217 beats = mxl.get_maybe_exist_named_child ('beats')
218 type = mxl.get_maybe_exist_named_child ('beat-type')
219 return (int (beats.get_text ()),
220 int (type.get_text ()))
222 print 'error: requested time signature, but time sig unknown'
225 def get_clef_sign (self):
226 mxl = self.get_named_attribute ('clef')
227 sign = mxl.get_maybe_exist_named_child ('sign')
229 return sign.get_text ()
231 print 'clef requested, but unknow'
234 def get_key_signature (self):
235 "return (fifths, mode) tuple"
237 key = self.get_named_attribute ('key')
238 mode_node = key.get_maybe_exist_named_child ('mode')
241 mode = mode_node.get_text ()
243 fifths = int (key.get_maybe_exist_named_child ('fifths').get_text ())
244 return (fifths, mode)
247 class Note (Measure_element):
249 Measure_element.__init__ (self)
250 self.instrument_name = ''
252 def get_duration_log (self):
253 ch = self.get_maybe_exist_typed_child (get_class (u'type'))
256 log = ch.get_text ().strip()
264 'whole': 0}.get (log)
268 def get_factor (self):
271 def get_pitches (self):
272 return self.get_typed_children (get_class (u'pitch'))
274 class Part_list (Music_xml_node):
276 Music_xml_node.__init__ (self)
277 self._id_instrument_name_dict = {}
279 def generate_id_instrument_dict (self):
281 ## not empty to make sure this happens only once.
283 for score_part in self.get_named_children ('score-part'):
284 for instr in score_part.get_named_children ('score-instrument'):
286 name = instr.get_named_child ("instrument-name")
287 mapping[id] = name.get_text ()
289 self._id_instrument_name_dict = mapping
291 def get_instrument (self, id):
292 if not self._id_instrument_name_dict:
293 self.generate_id_instrument_dict()
295 instrument_name = self._id_instrument_name_dict.get (id)
297 return instrument_name
299 print "Opps, couldn't find instrument for ID=", id
302 class Measure(Music_xml_node):
303 def get_notes (self):
304 return self.get_typed_children (get_class (u'note'))
307 class Musicxml_voice:
311 self._start_staff = None
313 def add_element (self, e):
314 self._elements.append (e)
315 if (isinstance (e, Note)
316 and e.get_maybe_exist_typed_child (Staff)):
317 name = e.get_maybe_exist_typed_child (Staff).get_text ()
319 if not self._start_staff:
320 self._start_staff = name
321 self._staves[name] = True
323 def insert (self, idx, e):
324 self._elements.insert (idx, e)
328 class Part (Music_xml_node):
330 Music_xml_node.__init__ (self)
333 def get_part_list (self):
335 while n and n.get_name() != 'score-partwise':
338 return n.get_named_child ('part-list')
340 def interpret (self):
341 """Set durations and starting points."""
343 part_list = self.get_part_list ()
346 factor = Rational (1)
348 attributes_object = None
349 measures = self.get_typed_children (Measure)
350 last_moment = Rational (-1)
351 last_measure_position = Rational (-1)
353 measure_start_moment = now
354 measure_position = Rational (0)
355 for n in m.get_all_children ():
358 if n.__class__ == Attributes:
359 n.set_attributes_from_previous (attributes_dict)
361 attributes_dict = n._dict.copy ()
362 attributes_object = n
364 factor = Rational (1,
365 int (attributes_dict.get ('divisions').get_text ()))
368 if (n.get_maybe_exist_typed_child (Duration)):
369 mxl_dur = n.get_maybe_exist_typed_child (Duration)
370 dur = mxl_dur.get_length () * factor
372 if n.get_name() == 'backup':
374 if n.get_maybe_exist_typed_child (Grace):
377 rest = n.get_maybe_exist_typed_child (Rest)
379 and attributes_object
380 and attributes_object.get_measure_length () == dur):
382 rest._is_whole_measure = True
384 if (dur > Rational (0)
385 and n.get_maybe_exist_typed_child (Chord)):
387 measure_position = last_measure_position
390 last_measure_position = measure_position
393 n._measure_position = measure_position
396 measure_position += dur
397 if n._name == 'note':
398 instrument = n.get_maybe_exist_named_child ('instrument')
400 n.instrument_name = part_list.get_instrument (instrument.id)
402 if attributes_object:
403 length = attributes_object.get_measure_length ()
404 new_now = measure_start_moment + length
407 problem = 'incomplete'
411 ## only for verbose operation.
412 if problem <> 'incomplete':
413 m.message ('%s measure? Expected: %s, Difference: %s' % (problem, now, new_now - now))
417 def extract_voices (part):
419 measures = part.get_typed_children (Measure)
422 elements.extend (m.get_all_children ())
426 voice_id = n.get_maybe_exist_typed_child (get_class ('voice'))
428 # TODO: If the first element of a voice is a dynamics entry,
429 # then voice_id is not yet set! Thus it will currently be ignored
430 if not (voice_id or isinstance (n, Attributes) or isinstance (n, Direction) ):
433 if isinstance (n, Attributes) and not start_attr:
437 if isinstance (n, Attributes) or isinstance (n, Direction):
438 for v in voices.values ():
442 id = voice_id.get_text ()
443 if not voices.has_key (id):
444 voices[id] = Musicxml_voice()
446 voices[id].add_element (n)
449 for (k,v) in voices.items ():
450 v.insert (0, start_attr)
452 part._voices = voices
454 def get_voices (self):
457 class Notations (Music_xml_node):
459 ts = self.get_named_children ('tied')
460 starts = [t for t in ts if t.type == 'start']
466 def get_tuplet (self):
467 return self.get_maybe_exist_typed_child (Tuplet)
469 class Time_modification(Music_xml_node):
470 def get_fraction (self):
471 b = self.get_maybe_exist_named_child ('actual-notes')
472 a = self.get_maybe_exist_named_child ('normal-notes')
473 return (int(a.get_text ()), int (b.get_text ()))
475 class Accidental (Music_xml_node):
477 Music_xml_node.__init__ (self)
478 self.editorial = False
479 self.cautionary = False
482 class Tuplet(Music_xml_node):
485 class Slur (Music_xml_node):
489 class Beam (Music_xml_node):
491 return self.get_text ()
492 def is_primary (self):
493 return self.number == "1"
495 class Chord (Music_xml_node):
498 class Dot (Music_xml_node):
501 class Rest (Music_xml_node):
503 Music_xml_node.__init__ (self)
504 self._is_whole_measure = False
505 def is_whole_measure (self):
506 return self._is_whole_measure
508 class Type (Music_xml_node):
510 class Grace (Music_xml_node):
512 class Staff (Music_xml_node):
515 class Direction (Music_xml_node):
517 class DirType (Music_xml_node):
521 ## need this, not all classes are instantiated
522 ## for every input file. Only add those classes, that are either directly
523 ## used by class name or extend Music_xml_node in some way!
525 '#comment': Hash_comment,
526 'accidental': Accidental,
527 'attributes': Attributes,
531 'direction': Direction,
532 'direction-type': DirType,
533 'duration': Duration,
535 'identification': Identification,
537 'notations': Notations,
540 'part-list': Part_list,
544 'time-modification': Time_modification,
549 def name2class_name (name):
550 name = name.replace ('-', '_')
551 name = name.replace ('#', 'hash_')
552 name = name[0].upper() + name[1:].lower()
556 def get_class (name):
557 classname = class_dict.get (name)
561 class_name = name2class_name (name)
562 klass = new.classobj (class_name, (Music_xml_node,) , {})
563 class_dict[name] = klass
566 def lxml_demarshal_node (node):
571 klass = get_class (name)
574 py_node._original = node
576 py_node._data = node.text
577 py_node._children = [lxml_demarshal_node (cn) for cn in node.getchildren()]
578 py_node._children = filter (lambda x: x, py_node._children)
580 for c in py_node._children:
583 for (k,v) in node.items ():
584 py_node.__dict__[k] = v
585 py_node._attribute_dict[k] = v
589 def minidom_demarshal_node (node):
592 klass = get_class (name)
595 py_node._children = [minidom_demarshal_node (cn) for cn in node.childNodes]
596 for c in py_node._children:
600 for (nm, value) in node.attributes.items():
601 py_node.__dict__[nm] = value
602 py_node._attribute_dict[nm] = value
605 if node.nodeType == node.TEXT_NODE and node.data:
606 py_node._data = node.data
608 py_node._original = node
612 if __name__ == '__main__':
615 tree = lxml.etree.parse ('beethoven.xml')
616 mxl_tree = lxml_demarshal_node (tree.getroot ())
617 ks = class_dict.keys()