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