]> git.donarmstrong.com Git - lilypond.git/blob - python/musicxml.py
MusicXML: Support for upbeats and partial/implicit measures
[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 Partial (Measure_element):
275     def __init__ (self, partial):
276         Measure_element.__init__ (self)
277         self.partial = partial
278
279 class Note (Measure_element):
280     def __init__ (self):
281         Measure_element.__init__ (self)
282         self.instrument_name = ''
283         
284     def get_duration_log (self):
285         ch = self.get_maybe_exist_named_child (u'type')
286
287         if ch:
288             log = ch.get_text ().strip()
289             return {'256th': 8,
290                     '128th': 7,
291                     '64th': 6,
292                     '32nd': 5,
293                     '16th': 4,
294                     'eighth': 3,
295                     'quarter': 2,
296                     'half': 1,
297                     'whole': 0,
298                     'breve': -1,
299                     'long': -2}.get (log, 0)
300         else:
301             self.message ("Encountered note at %s without %s duration (no <type> element):" % (self.start, self.duration) )
302             return 0
303
304     def get_factor (self):
305         return 1
306
307     def get_pitches (self):
308         return self.get_typed_children (get_class (u'pitch'))
309
310 class Part_list (Music_xml_node):
311     def __init__ (self):
312         Music_xml_node.__init__ (self)
313         self._id_instrument_name_dict = {}
314         
315     def generate_id_instrument_dict (self):
316
317         ## not empty to make sure this happens only once.
318         mapping = {1: 1}
319         for score_part in self.get_named_children ('score-part'):
320             for instr in score_part.get_named_children ('score-instrument'):
321                 id = instr.id
322                 name = instr.get_named_child ("instrument-name")
323                 mapping[id] = name.get_text ()
324
325         self._id_instrument_name_dict = mapping
326
327     def get_instrument (self, id):
328         if not self._id_instrument_name_dict:
329             self.generate_id_instrument_dict()
330
331         instrument_name = self._id_instrument_name_dict.get (id)
332         if instrument_name:
333             return instrument_name
334         else:
335             sys.stderr.write ("Opps, couldn't find instrument for ID=%s\n" % id)
336             return "Grand Piano"
337
338 class Part_group (Music_xml_node):
339     pass
340 class Score_part (Music_xml_node):
341     pass
342         
343 class Measure (Music_xml_node):
344     def __init__ (self):
345         Music_xml_node.__init__ (self)
346         self.partial = 0
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'))
351
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):
357     pass
358
359 class Lyric (Music_xml_node):
360     def get_number (self):
361         if hasattr (self, 'number'):
362             return self.number
363         else:
364             return -1
365
366     def lyric_to_text (self):
367         continued = False
368         syllabic = self.get_maybe_exist_typed_child (Syllabic)
369         if syllabic:
370             continued = syllabic.continued ()
371         text = self.get_maybe_exist_typed_child (Text)
372         
373         if 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', '-' )
378         
379         if text == "-" and continued:
380             return "--"
381         elif text == "_" and continued:
382             return "__"
383         elif continued and text:
384             return escape_ly_output_string (text) + " --"
385         elif continued:
386             return "--"
387         elif text:
388             return escape_ly_output_string (text)
389         else:
390             return ""
391
392 class Musicxml_voice:
393     def __init__ (self):
394         self._elements = []
395         self._staves = {}
396         self._start_staff = None
397         self._lyrics = []
398         self._has_lyrics = False
399
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 ()
405
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
409
410         lyrics = e.get_typed_children (Lyric)
411         if not self._has_lyrics:
412           self.has_lyrics = len (lyrics) > 0
413
414         for l in lyrics:
415             nr = l.get_number()
416             if (nr > 0) and not (nr in self._lyrics):
417                 self._lyrics.append (nr)
418
419     def insert (self, idx, e):
420         self._elements.insert (idx, e)
421
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
425             return [1]
426         else:
427             return self._lyrics
428
429
430
431 class Part (Music_xml_node):
432     def __init__ (self):
433         Music_xml_node.__init__ (self)
434         self._voices = []
435
436     def get_part_list (self):
437         n = self
438         while n and n.get_name() != 'score-partwise':
439             n = n._parent
440
441         return n.get_named_child ('part-list')
442         
443     def interpret (self):
444         """Set durations and starting points."""
445         
446         part_list = self.get_part_list ()
447         
448         now = Rational (0)
449         factor = Rational (1)
450         attributes_dict = {}
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
459         for m in measures:
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
472                     if now <> new_now:
473                         problem = 'incomplete'
474                         if now > new_now:
475                             problem = 'overfull'
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))
479                     now = new_now
480                 measure_start_moment = now
481                 measure_position = Rational (0)
482
483             for n in m.get_all_children ():
484                 if isinstance (n, Hash_text):
485                     continue
486                 dur = Rational (0)
487
488                 if n.__class__ == Attributes:
489                     n.set_attributes_from_previous (attributes_dict)
490                     n.read_self ()
491                     attributes_dict = n._dict.copy ()
492                     attributes_object = n
493                     
494                     factor = Rational (1,
495                                        int (attributes_dict.get ('divisions').get_text ()))
496
497                 
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
501                     
502                     if n.get_name() == 'backup':
503                         dur = - dur
504                     if n.get_maybe_exist_typed_child (Grace):
505                         dur = Rational (0)
506
507                     rest = n.get_maybe_exist_typed_child (Rest)
508                     if (rest
509                         and attributes_object
510                         and attributes_object.get_measure_length () == dur):
511
512                         rest._is_whole_measure = True
513
514                 if (dur > Rational (0) 
515                     and n.get_maybe_exist_typed_child (Chord)):
516                     now = last_moment
517                     measure_position = last_measure_position
518
519                 n._when = now
520                 n._measure_position = measure_position
521                 n._duration = dur
522                 if dur > Rational (0):
523                     last_moment = now
524                     last_measure_position = measure_position
525                     now += dur
526                     measure_position += dur
527                 elif dur < Rational (0):
528                     # backup element, reset measure position
529                     now += dur
530                     measure_position += dur
531                     if measure_position < 0:
532                         # backup went beyond the measure start => reset to 0
533                         now -= measure_position
534                         measure_position = 0
535                     last_moment = now
536                     last_measure_position = measure_position
537                 if n._name == 'note':
538                     instrument = n.get_maybe_exist_named_child ('instrument')
539                     if instrument:
540                         n.instrument_name = part_list.get_instrument (instrument.id)
541
542             # Incomplete first measures are not padded, but registered as partial
543             if is_first_measure:
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:
550                         m.partial = now
551             previous_measure = m
552
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)
561         return attributes
562
563     def extract_voices (part):
564         voices = {}
565         measures = part.get_typed_children (Measure)
566         elements = []
567         for m in measures:
568             if m.partial > 0:
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 = {}
574         for n in elements:
575             voice_id = n.get_maybe_exist_named_child (u'voice')
576             vid = None
577             if voice_id:
578                 vid = voice_id.get_text ()
579
580             staff_id = n.get_maybe_exist_named_child (u'staff')
581             sid = None
582             if staff_id:
583                 sid = staff_id.get_text ()
584             else:
585                 sid = "None"
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]
599             else:
600                 staff_to_voice_dict[s].append (v)
601
602
603         start_attr = None
604         for n in elements:
605             voice_id = n.get_maybe_exist_typed_child (get_class ('voice'))
606
607             if not (voice_id or isinstance (n, Attributes) or isinstance (n, Direction) or isinstance (n, Partial) ):
608                 continue
609
610             if isinstance (n, Attributes) and not start_attr:
611                 start_attr = n
612                 continue
613
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)
618                     for v in vids:
619                         voices[v].add_element (staff_attributes)
620                 continue
621
622             if isinstance (n, Partial):
623                 for v in voices.keys ():
624                     voices[v].add_element (n)
625                 continue
626
627             if isinstance (n, Direction):
628                 staff_id = n.get_maybe_exist_named_child (u'staff')
629                 if staff_id:
630                     staff_id = staff_id.get_text ()
631                 if staff_id:
632                     dir_voices = staff_to_voice_dict.get (staff_id, voices.keys ())
633                 else:
634                     dir_voices = voices.keys ()
635                 for v in dir_voices:
636                     voices[v].add_element (n)
637                 continue
638
639             id = voice_id.get_text ()
640             if hasattr (n, 'print-object') and getattr (n, 'print-object') == "no":
641                 #Skip this note. 
642                 pass
643             else:
644                 voices[id].add_element (n)
645
646         if start_attr:
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 ()
650                 for v in vids:
651                     voices[v].insert (0, staff_attributes)
652                     voices[v]._elements[0].read_self()
653
654         part._voices = voices
655
656     def get_voices (self):
657         return self._voices
658
659 class Notations (Music_xml_node):
660     def get_tie (self):
661         ts = self.get_named_children ('tied')
662         starts = [t for t in ts if t.type == 'start']
663         if starts:
664             return starts[0]
665         else:
666             return None
667
668     def get_tuplet (self):
669         return self.get_maybe_exist_typed_child (Tuplet)
670
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 ()))
676
677 class Accidental (Music_xml_node):
678     def __init__ (self):
679         Music_xml_node.__init__ (self)
680         self.editorial = False
681         self.cautionary = False
682
683 class Music_xml_spanner (Music_xml_node):
684     def get_type (self):
685         if hasattr (self, 'type'):
686             return self.type
687         else:
688             return 0
689     def get_size (self):
690         if hasattr (self, 'size'):
691             return string.atoi (self.size)
692         else:
693             return 0
694
695 class Wedge (Music_xml_spanner):
696     pass
697
698 class Tuplet (Music_xml_spanner):
699     pass
700
701 class Slur (Music_xml_spanner):
702     def get_type (self):
703         return self.type
704
705 class Beam (Music_xml_spanner):
706     def get_type (self):
707         return self.get_text ()
708     def is_primary (self):
709         return self.number == "1"
710
711 class Wavy_line (Music_xml_spanner):
712     pass
713     
714 class Pedal (Music_xml_spanner):
715     pass
716
717 class Glissando (Music_xml_spanner):
718     pass
719
720 class Octave_shift (Music_xml_spanner):
721     # default is 8 for the octave-shift!
722     def get_size (self):
723         if hasattr (self, 'size'):
724             return string.atoi (self.size)
725         else:
726             return 8
727
728 class Chord (Music_xml_node):
729     pass
730
731 class Dot (Music_xml_node):
732     pass
733
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):
737     def __init__ (self):
738         Music_xml_node.__init__ (self)
739         self._is_whole_measure = False
740     def is_whole_measure (self):
741         return self._is_whole_measure
742     def get_step (self):
743         ch = self.get_maybe_exist_typed_child (get_class (u'display-step'))
744         if ch:
745             step = ch.get_text ().strip ()
746             return step
747         else:
748             return None
749     def get_octave (self):
750         ch = self.get_maybe_exist_typed_child (get_class (u'display-octave'))
751         if ch:
752             step = ch.get_text ().strip ()
753             return int (step)
754         else:
755             return None
756
757 class Type (Music_xml_node):
758     pass
759 class Grace (Music_xml_node):
760     pass
761 class Staff (Music_xml_node):
762     pass
763
764 class Direction (Music_xml_node):
765     pass
766 class DirType (Music_xml_node):
767     pass
768
769 class Bend (Music_xml_node):
770     def bend_alter (self):
771         alter = self.get_maybe_exist_named_child ('bend-alter')
772         if alter:
773             return alter.get_text()
774         else:
775             return 0
776
777
778
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!
782 class_dict = {
783         '#comment': Hash_comment,
784         '#text': Hash_text,
785         'accidental': Accidental,
786         'attributes': Attributes,
787         'beam' : Beam,
788         'bend' : Bend,
789         'chord': Chord,
790         'dot': Dot,
791         'direction': Direction,
792         'direction-type': DirType,
793         'duration': Duration,
794         'glissando': Glissando,
795         'grace': Grace,
796         'identification': Identification,
797         'lyric': Lyric,
798         'measure': Measure,
799         'notations': Notations,
800         'note': Note,
801         'octave-shift': Octave_shift,
802         'part': Part,
803     'part-group': Part_group,
804         'part-list': Part_list,
805         'pedal': Pedal,
806         'pitch': Pitch,
807         'rest': Rest,
808     'score-part': Score_part,
809         'slur': Slur,
810         'staff': Staff,
811         'syllabic': Syllabic,
812         'text': Text,
813         'time-modification': Time_modification,
814         'tuplet': Tuplet,
815         'type': Type,
816         'wavy-line': Wavy_line,
817         'wedge': Wedge,
818         'work': Work,
819 }
820
821 def name2class_name (name):
822     name = name.replace ('-', '_')
823     name = name.replace ('#', 'hash_')
824     name = name[0].upper() + name[1:].lower()
825
826     return str (name)
827
828 def get_class (name):
829     classname = class_dict.get (name)
830     if classname:
831         return classname
832     else:
833         class_name = name2class_name (name)
834         klass = new.classobj (class_name, (Music_xml_node,) , {})
835         class_dict[name] = klass
836         return klass
837         
838 def lxml_demarshal_node (node):
839     name = node.tag
840
841     if name is None:
842         return None
843     klass = get_class (name)
844     py_node = klass()
845     
846     py_node._original = node
847     py_node._name = name
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)
851     
852     for c in py_node._children:
853         c._parent = py_node
854
855     for (k,v) in node.items ():
856         py_node.__dict__[k] = v
857         py_node._attribute_dict[k] = v
858
859     return py_node
860
861 def minidom_demarshal_node (node):
862     name = node.nodeName
863
864     klass = get_class (name)
865     py_node = klass()
866     py_node._name = name
867     py_node._children = [minidom_demarshal_node (cn) for cn in node.childNodes]
868     for c in py_node._children:
869         c._parent = py_node
870
871     if node.attributes:
872         for (nm, value) in node.attributes.items():
873             py_node.__dict__[nm] = value
874             py_node._attribute_dict[nm] = value
875             
876     py_node._data = None
877     if node.nodeType == node.TEXT_NODE and node.data:
878         py_node._data = node.data 
879
880     py_node._original = node
881     return py_node
882
883
884 if __name__  == '__main__':
885         import lxml.etree
886         
887         tree = lxml.etree.parse ('beethoven.xml')
888         mxl_tree = lxml_demarshal_node (tree.getroot ())
889         ks = class_dict.keys()
890         ks.sort()
891         print '\n'.join (ks)