1 # -*- coding: utf-8 -*-
9 def escape_ly_output_string (input_string):
10 return_string = input_string
11 needs_quotes = not re.match (u"^[a-zA-ZäöüÜÄÖßñ]*$", return_string);
13 return_string = "\"" + string.replace (return_string, "\"", "\\\"") + "\""
22 self._name = 'xml_node'
24 self._attribute_dict = {}
26 def get_parent (self):
30 return self._parent.get_typed_children (self.__class__)[0] == self
41 if not self._children:
44 return ''.join ([c.get_text () for c in self._children])
46 def message (self, msg):
47 sys.stderr.write (msg+'\n')
51 sys.stderr.write (' In: <%s %s>\n' % (p._name, ' '.join (['%s=%s' % item for item in p._attribute_dict.items()])))
54 def get_typed_children (self, klass):
58 return [c for c in self._children if isinstance(c, klass)]
60 def get_named_children (self, nm):
61 return self.get_typed_children (get_class (nm))
63 def get_named_child (self, nm):
64 return self.get_maybe_exist_named_child (nm)
66 def get_children (self, predicate):
67 return [c for c in self._children if predicate(c)]
69 def get_all_children (self):
72 def get_maybe_exist_named_child (self, name):
73 return self.get_maybe_exist_typed_child (get_class (name))
75 def get_maybe_exist_typed_child (self, klass):
76 cn = self.get_typed_children (klass)
82 raise "More than 1 child", klass
84 def get_unique_typed_child (self, klass):
85 cn = self.get_typed_children(klass)
87 sys.stderr.write (self.__dict__ + '\n')
88 raise 'Child is not unique for', (klass, 'found', cn)
92 class Music_xml_node (Xml_node):
94 Xml_node.__init__ (self)
95 self.duration = Rational (0)
96 self.start = Rational (0)
98 class Work (Xml_node):
99 def get_work_information (self, tag):
100 wt = self.get_maybe_exist_named_child (tag)
102 return wt.get_text ()
106 def get_work_title (self):
107 return self.get_work_information ('work-title')
108 def get_work_number (self):
109 return self.get_work_information ('work-number')
111 return self.get_work_information ('opus')
113 class Identification (Xml_node):
114 def get_rights (self):
115 rights = self.get_maybe_exist_named_child ('rights')
117 return rights.get_text ()
121 def get_creator (self, type):
122 creators = self.get_named_children ('creator')
123 # return the first creator tag that has the particular type
125 if hasattr (i, 'type') and i.type == type:
129 def get_composer (self):
130 c = self.get_creator ('composer')
133 creators = self.get_named_children ('creator')
134 # return the first creator tag that has no type at all
136 if not hasattr (i, 'type'):
139 def get_arranger (self):
140 return self.get_creator ('arranger')
141 def get_editor (self):
142 return self.get_creator ('editor')
144 v = self.get_creator ('lyricist')
147 v = self.get_creator ('poet')
150 def get_encoding_information (self, type):
151 enc = self.get_named_children ('encoding')
153 children = enc[0].get_named_children (type)
155 return children[0].get_text ()
159 def get_encoding_software (self):
160 return self.get_encoding_information ('software')
161 def get_encoding_date (self):
162 return self.get_encoding_information ('encoding-date')
163 def get_encoding_person (self):
164 return self.get_encoding_information ('encoder')
165 def get_encoding_description (self):
166 return self.get_encoding_information ('encoding-description')
169 class Duration (Music_xml_node):
170 def get_length (self):
171 dur = int (self.get_text ()) * Rational (1,4)
174 class Hash_comment (Music_xml_node):
176 class Hash_text (Music_xml_node):
179 class Pitch (Music_xml_node):
181 ch = self.get_unique_typed_child (get_class (u'step'))
182 step = ch.get_text ().strip ()
184 def get_octave (self):
185 ch = self.get_unique_typed_child (get_class (u'octave'))
187 step = ch.get_text ().strip ()
190 def get_alteration (self):
191 ch = self.get_maybe_exist_typed_child (get_class (u'alter'))
194 alter = int (ch.get_text ().strip ())
197 class Measure_element (Music_xml_node):
198 def get_voice_id (self):
199 voice_id = self.get_maybe_exist_named_child ('voice')
201 return voice_id.get_text ()
206 cn = self._parent.get_typed_children (self.__class__)
207 cn = [c for c in cn if c.get_voice_id () == self.get_voice_id ()]
210 class Attributes (Measure_element):
212 Measure_element.__init__ (self)
215 def set_attributes_from_previous (self, dict):
216 self._dict.update (dict)
218 def read_self (self):
219 for c in self.get_all_children ():
220 self._dict[c.get_name()] = c
222 def get_named_attribute (self, name):
223 return self._dict.get (name)
225 def get_measure_length (self):
226 (n,d) = self.get_time_signature ()
227 return Rational (n,d)
229 def get_time_signature (self):
230 "return time sig as a (beat, beat-type) tuple"
233 mxl = self.get_named_attribute ('time')
235 beats = mxl.get_maybe_exist_named_child ('beats')
236 type = mxl.get_maybe_exist_named_child ('beat-type')
237 return (int (beats.get_text ()),
238 int (type.get_text ()))
242 sys.stderr.write ('error: requested time signature, but time sig unknown\n')
245 # returns clef information in the form ("cleftype", position, octave-shift)
246 def get_clef_information (self):
247 clefinfo = ['G', 2, 0]
248 mxl = self.get_named_attribute ('clef')
251 sign = mxl.get_maybe_exist_named_child ('sign')
253 clefinfo[0] = sign.get_text()
254 line = mxl.get_maybe_exist_named_child ('line')
256 clefinfo[1] = string.atoi (line.get_text ())
257 octave = mxl.get_maybe_exist_named_child ('clef-octave-change')
259 clefinfo[2] = string.atoi (octave.get_text ())
262 def get_key_signature (self):
263 "return (fifths, mode) tuple"
265 key = self.get_named_attribute ('key')
266 mode_node = key.get_maybe_exist_named_child ('mode')
269 mode = mode_node.get_text ()
271 fifths = int (key.get_maybe_exist_named_child ('fifths').get_text ())
272 return (fifths, mode)
275 class Note (Measure_element):
277 Measure_element.__init__ (self)
278 self.instrument_name = ''
280 def get_duration_log (self):
281 ch = self.get_maybe_exist_named_child (u'type')
284 log = ch.get_text ().strip()
295 'long': -2}.get (log, 0)
297 self.message ("Encountered note at %s without %s duration (no <type> element):" % (self.start, self.duration) )
300 def get_factor (self):
303 def get_pitches (self):
304 return self.get_typed_children (get_class (u'pitch'))
306 class Part_list (Music_xml_node):
308 Music_xml_node.__init__ (self)
309 self._id_instrument_name_dict = {}
311 def generate_id_instrument_dict (self):
313 ## not empty to make sure this happens only once.
315 for score_part in self.get_named_children ('score-part'):
316 for instr in score_part.get_named_children ('score-instrument'):
318 name = instr.get_named_child ("instrument-name")
319 mapping[id] = name.get_text ()
321 self._id_instrument_name_dict = mapping
323 def get_instrument (self, id):
324 if not self._id_instrument_name_dict:
325 self.generate_id_instrument_dict()
327 instrument_name = self._id_instrument_name_dict.get (id)
329 return instrument_name
331 sys.stderr.write ("Opps, couldn't find instrument for ID=%s\n" % id)
334 class Part_group (Music_xml_node):
336 class Score_part (Music_xml_node):
339 class Measure (Music_xml_node):
340 def get_notes (self):
341 return self.get_typed_children (get_class (u'note'))
343 class Syllabic (Music_xml_node):
344 def continued (self):
345 text = self.get_text()
346 return (text == "begin") or (text == "middle")
347 class Text (Music_xml_node):
350 class Lyric (Music_xml_node):
351 def get_number (self):
352 if hasattr (self, 'number'):
357 def lyric_to_text (self):
359 syllabic = self.get_maybe_exist_typed_child (Syllabic)
361 continued = syllabic.continued ()
362 text = self.get_maybe_exist_typed_child (Text)
365 text = text.get_text()
366 # We need to convert soft hyphens to -, otherwise the ascii codec as well
367 # as lilypond will barf on that character
368 text = string.replace( text, u'\xad', '-' )
370 if text == "-" and continued:
372 elif text == "_" and continued:
374 elif continued and text:
375 return escape_ly_output_string (text) + " --"
379 return escape_ly_output_string (text)
383 class Musicxml_voice:
387 self._start_staff = None
389 self._has_lyrics = False
391 def add_element (self, e):
392 self._elements.append (e)
393 if (isinstance (e, Note)
394 and e.get_maybe_exist_typed_child (Staff)):
395 name = e.get_maybe_exist_typed_child (Staff).get_text ()
397 if not self._start_staff and not e.get_maybe_exist_typed_child (Grace):
398 self._start_staff = name
399 self._staves[name] = True
401 lyrics = e.get_typed_children (Lyric)
402 if not self._has_lyrics:
403 self.has_lyrics = len (lyrics) > 0
407 if (nr > 0) and not (nr in self._lyrics):
408 self._lyrics.append (nr)
410 def insert (self, idx, e):
411 self._elements.insert (idx, e)
413 def get_lyrics_numbers (self):
414 if (len (self._lyrics) == 0) and self._has_lyrics:
415 #only happens if none of the <lyric> tags has a number attribute
422 class Part (Music_xml_node):
424 Music_xml_node.__init__ (self)
427 def get_part_list (self):
429 while n and n.get_name() != 'score-partwise':
432 return n.get_named_child ('part-list')
434 def interpret (self):
435 """Set durations and starting points."""
437 part_list = self.get_part_list ()
440 factor = Rational (1)
442 attributes_object = None
443 measures = self.get_typed_children (Measure)
444 last_moment = Rational (-1)
445 last_measure_position = Rational (-1)
447 measure_start_moment = now
448 measure_position = Rational (0)
449 for n in m.get_all_children ():
450 if isinstance (n, Hash_text):
454 if n.__class__ == Attributes:
455 n.set_attributes_from_previous (attributes_dict)
457 attributes_dict = n._dict.copy ()
458 attributes_object = n
460 factor = Rational (1,
461 int (attributes_dict.get ('divisions').get_text ()))
464 if (n.get_maybe_exist_typed_child (Duration)):
465 mxl_dur = n.get_maybe_exist_typed_child (Duration)
466 dur = mxl_dur.get_length () * factor
468 if n.get_name() == 'backup':
470 if n.get_maybe_exist_typed_child (Grace):
473 rest = n.get_maybe_exist_typed_child (Rest)
475 and attributes_object
476 and attributes_object.get_measure_length () == dur):
478 rest._is_whole_measure = True
480 if (dur > Rational (0)
481 and n.get_maybe_exist_typed_child (Chord)):
483 measure_position = last_measure_position
486 n._measure_position = measure_position
488 if dur > Rational (0):
490 last_measure_position = measure_position
492 measure_position += dur
493 elif dur < Rational (0):
494 # backup element, reset measure position
496 measure_position += dur
497 if measure_position < 0:
498 # backup went beyond the measure start => reset to 0
499 now -= measure_position
502 last_measure_position = measure_position
503 if n._name == 'note':
504 instrument = n.get_maybe_exist_named_child ('instrument')
506 n.instrument_name = part_list.get_instrument (instrument.id)
508 if attributes_object:
509 length = attributes_object.get_measure_length ()
510 new_now = measure_start_moment + length
513 problem = 'incomplete'
517 ## only for verbose operation.
518 if problem <> 'incomplete':
519 m.message ('%s measure? Expected: %s, Difference: %s' % (problem, now, new_now - now))
523 # modify attributes so that only those applying to the given staff remain
524 def extract_attributes_for_staff (part, attr, staff):
525 attributes = copy.copy (attr)
526 attributes._children = copy.copy (attr._children)
527 attributes._dict = attr._dict.copy ()
528 for c in attributes._children:
529 if hasattr (c, 'number') and c.number != staff:
530 attributes._children.remove (c)
533 def extract_voices (part):
535 measures = part.get_typed_children (Measure)
538 elements.extend (m.get_all_children ())
539 # make sure we know all voices already so that dynamics, clefs, etc.
540 # can be assigned to the correct voices
541 voice_to_staff_dict = {}
543 voice_id = n.get_maybe_exist_named_child (u'voice')
546 vid = voice_id.get_text ()
548 staff_id = n.get_maybe_exist_named_child (u'staff')
551 sid = staff_id.get_text ()
554 if vid and not voices.has_key (vid):
555 voices[vid] = Musicxml_voice()
556 if vid and sid and not n.get_maybe_exist_typed_child (Grace):
557 if not voice_to_staff_dict.has_key (vid):
558 voice_to_staff_dict[vid] = sid
559 # invert the voice_to_staff_dict into a staff_to_voice_dict (since we
560 # need to assign staff-assigned objects like clefs, times, etc. to
561 # all the correct voices. This will never work entirely correct due
562 # to staff-switches, but that's the best we can do!
563 staff_to_voice_dict = {}
564 for (v,s) in voice_to_staff_dict.items ():
565 if not staff_to_voice_dict.has_key (s):
566 staff_to_voice_dict[s] = [v]
568 staff_to_voice_dict[s].append (v)
573 voice_id = n.get_maybe_exist_typed_child (get_class ('voice'))
575 if not (voice_id or isinstance (n, Attributes) or isinstance (n, Direction) ):
578 if isinstance (n, Attributes) and not start_attr:
582 if isinstance (n, Attributes):
583 # assign these only to the voices they really belongs to!
584 for (s, vids) in staff_to_voice_dict.items ():
585 staff_attributes = part.extract_attributes_for_staff (n, s)
587 voices[v].add_element (staff_attributes)
590 if isinstance (n, Direction):
591 staff_id = n.get_maybe_exist_named_child (u'staff')
593 staff_id = staff_id.get_text ()
595 dir_voices = staff_to_voice_dict.get (staff_id, voices.keys ())
597 dir_voices = voices.keys ()
599 voices[v].add_element (n)
602 id = voice_id.get_text ()
603 if hasattr (n, 'print-object') and getattr (n, 'print-object') == "no":
607 voices[id].add_element (n)
610 for (s, vids) in staff_to_voice_dict.items ():
611 staff_attributes = part.extract_attributes_for_staff (start_attr, s)
612 staff_attributes.read_self ()
614 voices[v].insert (0, staff_attributes)
615 voices[v]._elements[0].read_self()
617 part._voices = voices
619 def get_voices (self):
622 class Notations (Music_xml_node):
624 ts = self.get_named_children ('tied')
625 starts = [t for t in ts if t.type == 'start']
631 def get_tuplet (self):
632 return self.get_maybe_exist_typed_child (Tuplet)
634 class Time_modification(Music_xml_node):
635 def get_fraction (self):
636 b = self.get_maybe_exist_named_child ('actual-notes')
637 a = self.get_maybe_exist_named_child ('normal-notes')
638 return (int(a.get_text ()), int (b.get_text ()))
640 class Accidental (Music_xml_node):
642 Music_xml_node.__init__ (self)
643 self.editorial = False
644 self.cautionary = False
646 class Music_xml_spanner (Music_xml_node):
648 if hasattr (self, 'type'):
653 if hasattr (self, 'size'):
654 return string.atoi (self.size)
658 class Wedge (Music_xml_spanner):
661 class Tuplet (Music_xml_spanner):
664 class Slur (Music_xml_spanner):
668 class Beam (Music_xml_spanner):
670 return self.get_text ()
671 def is_primary (self):
672 return self.number == "1"
674 class Wavy_line (Music_xml_spanner):
677 class Pedal (Music_xml_spanner):
680 class Glissando (Music_xml_spanner):
683 class Octave_shift (Music_xml_spanner):
684 # default is 8 for the octave-shift!
686 if hasattr (self, 'size'):
687 return string.atoi (self.size)
691 class Chord (Music_xml_node):
694 class Dot (Music_xml_node):
697 # Rests in MusicXML are <note> blocks with a <rest> inside. This class is only
698 # for the inner <rest> element, not the whole rest block.
699 class Rest (Music_xml_node):
701 Music_xml_node.__init__ (self)
702 self._is_whole_measure = False
703 def is_whole_measure (self):
704 return self._is_whole_measure
706 ch = self.get_maybe_exist_typed_child (get_class (u'display-step'))
708 step = ch.get_text ().strip ()
712 def get_octave (self):
713 ch = self.get_maybe_exist_typed_child (get_class (u'display-octave'))
715 step = ch.get_text ().strip ()
720 class Type (Music_xml_node):
722 class Grace (Music_xml_node):
724 class Staff (Music_xml_node):
727 class Direction (Music_xml_node):
729 class DirType (Music_xml_node):
732 class Bend (Music_xml_node):
733 def bend_alter (self):
734 alter = self.get_maybe_exist_named_child ('bend-alter')
736 return alter.get_text()
742 ## need this, not all classes are instantiated
743 ## for every input file. Only add those classes, that are either directly
744 ## used by class name or extend Music_xml_node in some way!
746 '#comment': Hash_comment,
748 'accidental': Accidental,
749 'attributes': Attributes,
754 'direction': Direction,
755 'direction-type': DirType,
756 'duration': Duration,
757 'glissando': Glissando,
759 'identification': Identification,
762 'notations': Notations,
764 'octave-shift': Octave_shift,
766 'part-group': Part_group,
767 'part-list': Part_list,
771 'score-part': Score_part,
774 'syllabic': Syllabic,
776 'time-modification': Time_modification,
779 'wavy-line': Wavy_line,
784 def name2class_name (name):
785 name = name.replace ('-', '_')
786 name = name.replace ('#', 'hash_')
787 name = name[0].upper() + name[1:].lower()
791 def get_class (name):
792 classname = class_dict.get (name)
796 class_name = name2class_name (name)
797 klass = new.classobj (class_name, (Music_xml_node,) , {})
798 class_dict[name] = klass
801 def lxml_demarshal_node (node):
806 klass = get_class (name)
809 py_node._original = node
811 py_node._data = node.text
812 py_node._children = [lxml_demarshal_node (cn) for cn in node.getchildren()]
813 py_node._children = filter (lambda x: x, py_node._children)
815 for c in py_node._children:
818 for (k,v) in node.items ():
819 py_node.__dict__[k] = v
820 py_node._attribute_dict[k] = v
824 def minidom_demarshal_node (node):
827 klass = get_class (name)
830 py_node._children = [minidom_demarshal_node (cn) for cn in node.childNodes]
831 for c in py_node._children:
835 for (nm, value) in node.attributes.items():
836 py_node.__dict__[nm] = value
837 py_node._attribute_dict[nm] = value
840 if node.nodeType == node.TEXT_NODE and node.data:
841 py_node._data = node.data
843 py_node._original = node
847 if __name__ == '__main__':
850 tree = lxml.etree.parse ('beethoven.xml')
851 mxl_tree = lxml_demarshal_node (tree.getroot ())
852 ks = class_dict.keys()