7 def escape_ly_output_string (input_string):
8 return_string = input_string
9 needs_quotes = not re.match ("^[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)
49 sys.stderr.write (' In: <%s %s>' % (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__)
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:
128 def get_composer (self):
129 c = self.get_creator ('composer')
132 creators = self.get_named_children ('creator')
133 # return the first creator tag that has no type at all
135 if not hasattr (i, 'type'):
138 def get_arranger (self):
139 return self.get_creator ('arranger')
140 def get_editor (self):
141 return self.get_creator ('editor')
143 return self.get_creator ('poet')
145 def get_encoding_information (self, type):
146 enc = self.get_named_children ('encoding')
148 children = enc[0].get_named_children (type)
150 return children[0].get_text ()
154 def get_encoding_software (self):
155 return self.get_encoding_information ('software')
156 def get_encoding_date (self):
157 return self.get_encoding_information ('encoding-date')
158 def get_encoding_person (self):
159 return self.get_encoding_information ('encoder')
160 def get_encoding_description (self):
161 return self.get_encoding_information ('encoding-description')
164 class Duration (Music_xml_node):
165 def get_length (self):
166 dur = int (self.get_text ()) * Rational (1,4)
169 class Hash_comment (Music_xml_node):
171 class Hash_text (Music_xml_node):
174 class Pitch (Music_xml_node):
176 ch = self.get_unique_typed_child (get_class (u'step'))
177 step = ch.get_text ().strip ()
179 def get_octave (self):
180 ch = self.get_unique_typed_child (get_class (u'octave'))
182 step = ch.get_text ().strip ()
185 def get_alteration (self):
186 ch = self.get_maybe_exist_typed_child (get_class (u'alter'))
189 alter = int (ch.get_text ().strip ())
192 class Measure_element (Music_xml_node):
193 def get_voice_id (self):
194 voice_id = self.get_maybe_exist_named_child ('voice')
196 return voice_id.get_text ()
201 cn = self._parent.get_typed_children (self.__class__)
202 cn = [c for c in cn if c.get_voice_id () == self.get_voice_id ()]
205 class Attributes (Measure_element):
207 Measure_element.__init__ (self)
210 def set_attributes_from_previous (self, dict):
211 self._dict.update (dict)
213 def read_self (self):
214 for c in self.get_all_children ():
215 self._dict[c.get_name()] = c
217 def get_named_attribute (self, name):
218 return self._dict.get (name)
220 def get_measure_length (self):
221 (n,d) = self.get_time_signature ()
222 return Rational (n,d)
224 def get_time_signature (self):
225 "return time sig as a (beat, beat-type) tuple"
228 mxl = self.get_named_attribute ('time')
230 beats = mxl.get_maybe_exist_named_child ('beats')
231 type = mxl.get_maybe_exist_named_child ('beat-type')
232 return (int (beats.get_text ()),
233 int (type.get_text ()))
237 sys.stderr.write ('error: requested time signature, but time sig unknown')
240 # returns clef information in the form ("cleftype", position, octave-shift)
241 def get_clef_information (self):
242 clefinfo = ['G', 2, 0]
243 mxl = self.get_named_attribute ('clef')
246 sign = mxl.get_maybe_exist_named_child ('sign')
248 clefinfo[0] = sign.get_text()
249 line = mxl.get_maybe_exist_named_child ('line')
251 clefinfo[1] = string.atoi (line.get_text ())
252 octave = mxl.get_maybe_exist_named_child ('clef-octave-change')
254 clefinfo[2] = string.atoi (octave.get_text ())
257 def get_key_signature (self):
258 "return (fifths, mode) tuple"
260 key = self.get_named_attribute ('key')
261 mode_node = key.get_maybe_exist_named_child ('mode')
264 mode = mode_node.get_text ()
266 fifths = int (key.get_maybe_exist_named_child ('fifths').get_text ())
267 return (fifths, mode)
270 class Note (Measure_element):
272 Measure_element.__init__ (self)
273 self.instrument_name = ''
275 def get_duration_log (self):
276 ch = self.get_maybe_exist_typed_child (get_class (u'type'))
279 log = ch.get_text ().strip()
290 'long': -2}.get (log, 0)
292 sys.stderr.write ("Encountered note without duration (no <type> element): %s\n" % self)
295 def get_factor (self):
298 def get_pitches (self):
299 return self.get_typed_children (get_class (u'pitch'))
301 class Part_list (Music_xml_node):
303 Music_xml_node.__init__ (self)
304 self._id_instrument_name_dict = {}
306 def generate_id_instrument_dict (self):
308 ## not empty to make sure this happens only once.
310 for score_part in self.get_named_children ('score-part'):
311 for instr in score_part.get_named_children ('score-instrument'):
313 name = instr.get_named_child ("instrument-name")
314 mapping[id] = name.get_text ()
316 self._id_instrument_name_dict = mapping
318 def get_instrument (self, id):
319 if not self._id_instrument_name_dict:
320 self.generate_id_instrument_dict()
322 instrument_name = self._id_instrument_name_dict.get (id)
324 return instrument_name
326 sys.stderr.write ("Opps, couldn't find instrument for ID=%s" % id)
329 class Measure (Music_xml_node):
330 def get_notes (self):
331 return self.get_typed_children (get_class (u'note'))
333 class Syllabic (Music_xml_node):
334 def continued (self):
335 text = self.get_text()
336 return (text == "begin") or (text == "middle")
337 class Text (Music_xml_node):
340 class Lyric (Music_xml_node):
341 def get_number (self):
342 if hasattr (self, 'number'):
347 def lyric_to_text (self):
349 syllabic = self.get_maybe_exist_typed_child (Syllabic)
351 continued = syllabic.continued ()
352 text = self.get_maybe_exist_typed_child (Text)
355 text = text.get_text()
356 # We need to convert soft hyphens to -, otherwise the ascii codec as well
357 # as lilypond will barf on that character
358 text = string.replace( text, u'\xad', '-' )
360 if text == "-" and continued:
362 elif text == "_" and continued:
364 elif continued and text:
365 return escape_ly_output_string (text) + " --"
369 return escape_ly_output_string (text)
373 class Musicxml_voice:
377 self._start_staff = None
379 self._has_lyrics = False
381 def add_element (self, e):
382 self._elements.append (e)
383 if (isinstance (e, Note)
384 and e.get_maybe_exist_typed_child (Staff)):
385 name = e.get_maybe_exist_typed_child (Staff).get_text ()
387 if not self._start_staff:
388 self._start_staff = name
389 self._staves[name] = True
391 lyrics = e.get_typed_children (Lyric)
392 if not self._has_lyrics:
393 self.has_lyrics = len (lyrics) > 0
397 if (nr > 0) and not (nr in self._lyrics):
398 self._lyrics.append (nr)
400 def insert (self, idx, e):
401 self._elements.insert (idx, e)
403 def get_lyrics_numbers (self):
404 if (len (self._lyrics) == 0) and self._has_lyrics:
405 #only happens if none of the <lyric> tags has a number attribute
412 class Part (Music_xml_node):
414 Music_xml_node.__init__ (self)
417 def get_part_list (self):
419 while n and n.get_name() != 'score-partwise':
422 return n.get_named_child ('part-list')
424 def interpret (self):
425 """Set durations and starting points."""
427 part_list = self.get_part_list ()
430 factor = Rational (1)
432 attributes_object = None
433 measures = self.get_typed_children (Measure)
434 last_moment = Rational (-1)
435 last_measure_position = Rational (-1)
437 measure_start_moment = now
438 measure_position = Rational (0)
439 for n in m.get_all_children ():
440 if isinstance (n, Hash_text):
444 if n.__class__ == Attributes:
445 n.set_attributes_from_previous (attributes_dict)
447 attributes_dict = n._dict.copy ()
448 attributes_object = n
450 factor = Rational (1,
451 int (attributes_dict.get ('divisions').get_text ()))
454 if (n.get_maybe_exist_typed_child (Duration)):
455 mxl_dur = n.get_maybe_exist_typed_child (Duration)
456 dur = mxl_dur.get_length () * factor
458 if n.get_name() == 'backup':
460 if n.get_maybe_exist_typed_child (Grace):
463 rest = n.get_maybe_exist_typed_child (Rest)
465 and attributes_object
466 and attributes_object.get_measure_length () == dur):
468 rest._is_whole_measure = True
470 if (dur > Rational (0)
471 and n.get_maybe_exist_typed_child (Chord)):
473 measure_position = last_measure_position
476 n._measure_position = measure_position
478 if dur > Rational (0):
480 last_measure_position = measure_position
482 measure_position += dur
483 elif dur < Rational (0):
484 # backup element, reset measure position
486 measure_position += dur
487 if measure_position < 0:
488 # backup went beyond the measure start => reset to 0
489 now -= measure_position
492 last_measure_position = measure_position
493 if n._name == 'note':
494 instrument = n.get_maybe_exist_named_child ('instrument')
496 n.instrument_name = part_list.get_instrument (instrument.id)
498 if attributes_object:
499 length = attributes_object.get_measure_length ()
500 new_now = measure_start_moment + length
503 problem = 'incomplete'
507 ## only for verbose operation.
508 if problem <> 'incomplete':
509 m.message ('%s measure? Expected: %s, Difference: %s' % (problem, now, new_now - now))
513 def extract_voices (part):
515 measures = part.get_typed_children (Measure)
518 elements.extend (m.get_all_children ())
522 voice_id = n.get_maybe_exist_typed_child (get_class ('voice'))
524 # TODO: If the first element of a voice is a dynamics entry,
525 # then voice_id is not yet set! Thus it will currently be ignored
526 if not (voice_id or isinstance (n, Attributes) or isinstance (n, Direction) ):
529 if isinstance (n, Attributes) and not start_attr:
533 if isinstance (n, Attributes) or isinstance (n, Direction):
534 for v in voices.values ():
538 id = voice_id.get_text ()
539 if not voices.has_key (id):
540 voices[id] = Musicxml_voice()
542 voices[id].add_element (n)
545 for (k,v) in voices.items ():
546 v.insert (0, start_attr)
548 part._voices = voices
550 def get_voices (self):
553 class Notations (Music_xml_node):
555 ts = self.get_named_children ('tied')
556 starts = [t for t in ts if t.type == 'start']
562 def get_tuplet (self):
563 return self.get_maybe_exist_typed_child (Tuplet)
565 class Time_modification(Music_xml_node):
566 def get_fraction (self):
567 b = self.get_maybe_exist_named_child ('actual-notes')
568 a = self.get_maybe_exist_named_child ('normal-notes')
569 return (int(a.get_text ()), int (b.get_text ()))
571 class Accidental (Music_xml_node):
573 Music_xml_node.__init__ (self)
574 self.editorial = False
575 self.cautionary = False
577 class Music_xml_spanner (Music_xml_node):
579 if hasattr (self, 'type'):
584 if hasattr (self, 'size'):
585 return string.atoi (self.size)
589 class Wedge (Music_xml_spanner):
592 class Tuplet (Music_xml_spanner):
595 class Slur (Music_xml_spanner):
599 class Beam (Music_xml_spanner):
601 return self.get_text ()
602 def is_primary (self):
603 return self.number == "1"
605 class Wavy_line (Music_xml_spanner):
608 class Pedal (Music_xml_spanner):
611 class Glissando (Music_xml_spanner):
614 class Octave_shift (Music_xml_spanner):
615 # default is 8 for the octave-shift!
617 if hasattr (self, 'size'):
618 return string.atoi (self.size)
622 class Chord (Music_xml_node):
625 class Dot (Music_xml_node):
628 # Rests in MusicXML are <note> blocks with a <rest> inside. This class is only
629 # for the inner <rest> element, not the whole rest block.
630 class Rest (Music_xml_node):
632 Music_xml_node.__init__ (self)
633 self._is_whole_measure = False
634 def is_whole_measure (self):
635 return self._is_whole_measure
637 ch = self.get_maybe_exist_typed_child (get_class (u'display-step'))
639 step = ch.get_text ().strip ()
643 def get_octave (self):
644 ch = self.get_maybe_exist_typed_child (get_class (u'display-octave'))
646 step = ch.get_text ().strip ()
651 class Type (Music_xml_node):
653 class Grace (Music_xml_node):
655 class Staff (Music_xml_node):
658 class Direction (Music_xml_node):
660 class DirType (Music_xml_node):
663 class Bend (Music_xml_node):
664 def bend_alter (self):
665 alter = self.get_maybe_exist_named_child ('bend-alter')
667 return alter.get_text()
673 ## need this, not all classes are instantiated
674 ## for every input file. Only add those classes, that are either directly
675 ## used by class name or extend Music_xml_node in some way!
677 '#comment': Hash_comment,
679 'accidental': Accidental,
680 'attributes': Attributes,
685 'direction': Direction,
686 'direction-type': DirType,
687 'duration': Duration,
688 'glissando': Glissando,
690 'identification': Identification,
693 'notations': Notations,
695 'octave-shift': Octave_shift,
697 'part-list': Part_list,
703 'syllabic': Syllabic,
705 'time-modification': Time_modification,
708 'wavy-line': Wavy_line,
713 def name2class_name (name):
714 name = name.replace ('-', '_')
715 name = name.replace ('#', 'hash_')
716 name = name[0].upper() + name[1:].lower()
720 def get_class (name):
721 classname = class_dict.get (name)
725 class_name = name2class_name (name)
726 klass = new.classobj (class_name, (Music_xml_node,) , {})
727 class_dict[name] = klass
730 def lxml_demarshal_node (node):
735 klass = get_class (name)
738 py_node._original = node
740 py_node._data = node.text
741 py_node._children = [lxml_demarshal_node (cn) for cn in node.getchildren()]
742 py_node._children = filter (lambda x: x, py_node._children)
744 for c in py_node._children:
747 for (k,v) in node.items ():
748 py_node.__dict__[k] = v
749 py_node._attribute_dict[k] = v
753 def minidom_demarshal_node (node):
756 klass = get_class (name)
759 py_node._children = [minidom_demarshal_node (cn) for cn in node.childNodes]
760 for c in py_node._children:
764 for (nm, value) in node.attributes.items():
765 py_node.__dict__[nm] = value
766 py_node._attribute_dict[nm] = value
769 if node.nodeType == node.TEXT_NODE and node.data:
770 py_node._data = node.data
772 py_node._original = node
776 if __name__ == '__main__':
779 tree = lxml.etree.parse ('beethoven.xml')
780 mxl_tree = lxml_demarshal_node (tree.getroot ())
781 ks = class_dict.keys()