7 def escape_ly_output_string (input_string):
8 return_string = input_string
9 needs_quotes = not re.match (u"^[a-zA-ZäöüÜÄÖßñ]*$", return_string);
11 return_string = "\"" + string.replace (return_string, "\"", "\\\"") + "\""
20 self._name = 'xml_node'
22 self._attribute_dict = {}
24 def get_parent (self):
28 return self._parent.get_typed_children (self.__class__)[0] == self
39 if not self._children:
42 return ''.join ([c.get_text () for c in self._children])
44 def message (self, msg):
45 sys.stderr.write (msg+'\n')
49 sys.stderr.write (' In: <%s %s>\n' % (p._name, ' '.join (['%s=%s' % item for item in p._attribute_dict.items()])))
52 def get_typed_children (self, klass):
56 return [c for c in self._children if isinstance(c, klass)]
58 def get_named_children (self, nm):
59 return self.get_typed_children (get_class (nm))
61 def get_named_child (self, nm):
62 return self.get_maybe_exist_named_child (nm)
64 def get_children (self, predicate):
65 return [c for c in self._children if predicate(c)]
67 def get_all_children (self):
70 def get_maybe_exist_named_child (self, name):
71 return self.get_maybe_exist_typed_child (get_class (name))
73 def get_maybe_exist_typed_child (self, klass):
74 cn = self.get_typed_children (klass)
80 raise "More than 1 child", klass
82 def get_unique_typed_child (self, klass):
83 cn = self.get_typed_children(klass)
85 sys.stderr.write (self.__dict__ + '\n')
86 raise 'Child is not unique for', (klass, 'found', cn)
90 class Music_xml_node (Xml_node):
92 Xml_node.__init__ (self)
93 self.duration = Rational (0)
94 self.start = Rational (0)
96 class Work (Xml_node):
97 def get_work_information (self, tag):
98 wt = self.get_maybe_exist_named_child (tag)
100 return wt.get_text ()
104 def get_work_title (self):
105 return self.get_work_information ('work-title')
106 def get_work_number (self):
107 return self.get_work_information ('work-number')
109 return self.get_work_information ('opus')
111 class Identification (Xml_node):
112 def get_rights (self):
113 rights = self.get_maybe_exist_named_child ('rights')
115 return rights.get_text ()
119 def get_creator (self, type):
120 creators = self.get_named_children ('creator')
121 # return the first creator tag that has the particular type
123 if hasattr (i, 'type') and i.type == type:
127 def get_composer (self):
128 c = self.get_creator ('composer')
131 creators = self.get_named_children ('creator')
132 # return the first creator tag that has no type at all
134 if not hasattr (i, 'type'):
137 def get_arranger (self):
138 return self.get_creator ('arranger')
139 def get_editor (self):
140 return self.get_creator ('editor')
142 v = self.get_creator ('lyricist')
145 v = self.get_creator ('poet')
148 def get_encoding_information (self, type):
149 enc = self.get_named_children ('encoding')
151 children = enc[0].get_named_children (type)
153 return children[0].get_text ()
157 def get_encoding_software (self):
158 return self.get_encoding_information ('software')
159 def get_encoding_date (self):
160 return self.get_encoding_information ('encoding-date')
161 def get_encoding_person (self):
162 return self.get_encoding_information ('encoder')
163 def get_encoding_description (self):
164 return self.get_encoding_information ('encoding-description')
167 class Duration (Music_xml_node):
168 def get_length (self):
169 dur = int (self.get_text ()) * Rational (1,4)
172 class Hash_comment (Music_xml_node):
174 class Hash_text (Music_xml_node):
177 class Pitch (Music_xml_node):
179 ch = self.get_unique_typed_child (get_class (u'step'))
180 step = ch.get_text ().strip ()
182 def get_octave (self):
183 ch = self.get_unique_typed_child (get_class (u'octave'))
185 step = ch.get_text ().strip ()
188 def get_alteration (self):
189 ch = self.get_maybe_exist_typed_child (get_class (u'alter'))
192 alter = int (ch.get_text ().strip ())
195 class Measure_element (Music_xml_node):
196 def get_voice_id (self):
197 voice_id = self.get_maybe_exist_named_child ('voice')
199 return voice_id.get_text ()
204 cn = self._parent.get_typed_children (self.__class__)
205 cn = [c for c in cn if c.get_voice_id () == self.get_voice_id ()]
208 class Attributes (Measure_element):
210 Measure_element.__init__ (self)
213 def set_attributes_from_previous (self, dict):
214 self._dict.update (dict)
216 def read_self (self):
217 for c in self.get_all_children ():
218 self._dict[c.get_name()] = c
220 def get_named_attribute (self, name):
221 return self._dict.get (name)
223 def get_measure_length (self):
224 (n,d) = self.get_time_signature ()
225 return Rational (n,d)
227 def get_time_signature (self):
228 "return time sig as a (beat, beat-type) tuple"
231 mxl = self.get_named_attribute ('time')
233 beats = mxl.get_maybe_exist_named_child ('beats')
234 type = mxl.get_maybe_exist_named_child ('beat-type')
235 return (int (beats.get_text ()),
236 int (type.get_text ()))
240 sys.stderr.write ('error: requested time signature, but time sig unknown\n')
243 # returns clef information in the form ("cleftype", position, octave-shift)
244 def get_clef_information (self):
245 clefinfo = ['G', 2, 0]
246 mxl = self.get_named_attribute ('clef')
249 sign = mxl.get_maybe_exist_named_child ('sign')
251 clefinfo[0] = sign.get_text()
252 line = mxl.get_maybe_exist_named_child ('line')
254 clefinfo[1] = string.atoi (line.get_text ())
255 octave = mxl.get_maybe_exist_named_child ('clef-octave-change')
257 clefinfo[2] = string.atoi (octave.get_text ())
260 def get_key_signature (self):
261 "return (fifths, mode) tuple"
263 key = self.get_named_attribute ('key')
264 mode_node = key.get_maybe_exist_named_child ('mode')
267 mode = mode_node.get_text ()
269 fifths = int (key.get_maybe_exist_named_child ('fifths').get_text ())
270 return (fifths, mode)
273 class Note (Measure_element):
275 Measure_element.__init__ (self)
276 self.instrument_name = ''
278 def get_duration_log (self):
279 ch = self.get_maybe_exist_typed_child (get_class (u'type'))
282 log = ch.get_text ().strip()
293 'long': -2}.get (log, 0)
295 sys.stderr.write ("Encountered note without duration (no <type> element): %s\n" % self)
298 def get_factor (self):
301 def get_pitches (self):
302 return self.get_typed_children (get_class (u'pitch'))
304 class Part_list (Music_xml_node):
306 Music_xml_node.__init__ (self)
307 self._id_instrument_name_dict = {}
309 def generate_id_instrument_dict (self):
311 ## not empty to make sure this happens only once.
313 for score_part in self.get_named_children ('score-part'):
314 for instr in score_part.get_named_children ('score-instrument'):
316 name = instr.get_named_child ("instrument-name")
317 mapping[id] = name.get_text ()
319 self._id_instrument_name_dict = mapping
321 def get_instrument (self, id):
322 if not self._id_instrument_name_dict:
323 self.generate_id_instrument_dict()
325 instrument_name = self._id_instrument_name_dict.get (id)
327 return instrument_name
329 sys.stderr.write ("Opps, couldn't find instrument for ID=%s\n" % id)
332 class Part_group (Music_xml_node):
334 class Score_part (Music_xml_node):
337 class Measure (Music_xml_node):
338 def get_notes (self):
339 return self.get_typed_children (get_class (u'note'))
341 class Syllabic (Music_xml_node):
342 def continued (self):
343 text = self.get_text()
344 return (text == "begin") or (text == "middle")
345 class Text (Music_xml_node):
348 class Lyric (Music_xml_node):
349 def get_number (self):
350 if hasattr (self, 'number'):
355 def lyric_to_text (self):
357 syllabic = self.get_maybe_exist_typed_child (Syllabic)
359 continued = syllabic.continued ()
360 text = self.get_maybe_exist_typed_child (Text)
363 text = text.get_text()
364 # We need to convert soft hyphens to -, otherwise the ascii codec as well
365 # as lilypond will barf on that character
366 text = string.replace( text, u'\xad', '-' )
368 if text == "-" and continued:
370 elif text == "_" and continued:
372 elif continued and text:
373 return escape_ly_output_string (text) + " --"
377 return escape_ly_output_string (text)
381 class Musicxml_voice:
385 self._start_staff = None
387 self._has_lyrics = False
389 def add_element (self, e):
390 self._elements.append (e)
391 if (isinstance (e, Note)
392 and e.get_maybe_exist_typed_child (Staff)):
393 name = e.get_maybe_exist_typed_child (Staff).get_text ()
395 if not self._start_staff:
396 self._start_staff = name
397 self._staves[name] = True
399 lyrics = e.get_typed_children (Lyric)
400 if not self._has_lyrics:
401 self.has_lyrics = len (lyrics) > 0
405 if (nr > 0) and not (nr in self._lyrics):
406 self._lyrics.append (nr)
408 def insert (self, idx, e):
409 self._elements.insert (idx, e)
411 def get_lyrics_numbers (self):
412 if (len (self._lyrics) == 0) and self._has_lyrics:
413 #only happens if none of the <lyric> tags has a number attribute
420 class Part (Music_xml_node):
422 Music_xml_node.__init__ (self)
425 def get_part_list (self):
427 while n and n.get_name() != 'score-partwise':
430 return n.get_named_child ('part-list')
432 def interpret (self):
433 """Set durations and starting points."""
435 part_list = self.get_part_list ()
438 factor = Rational (1)
440 attributes_object = None
441 measures = self.get_typed_children (Measure)
442 last_moment = Rational (-1)
443 last_measure_position = Rational (-1)
445 measure_start_moment = now
446 measure_position = Rational (0)
447 for n in m.get_all_children ():
448 if isinstance (n, Hash_text):
452 if n.__class__ == Attributes:
453 n.set_attributes_from_previous (attributes_dict)
455 attributes_dict = n._dict.copy ()
456 attributes_object = n
458 factor = Rational (1,
459 int (attributes_dict.get ('divisions').get_text ()))
462 if (n.get_maybe_exist_typed_child (Duration)):
463 mxl_dur = n.get_maybe_exist_typed_child (Duration)
464 dur = mxl_dur.get_length () * factor
466 if n.get_name() == 'backup':
468 if n.get_maybe_exist_typed_child (Grace):
471 rest = n.get_maybe_exist_typed_child (Rest)
473 and attributes_object
474 and attributes_object.get_measure_length () == dur):
476 rest._is_whole_measure = True
478 if (dur > Rational (0)
479 and n.get_maybe_exist_typed_child (Chord)):
481 measure_position = last_measure_position
484 n._measure_position = measure_position
486 if dur > Rational (0):
488 last_measure_position = measure_position
490 measure_position += dur
491 elif dur < Rational (0):
492 # backup element, reset measure position
494 measure_position += dur
495 if measure_position < 0:
496 # backup went beyond the measure start => reset to 0
497 now -= measure_position
500 last_measure_position = measure_position
501 if n._name == 'note':
502 instrument = n.get_maybe_exist_named_child ('instrument')
504 n.instrument_name = part_list.get_instrument (instrument.id)
506 if attributes_object:
507 length = attributes_object.get_measure_length ()
508 new_now = measure_start_moment + length
511 problem = 'incomplete'
515 ## only for verbose operation.
516 if problem <> 'incomplete':
517 m.message ('%s measure? Expected: %s, Difference: %s' % (problem, now, new_now - now))
521 def extract_voices (part):
523 measures = part.get_typed_children (Measure)
526 elements.extend (m.get_all_children ())
530 voice_id = n.get_maybe_exist_typed_child (get_class ('voice'))
532 # TODO: If the first element of a voice is a dynamics entry,
533 # then voice_id is not yet set! Thus it will currently be ignored
534 if not (voice_id or isinstance (n, Attributes) or isinstance (n, Direction) ):
537 if isinstance (n, Attributes) and not start_attr:
541 if isinstance (n, Attributes) or isinstance (n, Direction):
542 for v in voices.values ():
546 id = voice_id.get_text ()
547 if not voices.has_key (id):
548 voices[id] = Musicxml_voice()
550 voices[id].add_element (n)
553 for (k,v) in voices.items ():
554 v.insert (0, start_attr)
556 part._voices = voices
558 def get_voices (self):
561 class Notations (Music_xml_node):
563 ts = self.get_named_children ('tied')
564 starts = [t for t in ts if t.type == 'start']
570 def get_tuplet (self):
571 return self.get_maybe_exist_typed_child (Tuplet)
573 class Time_modification(Music_xml_node):
574 def get_fraction (self):
575 b = self.get_maybe_exist_named_child ('actual-notes')
576 a = self.get_maybe_exist_named_child ('normal-notes')
577 return (int(a.get_text ()), int (b.get_text ()))
579 class Accidental (Music_xml_node):
581 Music_xml_node.__init__ (self)
582 self.editorial = False
583 self.cautionary = False
585 class Music_xml_spanner (Music_xml_node):
587 if hasattr (self, 'type'):
592 if hasattr (self, 'size'):
593 return string.atoi (self.size)
597 class Wedge (Music_xml_spanner):
600 class Tuplet (Music_xml_spanner):
603 class Slur (Music_xml_spanner):
607 class Beam (Music_xml_spanner):
609 return self.get_text ()
610 def is_primary (self):
611 return self.number == "1"
613 class Wavy_line (Music_xml_spanner):
616 class Pedal (Music_xml_spanner):
619 class Glissando (Music_xml_spanner):
622 class Octave_shift (Music_xml_spanner):
623 # default is 8 for the octave-shift!
625 if hasattr (self, 'size'):
626 return string.atoi (self.size)
630 class Chord (Music_xml_node):
633 class Dot (Music_xml_node):
636 # Rests in MusicXML are <note> blocks with a <rest> inside. This class is only
637 # for the inner <rest> element, not the whole rest block.
638 class Rest (Music_xml_node):
640 Music_xml_node.__init__ (self)
641 self._is_whole_measure = False
642 def is_whole_measure (self):
643 return self._is_whole_measure
645 ch = self.get_maybe_exist_typed_child (get_class (u'display-step'))
647 step = ch.get_text ().strip ()
651 def get_octave (self):
652 ch = self.get_maybe_exist_typed_child (get_class (u'display-octave'))
654 step = ch.get_text ().strip ()
659 class Type (Music_xml_node):
661 class Grace (Music_xml_node):
663 class Staff (Music_xml_node):
666 class Direction (Music_xml_node):
668 class DirType (Music_xml_node):
671 class Bend (Music_xml_node):
672 def bend_alter (self):
673 alter = self.get_maybe_exist_named_child ('bend-alter')
675 return alter.get_text()
681 ## need this, not all classes are instantiated
682 ## for every input file. Only add those classes, that are either directly
683 ## used by class name or extend Music_xml_node in some way!
685 '#comment': Hash_comment,
687 'accidental': Accidental,
688 'attributes': Attributes,
693 'direction': Direction,
694 'direction-type': DirType,
695 'duration': Duration,
696 'glissando': Glissando,
698 'identification': Identification,
701 'notations': Notations,
703 'octave-shift': Octave_shift,
705 'part-group': Part_group,
706 'part-list': Part_list,
710 'score-part': Score_part,
713 'syllabic': Syllabic,
715 'time-modification': Time_modification,
718 'wavy-line': Wavy_line,
723 def name2class_name (name):
724 name = name.replace ('-', '_')
725 name = name.replace ('#', 'hash_')
726 name = name[0].upper() + name[1:].lower()
730 def get_class (name):
731 classname = class_dict.get (name)
735 class_name = name2class_name (name)
736 klass = new.classobj (class_name, (Music_xml_node,) , {})
737 class_dict[name] = klass
740 def lxml_demarshal_node (node):
745 klass = get_class (name)
748 py_node._original = node
750 py_node._data = node.text
751 py_node._children = [lxml_demarshal_node (cn) for cn in node.getchildren()]
752 py_node._children = filter (lambda x: x, py_node._children)
754 for c in py_node._children:
757 for (k,v) in node.items ():
758 py_node.__dict__[k] = v
759 py_node._attribute_dict[k] = v
763 def minidom_demarshal_node (node):
766 klass = get_class (name)
769 py_node._children = [minidom_demarshal_node (cn) for cn in node.childNodes]
770 for c in py_node._children:
774 for (nm, value) in node.attributes.items():
775 py_node.__dict__[nm] = value
776 py_node._attribute_dict[nm] = value
779 if node.nodeType == node.TEXT_NODE and node.data:
780 py_node._data = node.data
782 py_node._original = node
786 if __name__ == '__main__':
789 tree = lxml.etree.parse ('beethoven.xml')
790 mxl_tree = lxml_demarshal_node (tree.getroot ())
791 ks = class_dict.keys()