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)
274 class Partial (Measure_element):
275 def __init__ (self, partial):
276 Measure_element.__init__ (self)
277 self.partial = partial
279 class Note (Measure_element):
281 Measure_element.__init__ (self)
282 self.instrument_name = ''
284 def get_duration_log (self):
285 ch = self.get_maybe_exist_named_child (u'type')
288 log = ch.get_text ().strip()
299 'long': -2}.get (log, 0)
301 self.message ("Encountered note at %s without %s duration (no <type> element):" % (self.start, self.duration) )
304 def get_factor (self):
307 def get_pitches (self):
308 return self.get_typed_children (get_class (u'pitch'))
310 class Part_list (Music_xml_node):
312 Music_xml_node.__init__ (self)
313 self._id_instrument_name_dict = {}
315 def generate_id_instrument_dict (self):
317 ## not empty to make sure this happens only once.
319 for score_part in self.get_named_children ('score-part'):
320 for instr in score_part.get_named_children ('score-instrument'):
322 name = instr.get_named_child ("instrument-name")
323 mapping[id] = name.get_text ()
325 self._id_instrument_name_dict = mapping
327 def get_instrument (self, id):
328 if not self._id_instrument_name_dict:
329 self.generate_id_instrument_dict()
331 instrument_name = self._id_instrument_name_dict.get (id)
333 return instrument_name
335 sys.stderr.write ("Opps, couldn't find instrument for ID=%s\n" % id)
338 class Part_group (Music_xml_node):
340 class Score_part (Music_xml_node):
343 class Measure (Music_xml_node):
345 Music_xml_node.__init__ (self)
347 def is_implicit (self):
348 return hasattr (self, 'implicit') and self.implicit == 'yes'
349 def get_notes (self):
350 return self.get_typed_children (get_class (u'note'))
352 class Syllabic (Music_xml_node):
353 def continued (self):
354 text = self.get_text()
355 return (text == "begin") or (text == "middle")
356 class Text (Music_xml_node):
359 class Lyric (Music_xml_node):
360 def get_number (self):
361 if hasattr (self, 'number'):
366 def lyric_to_text (self):
368 syllabic = self.get_maybe_exist_typed_child (Syllabic)
370 continued = syllabic.continued ()
371 text = self.get_maybe_exist_typed_child (Text)
374 text = text.get_text()
375 # We need to convert soft hyphens to -, otherwise the ascii codec as well
376 # as lilypond will barf on that character
377 text = string.replace( text, u'\xad', '-' )
379 if text == "-" and continued:
381 elif text == "_" and continued:
383 elif continued and text:
384 return escape_ly_output_string (text) + " --"
388 return escape_ly_output_string (text)
392 class Musicxml_voice:
396 self._start_staff = None
398 self._has_lyrics = False
400 def add_element (self, e):
401 self._elements.append (e)
402 if (isinstance (e, Note)
403 and e.get_maybe_exist_typed_child (Staff)):
404 name = e.get_maybe_exist_typed_child (Staff).get_text ()
406 if not self._start_staff and not e.get_maybe_exist_typed_child (Grace):
407 self._start_staff = name
408 self._staves[name] = True
410 lyrics = e.get_typed_children (Lyric)
411 if not self._has_lyrics:
412 self.has_lyrics = len (lyrics) > 0
416 if (nr > 0) and not (nr in self._lyrics):
417 self._lyrics.append (nr)
419 def insert (self, idx, e):
420 self._elements.insert (idx, e)
422 def get_lyrics_numbers (self):
423 if (len (self._lyrics) == 0) and self._has_lyrics:
424 #only happens if none of the <lyric> tags has a number attribute
431 class Part (Music_xml_node):
433 Music_xml_node.__init__ (self)
436 def get_part_list (self):
438 while n and n.get_name() != 'score-partwise':
441 return n.get_named_child ('part-list')
443 def interpret (self):
444 """Set durations and starting points."""
446 part_list = self.get_part_list ()
449 factor = Rational (1)
451 attributes_object = None
452 measures = self.get_typed_children (Measure)
453 last_moment = Rational (-1)
454 last_measure_position = Rational (-1)
455 measure_position = Rational (0)
456 measure_start_moment = now
457 is_first_measure = True
458 prvious_measure = None
460 # implicit measures are used for artificial measures, e.g. when
461 # a repeat bar line splits a bar into two halves. In this case,
462 # don't reset the measure position to 0. They are also used for
463 # upbeats (initial value of 0 fits these, too).
464 # Also, don't reset the measure position at the end of the loop,
465 # but rather when starting the next measure (since only then do we
466 # know if the next measure is implicit and continues that measure)
467 if not m.is_implicit ():
468 # Warn about possibly overfull measures and reset the position
469 if attributes_object:
470 length = attributes_object.get_measure_length ()
471 new_now = measure_start_moment + length
473 problem = 'incomplete'
476 ## only for verbose operation.
477 if problem <> 'incomplete' and previous_measure:
478 previous_measure.message ('%s measure? Expected: %s, Difference: %s' % (problem, now, new_now - now))
480 measure_start_moment = now
481 measure_position = Rational (0)
483 for n in m.get_all_children ():
484 if isinstance (n, Hash_text):
488 if n.__class__ == Attributes:
489 n.set_attributes_from_previous (attributes_dict)
491 attributes_dict = n._dict.copy ()
492 attributes_object = n
494 factor = Rational (1,
495 int (attributes_dict.get ('divisions').get_text ()))
498 if (n.get_maybe_exist_typed_child (Duration)):
499 mxl_dur = n.get_maybe_exist_typed_child (Duration)
500 dur = mxl_dur.get_length () * factor
502 if n.get_name() == 'backup':
504 if n.get_maybe_exist_typed_child (Grace):
507 rest = n.get_maybe_exist_typed_child (Rest)
509 and attributes_object
510 and attributes_object.get_measure_length () == dur):
512 rest._is_whole_measure = True
514 if (dur > Rational (0)
515 and n.get_maybe_exist_typed_child (Chord)):
517 measure_position = last_measure_position
520 n._measure_position = measure_position
522 if dur > Rational (0):
524 last_measure_position = measure_position
526 measure_position += dur
527 elif dur < Rational (0):
528 # backup element, reset measure position
530 measure_position += dur
531 if measure_position < 0:
532 # backup went beyond the measure start => reset to 0
533 now -= measure_position
536 last_measure_position = measure_position
537 if n._name == 'note':
538 instrument = n.get_maybe_exist_named_child ('instrument')
540 n.instrument_name = part_list.get_instrument (instrument.id)
542 # Incomplete first measures are not padded, but registered as partial
544 is_first_measure = False
545 # upbeats are marked as implicit measures
546 if attributes_object and m.is_implicit ():
547 length = attributes_object.get_measure_length ()
548 measure_end = measure_start_moment + length
549 if measure_end <> now:
553 # modify attributes so that only those applying to the given staff remain
554 def extract_attributes_for_staff (part, attr, staff):
555 attributes = copy.copy (attr)
556 attributes._children = copy.copy (attr._children)
557 attributes._dict = attr._dict.copy ()
558 for c in attributes._children:
559 if hasattr (c, 'number') and c.number != staff:
560 attributes._children.remove (c)
563 def extract_voices (part):
565 measures = part.get_typed_children (Measure)
569 elements.append (Partial (m.partial))
570 elements.extend (m.get_all_children ())
571 # make sure we know all voices already so that dynamics, clefs, etc.
572 # can be assigned to the correct voices
573 voice_to_staff_dict = {}
575 voice_id = n.get_maybe_exist_named_child (u'voice')
578 vid = voice_id.get_text ()
580 staff_id = n.get_maybe_exist_named_child (u'staff')
583 sid = staff_id.get_text ()
586 if vid and not voices.has_key (vid):
587 voices[vid] = Musicxml_voice()
588 if vid and sid and not n.get_maybe_exist_typed_child (Grace):
589 if not voice_to_staff_dict.has_key (vid):
590 voice_to_staff_dict[vid] = sid
591 # invert the voice_to_staff_dict into a staff_to_voice_dict (since we
592 # need to assign staff-assigned objects like clefs, times, etc. to
593 # all the correct voices. This will never work entirely correct due
594 # to staff-switches, but that's the best we can do!
595 staff_to_voice_dict = {}
596 for (v,s) in voice_to_staff_dict.items ():
597 if not staff_to_voice_dict.has_key (s):
598 staff_to_voice_dict[s] = [v]
600 staff_to_voice_dict[s].append (v)
605 voice_id = n.get_maybe_exist_typed_child (get_class ('voice'))
607 if not (voice_id or isinstance (n, Attributes) or isinstance (n, Direction) or isinstance (n, Partial) ):
610 if isinstance (n, Attributes) and not start_attr:
614 if isinstance (n, Attributes):
615 # assign these only to the voices they really belongs to!
616 for (s, vids) in staff_to_voice_dict.items ():
617 staff_attributes = part.extract_attributes_for_staff (n, s)
619 voices[v].add_element (staff_attributes)
622 if isinstance (n, Partial):
623 for v in voices.keys ():
624 voices[v].add_element (n)
627 if isinstance (n, Direction):
628 staff_id = n.get_maybe_exist_named_child (u'staff')
630 staff_id = staff_id.get_text ()
632 dir_voices = staff_to_voice_dict.get (staff_id, voices.keys ())
634 dir_voices = voices.keys ()
636 voices[v].add_element (n)
639 id = voice_id.get_text ()
640 if hasattr (n, 'print-object') and getattr (n, 'print-object') == "no":
644 voices[id].add_element (n)
647 for (s, vids) in staff_to_voice_dict.items ():
648 staff_attributes = part.extract_attributes_for_staff (start_attr, s)
649 staff_attributes.read_self ()
651 voices[v].insert (0, staff_attributes)
652 voices[v]._elements[0].read_self()
654 part._voices = voices
656 def get_voices (self):
659 class Notations (Music_xml_node):
661 ts = self.get_named_children ('tied')
662 starts = [t for t in ts if t.type == 'start']
668 def get_tuplet (self):
669 return self.get_maybe_exist_typed_child (Tuplet)
671 class Time_modification(Music_xml_node):
672 def get_fraction (self):
673 b = self.get_maybe_exist_named_child ('actual-notes')
674 a = self.get_maybe_exist_named_child ('normal-notes')
675 return (int(a.get_text ()), int (b.get_text ()))
677 class Accidental (Music_xml_node):
679 Music_xml_node.__init__ (self)
680 self.editorial = False
681 self.cautionary = False
683 class Music_xml_spanner (Music_xml_node):
685 if hasattr (self, 'type'):
690 if hasattr (self, 'size'):
691 return string.atoi (self.size)
695 class Wedge (Music_xml_spanner):
698 class Tuplet (Music_xml_spanner):
701 class Slur (Music_xml_spanner):
705 class Beam (Music_xml_spanner):
707 return self.get_text ()
708 def is_primary (self):
709 return self.number == "1"
711 class Wavy_line (Music_xml_spanner):
714 class Pedal (Music_xml_spanner):
717 class Glissando (Music_xml_spanner):
720 class Octave_shift (Music_xml_spanner):
721 # default is 8 for the octave-shift!
723 if hasattr (self, 'size'):
724 return string.atoi (self.size)
728 class Chord (Music_xml_node):
731 class Dot (Music_xml_node):
734 # Rests in MusicXML are <note> blocks with a <rest> inside. This class is only
735 # for the inner <rest> element, not the whole rest block.
736 class Rest (Music_xml_node):
738 Music_xml_node.__init__ (self)
739 self._is_whole_measure = False
740 def is_whole_measure (self):
741 return self._is_whole_measure
743 ch = self.get_maybe_exist_typed_child (get_class (u'display-step'))
745 step = ch.get_text ().strip ()
749 def get_octave (self):
750 ch = self.get_maybe_exist_typed_child (get_class (u'display-octave'))
752 step = ch.get_text ().strip ()
757 class Type (Music_xml_node):
759 class Grace (Music_xml_node):
761 class Staff (Music_xml_node):
764 class Direction (Music_xml_node):
766 class DirType (Music_xml_node):
769 class Bend (Music_xml_node):
770 def bend_alter (self):
771 alter = self.get_maybe_exist_named_child ('bend-alter')
773 return alter.get_text()
779 ## need this, not all classes are instantiated
780 ## for every input file. Only add those classes, that are either directly
781 ## used by class name or extend Music_xml_node in some way!
783 '#comment': Hash_comment,
785 'accidental': Accidental,
786 'attributes': Attributes,
791 'direction': Direction,
792 'direction-type': DirType,
793 'duration': Duration,
794 'glissando': Glissando,
796 'identification': Identification,
799 'notations': Notations,
801 'octave-shift': Octave_shift,
803 'part-group': Part_group,
804 'part-list': Part_list,
808 'score-part': Score_part,
811 'syllabic': Syllabic,
813 'time-modification': Time_modification,
816 'wavy-line': Wavy_line,
821 def name2class_name (name):
822 name = name.replace ('-', '_')
823 name = name.replace ('#', 'hash_')
824 name = name[0].upper() + name[1:].lower()
828 def get_class (name):
829 classname = class_dict.get (name)
833 class_name = name2class_name (name)
834 klass = new.classobj (class_name, (Music_xml_node,) , {})
835 class_dict[name] = klass
838 def lxml_demarshal_node (node):
843 klass = get_class (name)
846 py_node._original = node
848 py_node._data = node.text
849 py_node._children = [lxml_demarshal_node (cn) for cn in node.getchildren()]
850 py_node._children = filter (lambda x: x, py_node._children)
852 for c in py_node._children:
855 for (k,v) in node.items ():
856 py_node.__dict__[k] = v
857 py_node._attribute_dict[k] = v
861 def minidom_demarshal_node (node):
864 klass = get_class (name)
867 py_node._children = [minidom_demarshal_node (cn) for cn in node.childNodes]
868 for c in py_node._children:
872 for (nm, value) in node.attributes.items():
873 py_node.__dict__[nm] = value
874 py_node._attribute_dict[nm] = value
877 if node.nodeType == node.TEXT_NODE and node.data:
878 py_node._data = node.data
880 py_node._original = node
884 if __name__ == '__main__':
887 tree = lxml.etree.parse ('beethoven.xml')
888 mxl_tree = lxml_demarshal_node (tree.getroot ())
889 ks = class_dict.keys()