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