]> git.donarmstrong.com Git - lilypond.git/blob - python/musicxml.py
81d2e82465a744814f6c56e728233dfc7cbd3a8d
[lilypond.git] / python / musicxml.py
1 # -*- coding: utf-8 -*-
2 import new
3 import string
4 from rational import *
5 import re
6 import sys
7 import copy
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);
12     if needs_quotes:
13         return_string = "\"" + string.replace (return_string, "\"", "\\\"") + "\""
14     return return_string
15
16
17 class Xml_node:
18     def __init__ (self):
19         self._children = []
20         self._data = None
21         self._original = None
22         self._name = 'xml_node'
23         self._parent = None
24         self._attribute_dict = {}
25         
26     def get_parent (self):
27         return self._parent
28     
29     def is_first (self):
30         return self._parent.get_typed_children (self.__class__)[0] == self
31
32     def original (self):
33         return self._original 
34     def get_name (self):
35         return self._name
36
37     def get_text (self):
38         if self._data:
39             return self._data
40
41         if not self._children:
42             return ''
43
44         return ''.join ([c.get_text () for c in self._children])
45
46     def message (self, msg):
47         sys.stderr.write (msg+'\n')
48
49         p = self
50         while p:
51             sys.stderr.write ('  In: <%s %s>\n' % (p._name, ' '.join (['%s=%s' % item for item in p._attribute_dict.items()])))
52             p = p.get_parent ()
53         
54     def get_typed_children (self, klass):
55         if not klass:
56             return []
57         else:
58             return [c for c in self._children if isinstance(c, klass)]
59
60     def get_named_children (self, nm):
61         return self.get_typed_children (get_class (nm))
62
63     def get_named_child (self, nm):
64         return self.get_maybe_exist_named_child (nm)
65
66     def get_children (self, predicate):
67         return [c for c in self._children if predicate(c)]
68
69     def get_all_children (self):
70         return self._children
71
72     def get_maybe_exist_named_child (self, name):
73         return self.get_maybe_exist_typed_child (get_class (name))
74
75     def get_maybe_exist_typed_child (self, klass):
76         cn = self.get_typed_children (klass)
77         if len (cn)==0:
78             return None
79         elif len (cn) == 1:
80             return cn[0]
81         else:
82             raise "More than 1 child", klass
83
84     def get_unique_typed_child (self, klass):
85         cn = self.get_typed_children(klass)
86         if len (cn) <> 1:
87             sys.stderr.write (self.__dict__ + '\n')
88             raise 'Child is not unique for', (klass, 'found', cn)
89
90         return cn[0]
91
92 class Music_xml_node (Xml_node):
93     def __init__ (self):
94         Xml_node.__init__ (self)
95         self.duration = Rational (0)
96         self.start = Rational (0)
97
98 class Work (Xml_node):
99     def get_work_information (self, tag):
100         wt = self.get_maybe_exist_named_child (tag)
101         if wt:
102             return wt.get_text ()
103         else:
104             return ''
105       
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')
110     def get_opus (self):
111         return self.get_work_information ('opus')
112
113 class Identification (Xml_node):
114     def get_rights (self):
115         rights = self.get_maybe_exist_named_child ('rights')
116         if rights:
117             return rights.get_text ()
118         else:
119             return ''
120
121     def get_creator (self, type):
122         creators = self.get_named_children ('creator')
123         # return the first creator tag that has the particular type
124         for i in creators:
125             if hasattr (i, 'type') and i.type == type:
126                 return i.get_text ()
127         return None
128
129     def get_composer (self):
130         c = self.get_creator ('composer')
131         if c:
132             return c
133         creators = self.get_named_children ('creator')
134         # return the first creator tag that has no type at all
135         for i in creators:
136             if not hasattr (i, 'type'):
137                 return i.get_text ()
138         return None
139     def get_arranger (self):
140         return self.get_creator ('arranger')
141     def get_editor (self):
142         return self.get_creator ('editor')
143     def get_poet (self):
144         v = self.get_creator ('lyricist')
145         if v:
146             return v
147         v = self.get_creator ('poet')
148         return v
149     
150     def get_encoding_information (self, type):
151         enc = self.get_named_children ('encoding')
152         if enc:
153             children = enc[0].get_named_children (type)
154             if children:
155                 return children[0].get_text ()
156         else:
157             return None
158       
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')
167
168
169 class Duration (Music_xml_node):
170     def get_length (self):
171         dur = int (self.get_text ()) * Rational (1,4)
172         return dur
173
174 class Hash_comment (Music_xml_node):
175     pass
176 class Hash_text (Music_xml_node):
177     pass
178
179 class Pitch (Music_xml_node):
180     def get_step (self):
181         ch = self.get_unique_typed_child (get_class (u'step'))
182         step = ch.get_text ().strip ()
183         return step
184     def get_octave (self):
185         ch = self.get_unique_typed_child (get_class (u'octave'))
186
187         step = ch.get_text ().strip ()
188         return int (step)
189
190     def get_alteration (self):
191         ch = self.get_maybe_exist_typed_child (get_class (u'alter'))
192         alter = 0
193         if ch:
194             alter = int (ch.get_text ().strip ())
195         return alter
196
197 class Measure_element (Music_xml_node):
198     def get_voice_id (self):
199         voice_id = self.get_maybe_exist_named_child ('voice')
200         if voice_id:
201             return voice_id.get_text ()
202         else:
203             return None
204
205     def is_first (self):
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 ()]
208         return cn[0] == self
209
210 class Attributes (Measure_element):
211     def __init__ (self):
212         Measure_element.__init__ (self)
213         self._dict = {}
214
215     def set_attributes_from_previous (self, dict):
216         self._dict.update (dict)
217         
218     def read_self (self):
219         for c in self.get_all_children ():
220             self._dict[c.get_name()] = c
221
222     def get_named_attribute (self, name):
223         return self._dict.get (name)
224
225     def get_measure_length (self):
226         (n,d) = self.get_time_signature ()
227         return Rational (n,d)
228         
229     def get_time_signature (self):
230         "return time sig as a (beat, beat-type) tuple"
231
232         try:
233             mxl = self.get_named_attribute ('time')
234             if mxl:
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 ()))
239             else:
240                 return (4, 4)
241         except KeyError:
242             sys.stderr.write ('error: requested time signature, but time sig unknown\n')
243             return (4, 4)
244
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')
249         if not mxl:
250             return clefinfo
251         sign = mxl.get_maybe_exist_named_child ('sign')
252         if sign:
253             clefinfo[0] = sign.get_text()
254         line = mxl.get_maybe_exist_named_child ('line')
255         if line:
256             clefinfo[1] = string.atoi (line.get_text ())
257         octave = mxl.get_maybe_exist_named_child ('clef-octave-change')
258         if octave:
259             clefinfo[2] = string.atoi (octave.get_text ())
260         return clefinfo
261
262     def get_key_signature (self):
263         "return (fifths, mode) tuple"
264
265         key = self.get_named_attribute ('key')
266         mode_node = key.get_maybe_exist_named_child ('mode')
267         mode = 'major'
268         if mode_node:
269             mode = mode_node.get_text ()
270
271         fifths = int (key.get_maybe_exist_named_child ('fifths').get_text ())
272         return (fifths, mode)
273
274 class Barline (Measure_element):
275     pass
276 class BarStyle (Music_xml_node):
277     pass
278 class Partial (Measure_element):
279     def __init__ (self, partial):
280         Measure_element.__init__ (self)
281         self.partial = partial
282
283 class Note (Measure_element):
284     def __init__ (self):
285         Measure_element.__init__ (self)
286         self.instrument_name = ''
287         
288     def get_duration_log (self):
289         ch = self.get_maybe_exist_named_child (u'type')
290
291         if ch:
292             log = ch.get_text ().strip()
293             return {'256th': 8,
294                     '128th': 7,
295                     '64th': 6,
296                     '32nd': 5,
297                     '16th': 4,
298                     'eighth': 3,
299                     'quarter': 2,
300                     'half': 1,
301                     'whole': 0,
302                     'breve': -1,
303                     'long': -2}.get (log, 0)
304         else:
305             self.message ("Encountered note at %s without %s duration (no <type> element):" % (self.start, self.duration) )
306             return 0
307
308     def get_factor (self):
309         return 1
310
311     def get_pitches (self):
312         return self.get_typed_children (get_class (u'pitch'))
313
314 class Part_list (Music_xml_node):
315     def __init__ (self):
316         Music_xml_node.__init__ (self)
317         self._id_instrument_name_dict = {}
318         
319     def generate_id_instrument_dict (self):
320
321         ## not empty to make sure this happens only once.
322         mapping = {1: 1}
323         for score_part in self.get_named_children ('score-part'):
324             for instr in score_part.get_named_children ('score-instrument'):
325                 id = instr.id
326                 name = instr.get_named_child ("instrument-name")
327                 mapping[id] = name.get_text ()
328
329         self._id_instrument_name_dict = mapping
330
331     def get_instrument (self, id):
332         if not self._id_instrument_name_dict:
333             self.generate_id_instrument_dict()
334
335         instrument_name = self._id_instrument_name_dict.get (id)
336         if instrument_name:
337             return instrument_name
338         else:
339             sys.stderr.write ("Opps, couldn't find instrument for ID=%s\n" % id)
340             return "Grand Piano"
341
342 class Part_group (Music_xml_node):
343     pass
344 class Score_part (Music_xml_node):
345     pass
346         
347 class Measure (Music_xml_node):
348     def __init__ (self):
349         Music_xml_node.__init__ (self)
350         self.partial = 0
351     def is_implicit (self):
352         return hasattr (self, 'implicit') and self.implicit == 'yes'
353     def get_notes (self):
354         return self.get_typed_children (get_class (u'note'))
355
356 class Syllabic (Music_xml_node):
357     def continued (self):
358         text = self.get_text()
359         return (text == "begin") or (text == "middle")
360 class Text (Music_xml_node):
361     pass
362
363 class Lyric (Music_xml_node):
364     def get_number (self):
365         if hasattr (self, 'number'):
366             return self.number
367         else:
368             return -1
369
370     def lyric_to_text (self):
371         continued = False
372         syllabic = self.get_maybe_exist_typed_child (Syllabic)
373         if syllabic:
374             continued = syllabic.continued ()
375         text = self.get_maybe_exist_typed_child (Text)
376         
377         if text:
378             text = text.get_text()
379             # We need to convert soft hyphens to -, otherwise the ascii codec as well
380             # as lilypond will barf on that character
381             text = string.replace( text, u'\xad', '-' )
382         
383         if text == "-" and continued:
384             return "--"
385         elif text == "_" and continued:
386             return "__"
387         elif continued and text:
388             return escape_ly_output_string (text) + " --"
389         elif continued:
390             return "--"
391         elif text:
392             return escape_ly_output_string (text)
393         else:
394             return ""
395
396 class Musicxml_voice:
397     def __init__ (self):
398         self._elements = []
399         self._staves = {}
400         self._start_staff = None
401         self._lyrics = []
402         self._has_lyrics = False
403
404     def add_element (self, e):
405         self._elements.append (e)
406         if (isinstance (e, Note)
407             and e.get_maybe_exist_typed_child (Staff)):
408             name = e.get_maybe_exist_typed_child (Staff).get_text ()
409
410             if not self._start_staff and not e.get_maybe_exist_typed_child (Grace):
411                 self._start_staff = name
412             self._staves[name] = True
413
414         lyrics = e.get_typed_children (Lyric)
415         if not self._has_lyrics:
416           self.has_lyrics = len (lyrics) > 0
417
418         for l in lyrics:
419             nr = l.get_number()
420             if (nr > 0) and not (nr in self._lyrics):
421                 self._lyrics.append (nr)
422
423     def insert (self, idx, e):
424         self._elements.insert (idx, e)
425
426     def get_lyrics_numbers (self):
427         if (len (self._lyrics) == 0) and self._has_lyrics:
428             #only happens if none of the <lyric> tags has a number attribute
429             return [1]
430         else:
431             return self._lyrics
432
433
434
435 class Part (Music_xml_node):
436     def __init__ (self):
437         Music_xml_node.__init__ (self)
438         self._voices = []
439
440     def get_part_list (self):
441         n = self
442         while n and n.get_name() != 'score-partwise':
443             n = n._parent
444
445         return n.get_named_child ('part-list')
446         
447     def interpret (self):
448         """Set durations and starting points."""
449         
450         part_list = self.get_part_list ()
451         
452         now = Rational (0)
453         factor = Rational (1)
454         attributes_dict = {}
455         attributes_object = None
456         measures = self.get_typed_children (Measure)
457         last_moment = Rational (-1)
458         last_measure_position = Rational (-1)
459         measure_position = Rational (0)
460         measure_start_moment = now
461         is_first_measure = True
462         prvious_measure = None
463         for m in measures:
464             # implicit measures are used for artificial measures, e.g. when
465             # a repeat bar line splits a bar into two halves. In this case,
466             # don't reset the measure position to 0. They are also used for
467             # upbeats (initial value of 0 fits these, too).
468             # Also, don't reset the measure position at the end of the loop,
469             # but rather when starting the next measure (since only then do we
470             # know if the next measure is implicit and continues that measure)
471             if not m.is_implicit ():
472                 # Warn about possibly overfull measures and reset the position
473                 if attributes_object:
474                     length = attributes_object.get_measure_length ()
475                     new_now = measure_start_moment + length
476                     if now <> new_now:
477                         problem = 'incomplete'
478                         if now > new_now:
479                             problem = 'overfull'
480                         ## only for verbose operation.
481                         if problem <> 'incomplete' and previous_measure:
482                             previous_measure.message ('%s measure? Expected: %s, Difference: %s' % (problem, now, new_now - now))
483                     now = new_now
484                 measure_start_moment = now
485                 measure_position = Rational (0)
486
487             for n in m.get_all_children ():
488                 if isinstance (n, Hash_text):
489                     continue
490                 dur = Rational (0)
491
492                 if n.__class__ == Attributes:
493                     n.set_attributes_from_previous (attributes_dict)
494                     n.read_self ()
495                     attributes_dict = n._dict.copy ()
496                     attributes_object = n
497                     
498                     factor = Rational (1,
499                                        int (attributes_dict.get ('divisions').get_text ()))
500
501                 
502                 if (n.get_maybe_exist_typed_child (Duration)):
503                     mxl_dur = n.get_maybe_exist_typed_child (Duration)
504                     dur = mxl_dur.get_length () * factor
505                     
506                     if n.get_name() == 'backup':
507                         dur = - dur
508                     if n.get_maybe_exist_typed_child (Grace):
509                         dur = Rational (0)
510
511                     rest = n.get_maybe_exist_typed_child (Rest)
512                     if (rest
513                         and attributes_object
514                         and attributes_object.get_measure_length () == dur):
515
516                         rest._is_whole_measure = True
517
518                 if (dur > Rational (0) 
519                     and n.get_maybe_exist_typed_child (Chord)):
520                     now = last_moment
521                     measure_position = last_measure_position
522
523                 n._when = now
524                 n._measure_position = measure_position
525                 n._duration = dur
526                 if dur > Rational (0):
527                     last_moment = now
528                     last_measure_position = measure_position
529                     now += dur
530                     measure_position += dur
531                 elif dur < Rational (0):
532                     # backup element, reset measure position
533                     now += dur
534                     measure_position += dur
535                     if measure_position < 0:
536                         # backup went beyond the measure start => reset to 0
537                         now -= measure_position
538                         measure_position = 0
539                     last_moment = now
540                     last_measure_position = measure_position
541                 if n._name == 'note':
542                     instrument = n.get_maybe_exist_named_child ('instrument')
543                     if instrument:
544                         n.instrument_name = part_list.get_instrument (instrument.id)
545
546             # Incomplete first measures are not padded, but registered as partial
547             if is_first_measure:
548                 is_first_measure = False
549                 # upbeats are marked as implicit measures
550                 if attributes_object and m.is_implicit ():
551                     length = attributes_object.get_measure_length ()
552                     measure_end = measure_start_moment + length
553                     if measure_end <> now:
554                         m.partial = now
555             previous_measure = m
556
557     # modify attributes so that only those applying to the given staff remain
558     def extract_attributes_for_staff (part, attr, staff):
559         attributes = copy.copy (attr)
560         attributes._children = copy.copy (attr._children)
561         attributes._dict = attr._dict.copy ()
562         for c in attributes._children:
563             if hasattr (c, 'number') and c.number != staff:
564                 attributes._children.remove (c)
565         return attributes
566
567     def extract_voices (part):
568         voices = {}
569         measures = part.get_typed_children (Measure)
570         elements = []
571         for m in measures:
572             if m.partial > 0:
573                 elements.append (Partial (m.partial))
574             elements.extend (m.get_all_children ())
575         # make sure we know all voices already so that dynamics, clefs, etc.
576         # can be assigned to the correct voices
577         voice_to_staff_dict = {}
578         for n in elements:
579             voice_id = n.get_maybe_exist_named_child (u'voice')
580             vid = None
581             if voice_id:
582                 vid = voice_id.get_text ()
583
584             staff_id = n.get_maybe_exist_named_child (u'staff')
585             sid = None
586             if staff_id:
587                 sid = staff_id.get_text ()
588             else:
589                 sid = "None"
590             if vid and not voices.has_key (vid):
591                 voices[vid] = Musicxml_voice()
592             if vid and sid and not n.get_maybe_exist_typed_child (Grace):
593                 if not voice_to_staff_dict.has_key (vid):
594                     voice_to_staff_dict[vid] = sid
595         # invert the voice_to_staff_dict into a staff_to_voice_dict (since we
596         # need to assign staff-assigned objects like clefs, times, etc. to
597         # all the correct voices. This will never work entirely correct due
598         # to staff-switches, but that's the best we can do!
599         staff_to_voice_dict = {}
600         for (v,s) in voice_to_staff_dict.items ():
601             if not staff_to_voice_dict.has_key (s):
602                 staff_to_voice_dict[s] = [v]
603             else:
604                 staff_to_voice_dict[s].append (v)
605
606
607         start_attr = None
608         for n in elements:
609             voice_id = n.get_maybe_exist_typed_child (get_class ('voice'))
610
611             if not (voice_id or isinstance (n, Attributes) or
612                     isinstance (n, Direction) or isinstance (n, Partial) or
613                     isinstance (n, Barline) ):
614                 continue
615
616             if isinstance (n, Attributes) and not start_attr:
617                 start_attr = n
618                 continue
619
620             if isinstance (n, Attributes):
621                 # assign these only to the voices they really belongs to!
622                 for (s, vids) in staff_to_voice_dict.items ():
623                     staff_attributes = part.extract_attributes_for_staff (n, s)
624                     for v in vids:
625                         voices[v].add_element (staff_attributes)
626                 continue
627
628             if isinstance (n, Partial) or isinstance (n, Barline):
629                 for v in voices.keys ():
630                     voices[v].add_element (n)
631                 continue
632
633             if isinstance (n, Direction):
634                 staff_id = n.get_maybe_exist_named_child (u'staff')
635                 if staff_id:
636                     staff_id = staff_id.get_text ()
637                 if staff_id:
638                     dir_voices = staff_to_voice_dict.get (staff_id, voices.keys ())
639                 else:
640                     dir_voices = voices.keys ()
641                 for v in dir_voices:
642                     voices[v].add_element (n)
643                 continue
644
645             id = voice_id.get_text ()
646             if hasattr (n, 'print-object') and getattr (n, 'print-object') == "no":
647                 #Skip this note. 
648                 pass
649             else:
650                 voices[id].add_element (n)
651
652         if start_attr:
653             for (s, vids) in staff_to_voice_dict.items ():
654                 staff_attributes = part.extract_attributes_for_staff (start_attr, s)
655                 staff_attributes.read_self ()
656                 for v in vids:
657                     voices[v].insert (0, staff_attributes)
658                     voices[v]._elements[0].read_self()
659
660         part._voices = voices
661
662     def get_voices (self):
663         return self._voices
664
665 class Notations (Music_xml_node):
666     def get_tie (self):
667         ts = self.get_named_children ('tied')
668         starts = [t for t in ts if t.type == 'start']
669         if starts:
670             return starts[0]
671         else:
672             return None
673
674     def get_tuplet (self):
675         return self.get_maybe_exist_typed_child (Tuplet)
676
677 class Time_modification(Music_xml_node):
678     def get_fraction (self):
679         b = self.get_maybe_exist_named_child ('actual-notes')
680         a = self.get_maybe_exist_named_child ('normal-notes')
681         return (int(a.get_text ()), int (b.get_text ()))
682
683 class Accidental (Music_xml_node):
684     def __init__ (self):
685         Music_xml_node.__init__ (self)
686         self.editorial = False
687         self.cautionary = False
688
689 class Music_xml_spanner (Music_xml_node):
690     def get_type (self):
691         if hasattr (self, 'type'):
692             return self.type
693         else:
694             return 0
695     def get_size (self):
696         if hasattr (self, 'size'):
697             return string.atoi (self.size)
698         else:
699             return 0
700
701 class Wedge (Music_xml_spanner):
702     pass
703
704 class Tuplet (Music_xml_spanner):
705     pass
706
707 class Slur (Music_xml_spanner):
708     def get_type (self):
709         return self.type
710
711 class Beam (Music_xml_spanner):
712     def get_type (self):
713         return self.get_text ()
714     def is_primary (self):
715         return self.number == "1"
716
717 class Wavy_line (Music_xml_spanner):
718     pass
719     
720 class Pedal (Music_xml_spanner):
721     pass
722
723 class Glissando (Music_xml_spanner):
724     pass
725
726 class Octave_shift (Music_xml_spanner):
727     # default is 8 for the octave-shift!
728     def get_size (self):
729         if hasattr (self, 'size'):
730             return string.atoi (self.size)
731         else:
732             return 8
733
734 class Chord (Music_xml_node):
735     pass
736
737 class Dot (Music_xml_node):
738     pass
739
740 # Rests in MusicXML are <note> blocks with a <rest> inside. This class is only
741 # for the inner <rest> element, not the whole rest block.
742 class Rest (Music_xml_node):
743     def __init__ (self):
744         Music_xml_node.__init__ (self)
745         self._is_whole_measure = False
746     def is_whole_measure (self):
747         return self._is_whole_measure
748     def get_step (self):
749         ch = self.get_maybe_exist_typed_child (get_class (u'display-step'))
750         if ch:
751             step = ch.get_text ().strip ()
752             return step
753         else:
754             return None
755     def get_octave (self):
756         ch = self.get_maybe_exist_typed_child (get_class (u'display-octave'))
757         if ch:
758             step = ch.get_text ().strip ()
759             return int (step)
760         else:
761             return None
762
763 class Type (Music_xml_node):
764     pass
765 class Grace (Music_xml_node):
766     pass
767 class Staff (Music_xml_node):
768     pass
769
770 class Direction (Music_xml_node):
771     pass
772 class DirType (Music_xml_node):
773     pass
774
775 class Bend (Music_xml_node):
776     def bend_alter (self):
777         alter = self.get_maybe_exist_named_child ('bend-alter')
778         if alter:
779             return alter.get_text()
780         else:
781             return 0
782
783
784
785 ## need this, not all classes are instantiated
786 ## for every input file. Only add those classes, that are either directly
787 ## used by class name or extend Music_xml_node in some way!
788 class_dict = {
789         '#comment': Hash_comment,
790         '#text': Hash_text,
791         'accidental': Accidental,
792         'attributes': Attributes,
793         'barline': Barline,
794         'bar-style': BarStyle,
795         'beam' : Beam,
796         'bend' : Bend,
797         'chord': Chord,
798         'dot': Dot,
799         'direction': Direction,
800         'direction-type': DirType,
801         'duration': Duration,
802         'glissando': Glissando,
803         'grace': Grace,
804         'identification': Identification,
805         'lyric': Lyric,
806         'measure': Measure,
807         'notations': Notations,
808         'note': Note,
809         'octave-shift': Octave_shift,
810         'part': Part,
811     'part-group': Part_group,
812         'part-list': Part_list,
813         'pedal': Pedal,
814         'pitch': Pitch,
815         'rest': Rest,
816     'score-part': Score_part,
817         'slur': Slur,
818         'staff': Staff,
819         'syllabic': Syllabic,
820         'text': Text,
821         'time-modification': Time_modification,
822         'tuplet': Tuplet,
823         'type': Type,
824         'wavy-line': Wavy_line,
825         'wedge': Wedge,
826         'work': Work,
827 }
828
829 def name2class_name (name):
830     name = name.replace ('-', '_')
831     name = name.replace ('#', 'hash_')
832     name = name[0].upper() + name[1:].lower()
833
834     return str (name)
835
836 def get_class (name):
837     classname = class_dict.get (name)
838     if classname:
839         return classname
840     else:
841         class_name = name2class_name (name)
842         klass = new.classobj (class_name, (Music_xml_node,) , {})
843         class_dict[name] = klass
844         return klass
845         
846 def lxml_demarshal_node (node):
847     name = node.tag
848
849     if name is None:
850         return None
851     klass = get_class (name)
852     py_node = klass()
853     
854     py_node._original = node
855     py_node._name = name
856     py_node._data = node.text
857     py_node._children = [lxml_demarshal_node (cn) for cn in node.getchildren()]
858     py_node._children = filter (lambda x: x, py_node._children)
859     
860     for c in py_node._children:
861         c._parent = py_node
862
863     for (k,v) in node.items ():
864         py_node.__dict__[k] = v
865         py_node._attribute_dict[k] = v
866
867     return py_node
868
869 def minidom_demarshal_node (node):
870     name = node.nodeName
871
872     klass = get_class (name)
873     py_node = klass()
874     py_node._name = name
875     py_node._children = [minidom_demarshal_node (cn) for cn in node.childNodes]
876     for c in py_node._children:
877         c._parent = py_node
878
879     if node.attributes:
880         for (nm, value) in node.attributes.items():
881             py_node.__dict__[nm] = value
882             py_node._attribute_dict[nm] = value
883             
884     py_node._data = None
885     if node.nodeType == node.TEXT_NODE and node.data:
886         py_node._data = node.data 
887
888     py_node._original = node
889     return py_node
890
891
892 if __name__  == '__main__':
893         import lxml.etree
894         
895         tree = lxml.etree.parse ('beethoven.xml')
896         mxl_tree = lxml_demarshal_node (tree.getroot ())
897         ks = class_dict.keys()
898         ks.sort()
899         print '\n'.join (ks)