]> git.donarmstrong.com Git - lilypond.git/blob - python/musicxml.py
MusicXML: Implement after-grace notes
[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         self._after_grace = False
356     def is_grace (self):
357         return self.get_maybe_exist_named_child (u'grace')
358     def is_after_grace (self):
359         if not self.is_grace():
360             return False;
361         gr = self.get_maybe_exist_typed_child (Grace)
362         return self._after_grace or hasattr (gr, 'steal-time-previous');
363
364     def get_duration_log (self):
365         ch = self.get_maybe_exist_named_child (u'type')
366
367         if ch:
368             log = ch.get_text ().strip()
369             return musicxml_duration_to_log (log)
370         elif self.get_maybe_exist_named_child (u'grace'):
371             # FIXME: is it ok to default to eight note for grace notes?
372             return 3
373         else:
374             self.message (_ ("Encountered note at %s with %s duration (no <type> element):") % (self.start, self.duration) )
375             return 0
376
377     def get_factor (self):
378         return 1
379
380     def get_pitches (self):
381         return self.get_typed_children (get_class (u'pitch'))
382
383 class Part_list (Music_xml_node):
384     def __init__ (self):
385         Music_xml_node.__init__ (self)
386         self._id_instrument_name_dict = {}
387         
388     def generate_id_instrument_dict (self):
389
390         ## not empty to make sure this happens only once.
391         mapping = {1: 1}
392         for score_part in self.get_named_children ('score-part'):
393             for instr in score_part.get_named_children ('score-instrument'):
394                 id = instr.id
395                 name = instr.get_named_child ("instrument-name")
396                 mapping[id] = name.get_text ()
397
398         self._id_instrument_name_dict = mapping
399
400     def get_instrument (self, id):
401         if not self._id_instrument_name_dict:
402             self.generate_id_instrument_dict()
403
404         instrument_name = self._id_instrument_name_dict.get (id)
405         if instrument_name:
406             return instrument_name
407         else:
408             ly.stderr_write (_ ("Unable to find instrument for ID=%s\n") % id)
409             return "Grand Piano"
410
411 class Part_group (Music_xml_node):
412     pass
413 class Score_part (Music_xml_node):
414     pass
415         
416 class Measure (Music_xml_node):
417     def __init__ (self):
418         Music_xml_node.__init__ (self)
419         self.partial = 0
420     def is_implicit (self):
421         return hasattr (self, 'implicit') and self.implicit == 'yes'
422     def get_notes (self):
423         return self.get_typed_children (get_class (u'note'))
424
425 class Syllabic (Music_xml_node):
426     def continued (self):
427         text = self.get_text()
428         return (text == "begin") or (text == "middle")
429 class Text (Music_xml_node):
430     pass
431
432 class Lyric (Music_xml_node):
433     def get_number (self):
434         if hasattr (self, 'number'):
435             return self.number
436         else:
437             return -1
438
439     def lyric_to_text (self):
440         continued = False
441         syllabic = self.get_maybe_exist_typed_child (Syllabic)
442         if syllabic:
443             continued = syllabic.continued ()
444         text = self.get_maybe_exist_typed_child (Text)
445         
446         if text:
447             text = text.get_text()
448             # We need to convert soft hyphens to -, otherwise the ascii codec as well
449             # as lilypond will barf on that character
450             text = string.replace( text, u'\xad', '-' )
451         
452         if text == "-" and continued:
453             return "--"
454         elif text == "_" and continued:
455             return "__"
456         elif continued and text:
457             return escape_ly_output_string (text) + " --"
458         elif continued:
459             return "--"
460         elif text:
461             return escape_ly_output_string (text)
462         else:
463             return ""
464
465 class Musicxml_voice:
466     def __init__ (self):
467         self._elements = []
468         self._staves = {}
469         self._start_staff = None
470         self._lyrics = []
471         self._has_lyrics = False
472
473     def add_element (self, e):
474         self._elements.append (e)
475         if (isinstance (e, Note)
476             and e.get_maybe_exist_typed_child (Staff)):
477             name = e.get_maybe_exist_typed_child (Staff).get_text ()
478
479             if not self._start_staff and not e.get_maybe_exist_typed_child (Grace):
480                 self._start_staff = name
481             self._staves[name] = True
482
483         lyrics = e.get_typed_children (Lyric)
484         if not self._has_lyrics:
485           self.has_lyrics = len (lyrics) > 0
486
487         for l in lyrics:
488             nr = l.get_number()
489             if (nr > 0) and not (nr in self._lyrics):
490                 self._lyrics.append (nr)
491
492     def insert (self, idx, e):
493         self._elements.insert (idx, e)
494
495     def get_lyrics_numbers (self):
496         if (len (self._lyrics) == 0) and self._has_lyrics:
497             #only happens if none of the <lyric> tags has a number attribute
498             return [1]
499         else:
500             return self._lyrics
501
502
503 class Part (Music_xml_node):
504     def __init__ (self):
505         Music_xml_node.__init__ (self)
506         self._voices = {}
507         self._staff_attributes_dict = {}
508
509     def get_part_list (self):
510         n = self
511         while n and n.get_name() != 'score-partwise':
512             n = n._parent
513
514         return n.get_named_child ('part-list')
515         
516     def interpret (self):
517         """Set durations and starting points."""
518         """The starting point of the very first note is 0!"""
519         
520         part_list = self.get_part_list ()
521         
522         now = Rational (0)
523         factor = Rational (1)
524         attributes_dict = {}
525         attributes_object = None
526         measures = self.get_typed_children (Measure)
527         last_moment = Rational (-1)
528         last_measure_position = Rational (-1)
529         measure_position = Rational (0)
530         measure_start_moment = now
531         is_first_measure = True
532         previous_measure = None
533         # Graces at the end of a measure need to have their position set to the
534         # previous number!
535         pending_graces = []
536         for m in measures:
537             # implicit measures are used for artificial measures, e.g. when
538             # a repeat bar line splits a bar into two halves. In this case,
539             # don't reset the measure position to 0. They are also used for
540             # upbeats (initial value of 0 fits these, too).
541             # Also, don't reset the measure position at the end of the loop,
542             # but rather when starting the next measure (since only then do we
543             # know if the next measure is implicit and continues that measure)
544             if not m.is_implicit ():
545                 # Warn about possibly overfull measures and reset the position
546                 if attributes_object and previous_measure and previous_measure.partial == 0:
547                     length = attributes_object.get_measure_length ()
548                     new_now = measure_start_moment + length
549                     if now <> new_now:
550                         problem = 'incomplete'
551                         if now > new_now:
552                             problem = 'overfull'
553                         ## only for verbose operation.
554                         if problem <> 'incomplete' and previous_measure:
555                             previous_measure.message ('%s measure? Expected: %s, Difference: %s' % (problem, now, new_now - now))
556                     now = new_now
557                 measure_start_moment = now
558                 measure_position = Rational (0)
559
560             for n in m.get_all_children ():
561                 # figured bass has a duration, but applies to the next note
562                 # and should not change the current measure position!
563                 if isinstance (n, FiguredBass):
564                     n._divisions = factor.denominator ()
565                     n._when = now
566                     n._measure_position = measure_position
567                     continue
568
569                 if isinstance (n, Hash_text):
570                     continue
571                 dur = Rational (0)
572
573                 if n.__class__ == Attributes:
574                     n.set_attributes_from_previous (attributes_dict)
575                     n.read_self ()
576                     attributes_dict = n._dict.copy ()
577                     attributes_object = n
578                     
579                     factor = Rational (1,
580                                        int (attributes_dict.get ('divisions').get_text ()))
581
582                 
583                 if (n.get_maybe_exist_typed_child (Duration)):
584                     mxl_dur = n.get_maybe_exist_typed_child (Duration)
585                     dur = mxl_dur.get_length () * factor
586                     
587                     if n.get_name() == 'backup':
588                         dur = - dur
589                         # reset all graces before the backup to after-graces:
590                         for n in pending_graces:
591                             n._when = n._prev_when
592                             n._measure_position = n._prev_measure_position
593                             n._after_grace = True
594                         pending_graces = []
595                     if n.get_maybe_exist_typed_child (Grace):
596                         dur = Rational (0)
597
598                     rest = n.get_maybe_exist_typed_child (Rest)
599                     if (rest
600                         and attributes_object
601                         and attributes_object.get_measure_length () == dur):
602
603                         rest._is_whole_measure = True
604
605                 if (dur > Rational (0) 
606                     and n.get_maybe_exist_typed_child (Chord)):
607                     now = last_moment
608                     measure_position = last_measure_position
609
610                 n._when = now
611                 n._measure_position = measure_position
612
613                 # For all grace notes, store the previous note,  in case need
614                 # to turn the grace note into an after-grace later on!
615                 if isinstance(n, Note) and n.is_grace ():
616                     n._prev_when = last_moment
617                     n._prev_measure_position = last_measure_position
618                 # After-graces are placed at the same position as the previous note
619                 if isinstance(n, Note) and  n.is_after_grace ():
620                     # TODO: We should do the same for grace notes at the end of 
621                     # a measure with no following note!!!
622                     n._when = last_moment
623                     n._measure_position = last_measure_position
624                 elif isinstance(n, Note) and n.is_grace ():
625                     pending_graces.append (n)
626                 elif (dur > Rational (0)):
627                     pending_graces = [];
628
629                 n._duration = dur
630                 if dur > Rational (0):
631                     last_moment = now
632                     last_measure_position = measure_position
633                     now += dur
634                     measure_position += dur
635                 elif dur < Rational (0):
636                     # backup element, reset measure position
637                     now += dur
638                     measure_position += dur
639                     if measure_position < 0:
640                         # backup went beyond the measure start => reset to 0
641                         now -= measure_position
642                         measure_position = 0
643                     last_moment = now
644                     last_measure_position = measure_position
645                 if n._name == 'note':
646                     instrument = n.get_maybe_exist_named_child ('instrument')
647                     if instrument:
648                         n.instrument_name = part_list.get_instrument (instrument.id)
649
650             # reset all graces at the end of the measure to after-graces:
651             for n in pending_graces:
652                 n._when = n._prev_when
653                 n._measure_position = n._prev_measure_position
654                 n._after_grace = True
655             pending_graces = []
656             # Incomplete first measures are not padded, but registered as partial
657             if is_first_measure:
658                 is_first_measure = False
659                 # upbeats are marked as implicit measures
660                 if attributes_object and m.is_implicit ():
661                     length = attributes_object.get_measure_length ()
662                     measure_end = measure_start_moment + length
663                     if measure_end <> now:
664                         m.partial = now
665             previous_measure = m
666
667     # modify attributes so that only those applying to the given staff remain
668     def extract_attributes_for_staff (part, attr, staff):
669         attributes = copy.copy (attr)
670         attributes._children = [];
671         attributes._dict = attr._dict.copy ()
672         attributes._original_tag = attr
673         # copy only the relevant children over for the given staff
674         for c in attr._children:
675             if (not (hasattr (c, 'number') and (c.number != staff)) and
676                 not (isinstance (c, Hash_text))):
677                 attributes._children.append (c)
678         if not attributes._children:
679             return None
680         else:
681             return attributes
682
683     def extract_voices (part):
684         voices = {}
685         measures = part.get_typed_children (Measure)
686         elements = []
687         for m in measures:
688             if m.partial > 0:
689                 elements.append (Partial (m.partial))
690             elements.extend (m.get_all_children ())
691         # make sure we know all voices already so that dynamics, clefs, etc.
692         # can be assigned to the correct voices
693         voice_to_staff_dict = {}
694         for n in elements:
695             voice_id = n.get_maybe_exist_named_child (u'voice')
696             vid = None
697             if voice_id:
698                 vid = voice_id.get_text ()
699
700             staff_id = n.get_maybe_exist_named_child (u'staff')
701             sid = None
702             if staff_id:
703                 sid = staff_id.get_text ()
704             else:
705                 sid = "None"
706             if vid and not voices.has_key (vid):
707                 voices[vid] = Musicxml_voice()
708             if vid and sid and not n.get_maybe_exist_typed_child (Grace):
709                 if not voice_to_staff_dict.has_key (vid):
710                     voice_to_staff_dict[vid] = sid
711         # invert the voice_to_staff_dict into a staff_to_voice_dict (since we
712         # need to assign staff-assigned objects like clefs, times, etc. to
713         # all the correct voices. This will never work entirely correct due
714         # to staff-switches, but that's the best we can do!
715         staff_to_voice_dict = {}
716         for (v,s) in voice_to_staff_dict.items ():
717             if not staff_to_voice_dict.has_key (s):
718                 staff_to_voice_dict[s] = [v]
719             else:
720                 staff_to_voice_dict[s].append (v)
721
722
723         start_attr = None
724         assign_to_next_note = []
725         id = None
726         for n in elements:
727             voice_id = n.get_maybe_exist_typed_child (get_class ('voice'))
728
729             if not (voice_id or isinstance (n, Attributes) or
730                     isinstance (n, Direction) or isinstance (n, Partial) or
731                     isinstance (n, Barline) or isinstance (n, Harmony) or
732                     isinstance (n, FiguredBass) ):
733                 continue
734
735             if isinstance (n, Attributes) and not start_attr:
736                 start_attr = n
737                 continue
738
739             if isinstance (n, Attributes):
740                 # assign these only to the voices they really belongs to!
741                 for (s, vids) in staff_to_voice_dict.items ():
742                     staff_attributes = part.extract_attributes_for_staff (n, s)
743                     if staff_attributes:
744                         for v in vids:
745                             voices[v].add_element (staff_attributes)
746                 continue
747
748             if isinstance (n, Partial) or isinstance (n, Barline):
749                 for v in voices.keys ():
750                     voices[v].add_element (n)
751                 continue
752
753             if isinstance (n, Direction):
754                 staff_id = n.get_maybe_exist_named_child (u'staff')
755                 if staff_id:
756                     staff_id = staff_id.get_text ()
757                 if staff_id:
758                     dir_voices = staff_to_voice_dict.get (staff_id, voices.keys ())
759                 else:
760                     dir_voices = voices.keys ()
761                 for v in dir_voices:
762                     voices[v].add_element (n)
763                 continue
764
765             if isinstance (n, Harmony) or isinstance (n, FiguredBass):
766                 # store the harmony or figured bass element until we encounter 
767                 # the next note and assign it only to that one voice.
768                 assign_to_next_note.append (n)
769                 continue
770
771             id = voice_id.get_text ()
772             if hasattr (n, 'print-object') and getattr (n, 'print-object') == "no":
773                 #Skip this note. 
774                 pass
775             else:
776                 for i in assign_to_next_note:
777                     voices[id].add_element (i)
778                 assign_to_next_note = []
779                 voices[id].add_element (n)
780
781         # Assign all remaining elements from assign_to_next_note to the voice
782         # of the previous note:
783         for i in assign_to_next_note:
784             voices[id].add_element (i)
785         assign_to_next_note = []
786
787         if start_attr:
788             for (s, vids) in staff_to_voice_dict.items ():
789                 staff_attributes = part.extract_attributes_for_staff (start_attr, s)
790                 staff_attributes.read_self ()
791                 part._staff_attributes_dict[s] = staff_attributes
792                 for v in vids:
793                     voices[v].insert (0, staff_attributes)
794                     voices[v]._elements[0].read_self()
795
796         part._voices = voices
797
798     def get_voices (self):
799         return self._voices
800     def get_staff_attributes (self):
801         return self._staff_attributes_dict
802
803 class Notations (Music_xml_node):
804     def get_tie (self):
805         ts = self.get_named_children ('tied')
806         starts = [t for t in ts if t.type == 'start']
807         if starts:
808             return starts[0]
809         else:
810             return None
811
812     def get_tuplets (self):
813         return self.get_typed_children (Tuplet)
814
815 class Time_modification(Music_xml_node):
816     def get_fraction (self):
817         b = self.get_maybe_exist_named_child ('actual-notes')
818         a = self.get_maybe_exist_named_child ('normal-notes')
819         return (int(a.get_text ()), int (b.get_text ()))
820
821 class Accidental (Music_xml_node):
822     def __init__ (self):
823         Music_xml_node.__init__ (self)
824         self.editorial = False
825         self.cautionary = False
826
827 class Music_xml_spanner (Music_xml_node):
828     def get_type (self):
829         if hasattr (self, 'type'):
830             return self.type
831         else:
832             return 0
833     def get_size (self):
834         if hasattr (self, 'size'):
835             return string.atoi (self.size)
836         else:
837             return 0
838
839 class Wedge (Music_xml_spanner):
840     pass
841
842 class Tuplet (Music_xml_spanner):
843     pass
844
845 class Bracket (Music_xml_spanner):
846     pass
847
848 class Dashes (Music_xml_spanner):
849     pass
850
851 class Slur (Music_xml_spanner):
852     def get_type (self):
853         return self.type
854
855 class Beam (Music_xml_spanner):
856     def get_type (self):
857         return self.get_text ()
858     def is_primary (self):
859         return self.number == "1"
860
861 class Wavy_line (Music_xml_spanner):
862     pass
863     
864 class Pedal (Music_xml_spanner):
865     pass
866
867 class Glissando (Music_xml_spanner):
868     pass
869
870 class Slide (Music_xml_spanner):
871     pass
872
873 class Octave_shift (Music_xml_spanner):
874     # default is 8 for the octave-shift!
875     def get_size (self):
876         if hasattr (self, 'size'):
877             return string.atoi (self.size)
878         else:
879             return 8
880
881 class Chord (Music_xml_node):
882     pass
883
884 class Dot (Music_xml_node):
885     pass
886
887 # Rests in MusicXML are <note> blocks with a <rest> inside. This class is only
888 # for the inner <rest> element, not the whole rest block.
889 class Rest (Music_xml_node):
890     def __init__ (self):
891         Music_xml_node.__init__ (self)
892         self._is_whole_measure = False
893     def is_whole_measure (self):
894         return self._is_whole_measure
895     def get_step (self):
896         ch = self.get_maybe_exist_typed_child (get_class (u'display-step'))
897         if ch:
898             step = ch.get_text ().strip ()
899             return step
900         else:
901             return None
902     def get_octave (self):
903         ch = self.get_maybe_exist_typed_child (get_class (u'display-octave'))
904         if ch:
905             step = ch.get_text ().strip ()
906             return int (step)
907         else:
908             return None
909
910 class Type (Music_xml_node):
911     pass
912 class Grace (Music_xml_node):
913     pass
914 class Staff (Music_xml_node):
915     pass
916
917 class Direction (Music_xml_node):
918     pass
919 class DirType (Music_xml_node):
920     pass
921
922 class Bend (Music_xml_node):
923     def bend_alter (self):
924         alter = self.get_maybe_exist_named_child ('bend-alter')
925         if alter:
926             return alter.get_text()
927         else:
928             return 0
929
930 class Words (Music_xml_node):
931     pass
932
933 class Harmony (Music_xml_node):
934     pass
935
936 class ChordPitch (Music_xml_node):
937     def step_class_name (self):
938         return u'root-step'
939     def alter_class_name (self):
940         return u'root-alter'
941     def get_step (self):
942         ch = self.get_unique_typed_child (get_class (self.step_class_name ()))
943         return ch.get_text ().strip ()
944     def get_alteration (self):
945         ch = self.get_maybe_exist_typed_child (get_class (self.alter_class_name ()))
946         alter = 0
947         if ch:
948             alter = int (ch.get_text ().strip ())
949         return alter
950
951 class Root (ChordPitch):
952     pass
953
954 class Bass (ChordPitch):
955     def step_class_name (self):
956         return u'bass-step'
957     def alter_class_name (self):
958         return u'bass-alter'
959
960 class ChordModification (Music_xml_node):
961     def get_type (self):
962         ch = self.get_maybe_exist_typed_child (get_class (u'degree-type'))
963         return {'add': 1, 'alter': 1, 'subtract': -1}.get (ch.get_text ().strip (), 0)
964     def get_value (self):
965         ch = self.get_maybe_exist_typed_child (get_class (u'degree-value'))
966         value = 0
967         if ch:
968             value = int (ch.get_text ().strip ())
969         return value
970     def get_alter (self):
971         ch = self.get_maybe_exist_typed_child (get_class (u'degree-alter'))
972         value = 0
973         if ch:
974             value = int (ch.get_text ().strip ())
975         return value
976
977
978 class Frame (Music_xml_node):
979     def get_frets (self):
980         return self.get_named_child_value_number ('frame-frets', 4)
981     def get_strings (self):
982         return self.get_named_child_value_number ('frame-strings', 6)
983     def get_first_fret (self):
984         return self.get_named_child_value_number ('first-fret', 1)
985
986 class Frame_Note (Music_xml_node):
987     def get_string (self):
988         return self.get_named_child_value_number ('string', 1)
989     def get_fret (self):
990         return self.get_named_child_value_number ('fret', 0)
991     def get_fingering (self):
992         return self.get_named_child_value_number ('fingering', -1)
993     def get_barre (self):
994         n = self.get_maybe_exist_named_child ('barre')
995         if n:
996             return getattr (n, 'type', '')
997         else:
998             return ''
999
1000 class FiguredBass (Music_xml_node):
1001     pass
1002
1003 class BeatUnit (Music_xml_node):
1004     pass
1005
1006 class BeatUnitDot (Music_xml_node):
1007     pass
1008
1009 class PerMinute (Music_xml_node):
1010     pass
1011
1012
1013
1014 ## need this, not all classes are instantiated
1015 ## for every input file. Only add those classes, that are either directly
1016 ## used by class name or extend Music_xml_node in some way!
1017 class_dict = {
1018         '#comment': Hash_comment,
1019         '#text': Hash_text,
1020         'accidental': Accidental,
1021         'attributes': Attributes,
1022         'barline': Barline,
1023         'bar-style': BarStyle,
1024         'bass': Bass,
1025         'beam' : Beam,
1026         'beat-unit': BeatUnit,
1027         'beat-unit-dot': BeatUnitDot,
1028         'bend' : Bend,
1029         'bracket' : Bracket,
1030         'chord': Chord,
1031         'dashes' : Dashes,
1032         'degree' : ChordModification,
1033         'dot': Dot,
1034         'direction': Direction,
1035         'direction-type': DirType,
1036         'duration': Duration,
1037         'frame': Frame,
1038         'frame-note': Frame_Note,
1039         'figured-bass': FiguredBass,
1040         'glissando': Glissando,
1041         'grace': Grace,
1042         'harmony': Harmony,
1043         'identification': Identification,
1044         'lyric': Lyric,
1045         'measure': Measure,
1046         'notations': Notations,
1047         'note': Note,
1048         'octave-shift': Octave_shift,
1049         'part': Part,
1050     'part-group': Part_group,
1051         'part-list': Part_list,
1052         'pedal': Pedal,
1053         'per-minute': PerMinute,
1054         'pitch': Pitch,
1055         'rest': Rest,
1056         'root': Root,
1057         'score-part': Score_part,
1058         'slide': Slide,
1059         'slur': Slur,
1060         'staff': Staff,
1061         'syllabic': Syllabic,
1062         'text': Text,
1063         'time-modification': Time_modification,
1064         'tuplet': Tuplet,
1065         'type': Type,
1066         'unpitched': Unpitched,
1067         'wavy-line': Wavy_line,
1068         'wedge': Wedge,
1069         'words': Words,
1070         'work': Work,
1071 }
1072
1073 def name2class_name (name):
1074     name = name.replace ('-', '_')
1075     name = name.replace ('#', 'hash_')
1076     name = name[0].upper() + name[1:].lower()
1077
1078     return str (name)
1079
1080 def get_class (name):
1081     classname = class_dict.get (name)
1082     if classname:
1083         return classname
1084     else:
1085         class_name = name2class_name (name)
1086         klass = new.classobj (class_name, (Music_xml_node,) , {})
1087         class_dict[name] = klass
1088         return klass
1089         
1090 def lxml_demarshal_node (node):
1091     name = node.tag
1092
1093     # Ignore comment nodes, which are also returned by the etree parser!
1094     if name is None or node.__class__.__name__ == "_Comment":
1095         return None
1096     klass = get_class (name)
1097     py_node = klass()
1098     
1099     py_node._original = node
1100     py_node._name = name
1101     py_node._data = node.text
1102     py_node._children = [lxml_demarshal_node (cn) for cn in node.getchildren()]
1103     py_node._children = filter (lambda x: x, py_node._children)
1104     
1105     for c in py_node._children:
1106         c._parent = py_node
1107
1108     for (k, v) in node.items ():
1109         py_node.__dict__[k] = v
1110         py_node._attribute_dict[k] = v
1111
1112     return py_node
1113
1114 def minidom_demarshal_node (node):
1115     name = node.nodeName
1116
1117     klass = get_class (name)
1118     py_node = klass ()
1119     py_node._name = name
1120     py_node._children = [minidom_demarshal_node (cn) for cn in node.childNodes]
1121     for c in py_node._children:
1122         c._parent = py_node
1123
1124     if node.attributes:
1125         for (nm, value) in node.attributes.items ():
1126             py_node.__dict__[nm] = value
1127             py_node._attribute_dict[nm] = value
1128             
1129     py_node._data = None
1130     if node.nodeType == node.TEXT_NODE and node.data:
1131         py_node._data = node.data 
1132
1133     py_node._original = node
1134     return py_node
1135
1136
1137 if __name__  == '__main__':
1138     import lxml.etree
1139         
1140     tree = lxml.etree.parse ('beethoven.xml')
1141     mxl_tree = lxml_demarshal_node (tree.getroot ())
1142     ks = class_dict.keys ()
1143     ks.sort ()
1144     print '\n'.join (ks)