10 self._name = 'xml_node'
12 self._attribute_dict = {}
14 def get_parent (self):
18 return self._parent.get_typed_children (self.__class__)[0] == self
29 if not self._children:
32 return ''.join ([c.get_text () for c in self._children])
34 def message (self, msg):
39 print ' In: <%s %s>' % (p._name, ' '.join (['%s=%s' % item for item in p._attribute_dict.items()]))
42 def get_typed_children (self, klass):
46 return [c for c in self._children if isinstance(c, klass)]
48 def get_named_children (self, nm):
49 return self.get_typed_children (get_class (nm))
51 def get_named_child (self, nm):
52 return self.get_maybe_exist_named_child (nm)
54 def get_children (self, predicate):
55 return [c for c in self._children if predicate(c)]
57 def get_all_children (self):
60 def get_maybe_exist_named_child (self, name):
61 return self.get_maybe_exist_typed_child (get_class (name))
63 def get_maybe_exist_typed_child (self, klass):
64 cn = self.get_typed_children (klass)
70 raise "More than 1 child", klass
72 def get_unique_typed_child (self, klass):
73 cn = self.get_typed_children(klass)
76 raise 'Child is not unique for', (klass, 'found', cn)
80 class Music_xml_node (Xml_node):
82 Xml_node.__init__ (self)
83 self.duration = Rational (0)
84 self.start = Rational (0)
86 class Work (Xml_node):
87 def get_work_information (self, tag):
88 wt = self.get_maybe_exist_named_child (tag)
94 def get_work_title (self):
95 return self.get_work_information ('work-title')
96 def get_work_number (self):
97 return self.get_work_information ('work-number')
99 return self.get_work_information ('opus')
101 class Identification (Xml_node):
102 def get_rights (self):
103 rights = self.get_maybe_exist_named_child ('rights')
105 return rights.get_text ()
109 def get_creator (self, type):
110 creators = self.get_named_children ('creator')
111 # return the first creator tag that has type 'editor'
113 if hasattr (i, 'type') and i.type == type:
118 def get_composer (self):
119 c = self.get_creator ('composer')
122 creators = self.get_named_children ('creator')
123 # return the first creator tag that has no type at all
125 if not hasattr (i, 'type'):
128 def get_arranger (self):
129 return self.get_creator ('arranger')
130 def get_editor (self):
131 return self.get_creator ('editor')
133 return self.get_creator ('poet')
135 def get_encoding_information (self, type):
136 enc = self.get_named_children ('encoding')
138 children = enc[0].get_named_children (type)
140 return children[0].get_text ()
144 def get_encoding_software (self):
145 return self.get_encoding_information ('software')
146 def get_encoding_date (self):
147 return self.get_encoding_information ('encoding-date')
148 def get_encoding_person (self):
149 return self.get_encoding_information ('encoder')
150 def get_encoding_description (self):
151 return self.get_encoding_information ('encoding-description')
154 class Duration (Music_xml_node):
155 def get_length (self):
156 dur = int (self.get_text ()) * Rational (1,4)
159 class Hash_comment (Music_xml_node):
162 class Pitch (Music_xml_node):
164 ch = self.get_unique_typed_child (get_class (u'step'))
165 step = ch.get_text ().strip ()
167 def get_octave (self):
168 ch = self.get_unique_typed_child (get_class (u'octave'))
170 step = ch.get_text ().strip ()
173 def get_alteration (self):
174 ch = self.get_maybe_exist_typed_child (get_class (u'alter'))
177 alter = int (ch.get_text ().strip ())
180 class Measure_element (Music_xml_node):
181 def get_voice_id (self):
182 voice_id = self.get_maybe_exist_named_child ('voice')
184 return voice_id.get_text ()
189 cn = self._parent.get_typed_children (self.__class__)
190 cn = [c for c in cn if c.get_voice_id () == self.get_voice_id ()]
193 class Attributes (Measure_element):
195 Measure_element.__init__ (self)
198 def set_attributes_from_previous (self, dict):
199 self._dict.update (dict)
201 def read_self (self):
202 for c in self.get_all_children ():
203 self._dict[c.get_name()] = c
205 def get_named_attribute (self, name):
206 return self._dict.get (name)
208 def get_measure_length (self):
209 (n,d) = self.get_time_signature ()
210 return Rational (n,d)
212 def get_time_signature (self):
213 "return time sig as a (beat, beat-type) tuple"
216 mxl = self.get_named_attribute ('time')
218 beats = mxl.get_maybe_exist_named_child ('beats')
219 type = mxl.get_maybe_exist_named_child ('beat-type')
220 return (int (beats.get_text ()),
221 int (type.get_text ()))
223 print 'error: requested time signature, but time sig unknown'
226 def get_clef_sign (self):
227 mxl = self.get_named_attribute ('clef')
228 sign = mxl.get_maybe_exist_named_child ('sign')
230 return sign.get_text ()
232 print 'clef requested, but unknow'
235 def get_key_signature (self):
236 "return (fifths, mode) tuple"
238 key = self.get_named_attribute ('key')
239 mode_node = key.get_maybe_exist_named_child ('mode')
242 mode = mode_node.get_text ()
244 fifths = int (key.get_maybe_exist_named_child ('fifths').get_text ())
245 return (fifths, mode)
248 class Note (Measure_element):
250 Measure_element.__init__ (self)
251 self.instrument_name = ''
253 def get_duration_log (self):
254 ch = self.get_maybe_exist_typed_child (get_class (u'type'))
257 log = ch.get_text ().strip()
265 'whole': 0}.get (log)
269 def get_factor (self):
272 def get_pitches (self):
273 return self.get_typed_children (get_class (u'pitch'))
275 class Part_list (Music_xml_node):
277 Music_xml_node.__init__ (self)
278 self._id_instrument_name_dict = {}
280 def generate_id_instrument_dict (self):
282 ## not empty to make sure this happens only once.
284 for score_part in self.get_named_children ('score-part'):
285 for instr in score_part.get_named_children ('score-instrument'):
287 name = instr.get_named_child ("instrument-name")
288 mapping[id] = name.get_text ()
290 self._id_instrument_name_dict = mapping
292 def get_instrument (self, id):
293 if not self._id_instrument_name_dict:
294 self.generate_id_instrument_dict()
296 instrument_name = self._id_instrument_name_dict.get (id)
298 return instrument_name
300 print "Opps, couldn't find instrument for ID=", id
303 class Measure (Music_xml_node):
304 def get_notes (self):
305 return self.get_typed_children (get_class (u'note'))
307 class Syllabic (Music_xml_node):
308 def continued (self):
309 text = self.get_text()
310 return (text == "begin") or (text == "middle")
311 class Text (Music_xml_node):
314 class Lyric (Music_xml_node):
315 def get_number (self):
316 if hasattr (self, 'number'):
321 def lyric_to_text (self):
323 syllabic = self.get_maybe_exist_typed_child (Syllabic)
325 continued = syllabic.continued ()
326 text = self.get_maybe_exist_typed_child (Text)
329 text = text.get_text()
330 # We need to convert soft hyphens to -, otherwise the ascii codec as well
331 # as lilypond will barf on that character
332 text = string.replace( text, u'\xad', '-' )
334 if text == "-" and continued:
336 elif text == "_" and continued:
338 elif continued and text:
347 class Musicxml_voice:
351 self._start_staff = None
353 self._has_lyrics = False
355 def add_element (self, e):
356 self._elements.append (e)
357 if (isinstance (e, Note)
358 and e.get_maybe_exist_typed_child (Staff)):
359 name = e.get_maybe_exist_typed_child (Staff).get_text ()
361 if not self._start_staff:
362 self._start_staff = name
363 self._staves[name] = True
365 lyrics = e.get_typed_children (Lyric)
366 if not self._has_lyrics:
367 self.has_lyrics = len (lyrics) > 0
371 if (nr > 0) and not (nr in self._lyrics):
372 self._lyrics.append (nr)
374 def insert (self, idx, e):
375 self._elements.insert (idx, e)
377 def get_lyrics_numbers (self):
378 if (len (self._lyrics) == 0) and self._has_lyrics:
379 #only happens if none of the <lyric> tags has a number attribute
386 class Part (Music_xml_node):
388 Music_xml_node.__init__ (self)
391 def get_part_list (self):
393 while n and n.get_name() != 'score-partwise':
396 return n.get_named_child ('part-list')
398 def interpret (self):
399 """Set durations and starting points."""
401 part_list = self.get_part_list ()
404 factor = Rational (1)
406 attributes_object = None
407 measures = self.get_typed_children (Measure)
408 last_moment = Rational (-1)
409 last_measure_position = Rational (-1)
411 measure_start_moment = now
412 measure_position = Rational (0)
413 for n in m.get_all_children ():
416 if n.__class__ == Attributes:
417 n.set_attributes_from_previous (attributes_dict)
419 attributes_dict = n._dict.copy ()
420 attributes_object = n
422 factor = Rational (1,
423 int (attributes_dict.get ('divisions').get_text ()))
426 if (n.get_maybe_exist_typed_child (Duration)):
427 mxl_dur = n.get_maybe_exist_typed_child (Duration)
428 dur = mxl_dur.get_length () * factor
430 if n.get_name() == 'backup':
432 if n.get_maybe_exist_typed_child (Grace):
435 rest = n.get_maybe_exist_typed_child (Rest)
437 and attributes_object
438 and attributes_object.get_measure_length () == dur):
440 rest._is_whole_measure = True
442 if (dur > Rational (0)
443 and n.get_maybe_exist_typed_child (Chord)):
445 measure_position = last_measure_position
448 last_measure_position = measure_position
451 n._measure_position = measure_position
454 measure_position += dur
455 if n._name == 'note':
456 instrument = n.get_maybe_exist_named_child ('instrument')
458 n.instrument_name = part_list.get_instrument (instrument.id)
460 if attributes_object:
461 length = attributes_object.get_measure_length ()
462 new_now = measure_start_moment + length
465 problem = 'incomplete'
469 ## only for verbose operation.
470 if problem <> 'incomplete':
471 m.message ('%s measure? Expected: %s, Difference: %s' % (problem, now, new_now - now))
475 def extract_voices (part):
477 measures = part.get_typed_children (Measure)
480 elements.extend (m.get_all_children ())
484 voice_id = n.get_maybe_exist_typed_child (get_class ('voice'))
486 # TODO: If the first element of a voice is a dynamics entry,
487 # then voice_id is not yet set! Thus it will currently be ignored
488 if not (voice_id or isinstance (n, Attributes) or isinstance (n, Direction) ):
491 if isinstance (n, Attributes) and not start_attr:
495 if isinstance (n, Attributes) or isinstance (n, Direction):
496 for v in voices.values ():
500 id = voice_id.get_text ()
501 if not voices.has_key (id):
502 voices[id] = Musicxml_voice()
504 voices[id].add_element (n)
507 for (k,v) in voices.items ():
508 v.insert (0, start_attr)
510 part._voices = voices
512 def get_voices (self):
515 class Notations (Music_xml_node):
517 ts = self.get_named_children ('tied')
518 starts = [t for t in ts if t.type == 'start']
524 def get_tuplet (self):
525 return self.get_maybe_exist_typed_child (Tuplet)
527 class Time_modification(Music_xml_node):
528 def get_fraction (self):
529 b = self.get_maybe_exist_named_child ('actual-notes')
530 a = self.get_maybe_exist_named_child ('normal-notes')
531 return (int(a.get_text ()), int (b.get_text ()))
533 class Accidental (Music_xml_node):
535 Music_xml_node.__init__ (self)
536 self.editorial = False
537 self.cautionary = False
540 class Tuplet(Music_xml_node):
543 class Slur (Music_xml_node):
547 class Beam (Music_xml_node):
549 return self.get_text ()
550 def is_primary (self):
551 return self.number == "1"
553 class Chord (Music_xml_node):
556 class Dot (Music_xml_node):
559 class Rest (Music_xml_node):
561 Music_xml_node.__init__ (self)
562 self._is_whole_measure = False
563 def is_whole_measure (self):
564 return self._is_whole_measure
566 class Type (Music_xml_node):
568 class Grace (Music_xml_node):
570 class Staff (Music_xml_node):
573 class Direction (Music_xml_node):
575 class DirType (Music_xml_node):
579 ## need this, not all classes are instantiated
580 ## for every input file. Only add those classes, that are either directly
581 ## used by class name or extend Music_xml_node in some way!
583 '#comment': Hash_comment,
584 'accidental': Accidental,
585 'attributes': Attributes,
589 'direction': Direction,
590 'direction-type': DirType,
591 'duration': Duration,
593 'identification': Identification,
596 'notations': Notations,
599 'part-list': Part_list,
603 'syllabic': Syllabic,
605 'time-modification': Time_modification,
610 def name2class_name (name):
611 name = name.replace ('-', '_')
612 name = name.replace ('#', 'hash_')
613 name = name[0].upper() + name[1:].lower()
617 def get_class (name):
618 classname = class_dict.get (name)
622 class_name = name2class_name (name)
623 klass = new.classobj (class_name, (Music_xml_node,) , {})
624 class_dict[name] = klass
627 def lxml_demarshal_node (node):
632 klass = get_class (name)
635 py_node._original = node
637 py_node._data = node.text
638 py_node._children = [lxml_demarshal_node (cn) for cn in node.getchildren()]
639 py_node._children = filter (lambda x: x, py_node._children)
641 for c in py_node._children:
644 for (k,v) in node.items ():
645 py_node.__dict__[k] = v
646 py_node._attribute_dict[k] = v
650 def minidom_demarshal_node (node):
653 klass = get_class (name)
656 py_node._children = [minidom_demarshal_node (cn) for cn in node.childNodes]
657 for c in py_node._children:
661 for (nm, value) in node.attributes.items():
662 py_node.__dict__[nm] = value
663 py_node._attribute_dict[nm] = value
666 if node.nodeType == node.TEXT_NODE and node.data:
667 py_node._data = node.data
669 py_node._original = node
673 if __name__ == '__main__':
676 tree = lxml.etree.parse ('beethoven.xml')
677 mxl_tree = lxml_demarshal_node (tree.getroot ())
678 ks = class_dict.keys()