1 # -*- coding: utf-8 -*-
13 ly
.stderr_write ((_ ("error: %s") % str) + "\n")
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
);
20 return_string
= "\"" + string
.replace (return_string
, "\"", "\\\"") + "\""
24 def musicxml_duration_to_log (dur
):
36 'long': -2}.get (dur
, 0)
45 self
._name
= 'xml_node'
47 self
._attribute
_dict
= {}
49 def get_parent (self
):
53 return self
._parent
.get_typed_children (self
.__class
__)[0] == self
64 if not self
._children
:
67 return ''.join ([c
.get_text () for c
in self
._children
])
69 def message (self
, msg
):
70 ly
.stderr_write (msg
+'\n')
74 sys
.stderr
.write (' In: <%s %s>\n' % (p
._name
, ' '.join (['%s=%s' % item
for item
in p
._attribute
_dict
.items ()])))
77 def get_typed_children (self
, klass
):
81 return [c
for c
in self
._children
if isinstance(c
, klass
)]
83 def get_named_children (self
, nm
):
84 return self
.get_typed_children (get_class (nm
))
86 def get_named_child (self
, nm
):
87 return self
.get_maybe_exist_named_child (nm
)
89 def get_children (self
, predicate
):
90 return [c
for c
in self
._children
if predicate(c
)]
92 def get_all_children (self
):
95 def get_maybe_exist_named_child (self
, name
):
96 return self
.get_maybe_exist_typed_child (get_class (name
))
98 def get_maybe_exist_typed_child (self
, klass
):
99 cn
= self
.get_typed_children (klass
)
105 raise "More than 1 child", klass
107 def get_unique_typed_child (self
, klass
):
108 cn
= self
.get_typed_children(klass
)
110 sys
.stderr
.write (self
.__dict
__ + '\n')
111 raise 'Child is not unique for', (klass
, 'found', cn
)
115 def get_named_child_value_number (self
, name
, default
):
116 n
= self
.get_maybe_exist_named_child (name
)
118 return string
.atoi (n
.get_text())
123 class Music_xml_node (Xml_node
):
125 Xml_node
.__init
__ (self
)
126 self
.duration
= Rational (0)
127 self
.start
= Rational (0)
129 class Work (Xml_node
):
130 def get_work_information (self
, tag
):
131 wt
= self
.get_maybe_exist_named_child (tag
)
133 return wt
.get_text ()
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')
142 return self
.get_work_information ('opus')
144 class Identification (Xml_node
):
145 def get_rights (self
):
146 rights
= self
.get_maybe_exist_named_child ('rights')
148 return rights
.get_text ()
152 def get_creator (self
, type):
153 creators
= self
.get_named_children ('creator')
154 # return the first creator tag that has the particular type
156 if hasattr (i
, 'type') and i
.type == type:
160 def get_composer (self
):
161 c
= self
.get_creator ('composer')
164 creators
= self
.get_named_children ('creator')
165 # return the first creator tag that has no type at all
167 if not hasattr (i
, 'type'):
170 def get_arranger (self
):
171 return self
.get_creator ('arranger')
172 def get_editor (self
):
173 return self
.get_creator ('editor')
175 v
= self
.get_creator ('lyricist')
178 v
= self
.get_creator ('poet')
181 def get_encoding_information (self
, type):
182 enc
= self
.get_named_children ('encoding')
184 children
= enc
[0].get_named_children (type)
186 return children
[0].get_text ()
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')
199 def get_encoding_software_list (self
):
200 enc
= self
.get_named_children ('encoding')
203 softwares
= e
.get_named_children ('software')
205 software
.append (s
.get_text ())
208 def get_file_description (self
):
209 misc
= self
.get_named_children ('miscellaneous')
211 misc_fields
= m
.get_named_children ('miscellaneous-field')
212 for mf
in misc_fields
:
213 if hasattr (mf
, 'name') and mf
.name
== 'description':
214 return mf
.get_text ()
219 class Duration (Music_xml_node
):
220 def get_length (self
):
221 dur
= int (self
.get_text ()) * Rational (1,4)
224 class Hash_comment (Music_xml_node
):
226 class Hash_text (Music_xml_node
):
229 class Pitch (Music_xml_node
):
231 ch
= self
.get_unique_typed_child (get_class (u
'step'))
232 step
= ch
.get_text ().strip ()
234 def get_octave (self
):
235 ch
= self
.get_unique_typed_child (get_class (u
'octave'))
237 step
= ch
.get_text ().strip ()
240 def get_alteration (self
):
241 ch
= self
.get_maybe_exist_typed_child (get_class (u
'alter'))
244 alter
= int (ch
.get_text ().strip ())
247 class Unpitched (Music_xml_node
):
249 ch
= self
.get_unique_typed_child (get_class (u
'display-step'))
250 step
= ch
.get_text ().strip ()
253 def get_octave (self
):
254 ch
= self
.get_unique_typed_child (get_class (u
'display-octave'))
257 octave
= ch
.get_text ().strip ()
262 class Measure_element (Music_xml_node
):
263 def get_voice_id (self
):
264 voice_id
= self
.get_maybe_exist_named_child ('voice')
266 return voice_id
.get_text ()
271 # Look at all measure elements (previously we had self.__class__, which
272 # only looked at objects of the same type!
273 cn
= self
._parent
.get_typed_children (Measure_element
)
274 # But only look at the correct voice; But include Attributes, too, which
275 # are not tied to any particular voice
276 cn
= [c
for c
in cn
if (c
.get_voice_id () == self
.get_voice_id ()) or isinstance (c
, Attributes
)]
279 class Attributes (Measure_element
):
281 Measure_element
.__init
__ (self
)
283 self
._original
_tag
= None
286 cn
= self
._parent
.get_typed_children (self
.__class
__)
287 if self
._original
_tag
:
288 return cn
[0] == self
._original
_tag
292 def set_attributes_from_previous (self
, dict):
293 self
._dict
.update (dict)
295 def read_self (self
):
296 for c
in self
.get_all_children ():
297 self
._dict
[c
.get_name()] = c
299 def get_named_attribute (self
, name
):
300 return self
._dict
.get (name
)
302 def get_measure_length (self
):
303 (n
,d
) = self
.get_time_signature ()
304 return Rational (n
,d
)
306 def get_time_signature (self
):
307 "return time sig as a (beat, beat-type) tuple"
310 mxl
= self
.get_named_attribute ('time')
312 beats
= mxl
.get_maybe_exist_named_child ('beats')
313 type = mxl
.get_maybe_exist_named_child ('beat-type')
314 return (int (beats
.get_text ()),
315 int (type.get_text ()))
319 error (_ ("requested time signature, but time sig is unknown"))
322 # returns clef information in the form ("cleftype", position, octave-shift)
323 def get_clef_information (self
):
324 clefinfo
= ['G', 2, 0]
325 mxl
= self
.get_named_attribute ('clef')
328 sign
= mxl
.get_maybe_exist_named_child ('sign')
330 clefinfo
[0] = sign
.get_text()
331 line
= mxl
.get_maybe_exist_named_child ('line')
333 clefinfo
[1] = string
.atoi (line
.get_text ())
334 octave
= mxl
.get_maybe_exist_named_child ('clef-octave-change')
336 clefinfo
[2] = string
.atoi (octave
.get_text ())
339 def get_key_signature (self
):
340 "return (fifths, mode) tuple"
342 key
= self
.get_named_attribute ('key')
343 mode_node
= key
.get_maybe_exist_named_child ('mode')
346 mode
= mode_node
.get_text ()
348 fifths
= int (key
.get_maybe_exist_named_child ('fifths').get_text ())
349 return (fifths
, mode
)
351 class Barline (Measure_element
):
353 class BarStyle (Music_xml_node
):
355 class Partial (Measure_element
):
356 def __init__ (self
, partial
):
357 Measure_element
.__init
__ (self
)
358 self
.partial
= partial
360 class Note (Measure_element
):
362 Measure_element
.__init
__ (self
)
363 self
.instrument_name
= ''
364 self
._after
_grace
= False
366 return self
.get_maybe_exist_named_child (u
'grace')
367 def is_after_grace (self
):
368 if not self
.is_grace():
370 gr
= self
.get_maybe_exist_typed_child (Grace
)
371 return self
._after
_grace
or hasattr (gr
, 'steal-time-previous');
373 def get_duration_log (self
):
374 ch
= self
.get_maybe_exist_named_child (u
'type')
377 log
= ch
.get_text ().strip()
378 return musicxml_duration_to_log (log
)
379 elif self
.get_maybe_exist_named_child (u
'grace'):
380 # FIXME: is it ok to default to eight note for grace notes?
383 self
.message (_ ("Encountered note at %s with %s duration (no <type> element):") % (self
.start
, self
.duration
) )
386 def get_factor (self
):
389 def get_pitches (self
):
390 return self
.get_typed_children (get_class (u
'pitch'))
392 class Part_list (Music_xml_node
):
394 Music_xml_node
.__init
__ (self
)
395 self
._id
_instrument
_name
_dict
= {}
397 def generate_id_instrument_dict (self
):
399 ## not empty to make sure this happens only once.
401 for score_part
in self
.get_named_children ('score-part'):
402 for instr
in score_part
.get_named_children ('score-instrument'):
404 name
= instr
.get_named_child ("instrument-name")
405 mapping
[id] = name
.get_text ()
407 self
._id
_instrument
_name
_dict
= mapping
409 def get_instrument (self
, id):
410 if not self
._id
_instrument
_name
_dict
:
411 self
.generate_id_instrument_dict()
413 instrument_name
= self
._id
_instrument
_name
_dict
.get (id)
415 return instrument_name
417 ly
.stderr_write (_ ("Unable to find instrument for ID=%s\n") % id)
420 class Part_group (Music_xml_node
):
422 class Score_part (Music_xml_node
):
425 class Measure (Music_xml_node
):
427 Music_xml_node
.__init
__ (self
)
429 def is_implicit (self
):
430 return hasattr (self
, 'implicit') and self
.implicit
== 'yes'
431 def get_notes (self
):
432 return self
.get_typed_children (get_class (u
'note'))
434 class Syllabic (Music_xml_node
):
435 def continued (self
):
436 text
= self
.get_text()
437 return (text
== "begin") or (text
== "middle")
438 class Text (Music_xml_node
):
441 class Lyric (Music_xml_node
):
442 def get_number (self
):
443 if hasattr (self
, 'number'):
448 def lyric_to_text (self
):
450 syllabic
= self
.get_maybe_exist_typed_child (Syllabic
)
452 continued
= syllabic
.continued ()
453 text
= self
.get_maybe_exist_typed_child (Text
)
456 text
= text
.get_text()
457 # We need to convert soft hyphens to -, otherwise the ascii codec as well
458 # as lilypond will barf on that character
459 text
= string
.replace( text
, u
'\xad', '-' )
461 if text
== "-" and continued
:
463 elif text
== "_" and continued
:
465 elif continued
and text
:
466 return escape_ly_output_string (text
) + " --"
470 return escape_ly_output_string (text
)
474 class Musicxml_voice
:
478 self
._start
_staff
= None
480 self
._has
_lyrics
= False
482 def add_element (self
, e
):
483 self
._elements
.append (e
)
484 if (isinstance (e
, Note
)
485 and e
.get_maybe_exist_typed_child (Staff
)):
486 name
= e
.get_maybe_exist_typed_child (Staff
).get_text ()
488 if not self
._start
_staff
and not e
.get_maybe_exist_typed_child (Grace
):
489 self
._start
_staff
= name
490 self
._staves
[name
] = True
492 lyrics
= e
.get_typed_children (Lyric
)
493 if not self
._has
_lyrics
:
494 self
.has_lyrics
= len (lyrics
) > 0
498 if (nr
> 0) and not (nr
in self
._lyrics
):
499 self
._lyrics
.append (nr
)
501 def insert (self
, idx
, e
):
502 self
._elements
.insert (idx
, e
)
504 def get_lyrics_numbers (self
):
505 if (len (self
._lyrics
) == 0) and self
._has
_lyrics
:
506 #only happens if none of the <lyric> tags has a number attribute
512 class Part (Music_xml_node
):
514 Music_xml_node
.__init
__ (self
)
516 self
._staff
_attributes
_dict
= {}
518 def get_part_list (self
):
520 while n
and n
.get_name() != 'score-partwise':
523 return n
.get_named_child ('part-list')
525 def interpret (self
):
526 """Set durations and starting points."""
527 """The starting point of the very first note is 0!"""
529 part_list
= self
.get_part_list ()
532 factor
= Rational (1)
534 attributes_object
= None
535 measures
= self
.get_typed_children (Measure
)
536 last_moment
= Rational (-1)
537 last_measure_position
= Rational (-1)
538 measure_position
= Rational (0)
539 measure_start_moment
= now
540 is_first_measure
= True
541 previous_measure
= None
542 # Graces at the end of a measure need to have their position set to the
546 # implicit measures are used for artificial measures, e.g. when
547 # a repeat bar line splits a bar into two halves. In this case,
548 # don't reset the measure position to 0. They are also used for
549 # upbeats (initial value of 0 fits these, too).
550 # Also, don't reset the measure position at the end of the loop,
551 # but rather when starting the next measure (since only then do we
552 # know if the next measure is implicit and continues that measure)
553 if not m
.is_implicit ():
554 # Warn about possibly overfull measures and reset the position
555 if attributes_object
and previous_measure
and previous_measure
.partial
== 0:
556 length
= attributes_object
.get_measure_length ()
557 new_now
= measure_start_moment
+ length
559 problem
= 'incomplete'
562 ## only for verbose operation.
563 if problem
<> 'incomplete' and previous_measure
:
564 previous_measure
.message ('%s measure? Expected: %s, Difference: %s' % (problem
, now
, new_now
- now
))
566 measure_start_moment
= now
567 measure_position
= Rational (0)
569 for n
in m
.get_all_children ():
570 # figured bass has a duration, but applies to the next note
571 # and should not change the current measure position!
572 if isinstance (n
, FiguredBass
):
573 n
._divisions
= factor
.denominator ()
575 n
._measure
_position
= measure_position
578 if isinstance (n
, Hash_text
):
582 if n
.__class
__ == Attributes
:
583 n
.set_attributes_from_previous (attributes_dict
)
585 attributes_dict
= n
._dict
.copy ()
586 attributes_object
= n
588 factor
= Rational (1,
589 int (attributes_dict
.get ('divisions').get_text ()))
592 if (n
.get_maybe_exist_typed_child (Duration
)):
593 mxl_dur
= n
.get_maybe_exist_typed_child (Duration
)
594 dur
= mxl_dur
.get_length () * factor
596 if n
.get_name() == 'backup':
598 # reset all graces before the backup to after-graces:
599 for n
in pending_graces
:
600 n
._when
= n
._prev
_when
601 n
._measure
_position
= n
._prev
_measure
_position
602 n
._after
_grace
= True
604 if n
.get_maybe_exist_typed_child (Grace
):
607 rest
= n
.get_maybe_exist_typed_child (Rest
)
609 and attributes_object
610 and attributes_object
.get_measure_length () == dur
):
612 rest
._is
_whole
_measure
= True
614 if (dur
> Rational (0)
615 and n
.get_maybe_exist_typed_child (Chord
)):
617 measure_position
= last_measure_position
620 n
._measure
_position
= measure_position
622 # For all grace notes, store the previous note, in case need
623 # to turn the grace note into an after-grace later on!
624 if isinstance(n
, Note
) and n
.is_grace ():
625 n
._prev
_when
= last_moment
626 n
._prev
_measure
_position
= last_measure_position
627 # After-graces are placed at the same position as the previous note
628 if isinstance(n
, Note
) and n
.is_after_grace ():
629 # TODO: We should do the same for grace notes at the end of
630 # a measure with no following note!!!
631 n
._when
= last_moment
632 n
._measure
_position
= last_measure_position
633 elif isinstance(n
, Note
) and n
.is_grace ():
634 pending_graces
.append (n
)
635 elif (dur
> Rational (0)):
639 if dur
> Rational (0):
641 last_measure_position
= measure_position
643 measure_position
+= dur
644 elif dur
< Rational (0):
645 # backup element, reset measure position
647 measure_position
+= dur
648 if measure_position
< 0:
649 # backup went beyond the measure start => reset to 0
650 now
-= measure_position
653 last_measure_position
= measure_position
654 if n
._name
== 'note':
655 instrument
= n
.get_maybe_exist_named_child ('instrument')
657 n
.instrument_name
= part_list
.get_instrument (instrument
.id)
659 # reset all graces at the end of the measure to after-graces:
660 for n
in pending_graces
:
661 n
._when
= n
._prev
_when
662 n
._measure
_position
= n
._prev
_measure
_position
663 n
._after
_grace
= True
665 # Incomplete first measures are not padded, but registered as partial
667 is_first_measure
= False
668 # upbeats are marked as implicit measures
669 if attributes_object
and m
.is_implicit ():
670 length
= attributes_object
.get_measure_length ()
671 measure_end
= measure_start_moment
+ length
672 if measure_end
<> now
:
676 # modify attributes so that only those applying to the given staff remain
677 def extract_attributes_for_staff (part
, attr
, staff
):
678 attributes
= copy
.copy (attr
)
679 attributes
._children
= [];
680 attributes
._dict
= attr
._dict
.copy ()
681 attributes
._original
_tag
= attr
682 # copy only the relevant children over for the given staff
683 for c
in attr
._children
:
684 if (not (hasattr (c
, 'number') and (c
.number
!= staff
)) and
685 not (isinstance (c
, Hash_text
))):
686 attributes
._children
.append (c
)
687 if not attributes
._children
:
692 def extract_voices (part
):
694 measures
= part
.get_typed_children (Measure
)
698 elements
.append (Partial (m
.partial
))
699 elements
.extend (m
.get_all_children ())
700 # make sure we know all voices already so that dynamics, clefs, etc.
701 # can be assigned to the correct voices
702 voice_to_staff_dict
= {}
704 voice_id
= n
.get_maybe_exist_named_child (u
'voice')
707 vid
= voice_id
.get_text ()
709 staff_id
= n
.get_maybe_exist_named_child (u
'staff')
712 sid
= staff_id
.get_text ()
715 if vid
and not voices
.has_key (vid
):
716 voices
[vid
] = Musicxml_voice()
717 if vid
and sid
and not n
.get_maybe_exist_typed_child (Grace
):
718 if not voice_to_staff_dict
.has_key (vid
):
719 voice_to_staff_dict
[vid
] = sid
720 # invert the voice_to_staff_dict into a staff_to_voice_dict (since we
721 # need to assign staff-assigned objects like clefs, times, etc. to
722 # all the correct voices. This will never work entirely correct due
723 # to staff-switches, but that's the best we can do!
724 staff_to_voice_dict
= {}
725 for (v
,s
) in voice_to_staff_dict
.items ():
726 if not staff_to_voice_dict
.has_key (s
):
727 staff_to_voice_dict
[s
] = [v
]
729 staff_to_voice_dict
[s
].append (v
)
733 assign_to_next_note
= []
736 voice_id
= n
.get_maybe_exist_typed_child (get_class ('voice'))
738 if not (voice_id
or isinstance (n
, Attributes
) or
739 isinstance (n
, Direction
) or isinstance (n
, Partial
) or
740 isinstance (n
, Barline
) or isinstance (n
, Harmony
) or
741 isinstance (n
, FiguredBass
) ):
744 if isinstance (n
, Attributes
) and not start_attr
:
748 if isinstance (n
, Attributes
):
749 # assign these only to the voices they really belongs to!
750 for (s
, vids
) in staff_to_voice_dict
.items ():
751 staff_attributes
= part
.extract_attributes_for_staff (n
, s
)
754 voices
[v
].add_element (staff_attributes
)
757 if isinstance (n
, Partial
) or isinstance (n
, Barline
):
758 for v
in voices
.keys ():
759 voices
[v
].add_element (n
)
762 if isinstance (n
, Direction
):
763 staff_id
= n
.get_maybe_exist_named_child (u
'staff')
765 staff_id
= staff_id
.get_text ()
767 dir_voices
= staff_to_voice_dict
.get (staff_id
, voices
.keys ())
769 dir_voices
= voices
.keys ()
771 voices
[v
].add_element (n
)
774 if isinstance (n
, Harmony
) or isinstance (n
, FiguredBass
):
775 # store the harmony or figured bass element until we encounter
776 # the next note and assign it only to that one voice.
777 assign_to_next_note
.append (n
)
780 id = voice_id
.get_text ()
781 if hasattr (n
, 'print-object') and getattr (n
, 'print-object') == "no":
785 for i
in assign_to_next_note
:
786 voices
[id].add_element (i
)
787 assign_to_next_note
= []
788 voices
[id].add_element (n
)
790 # Assign all remaining elements from assign_to_next_note to the voice
791 # of the previous note:
792 for i
in assign_to_next_note
:
793 voices
[id].add_element (i
)
794 assign_to_next_note
= []
797 for (s
, vids
) in staff_to_voice_dict
.items ():
798 staff_attributes
= part
.extract_attributes_for_staff (start_attr
, s
)
799 staff_attributes
.read_self ()
800 part
._staff
_attributes
_dict
[s
] = staff_attributes
802 voices
[v
].insert (0, staff_attributes
)
803 voices
[v
]._elements
[0].read_self()
805 part
._voices
= voices
807 def get_voices (self
):
809 def get_staff_attributes (self
):
810 return self
._staff
_attributes
_dict
812 class Notations (Music_xml_node
):
814 ts
= self
.get_named_children ('tied')
815 starts
= [t
for t
in ts
if t
.type == 'start']
821 def get_tuplets (self
):
822 return self
.get_typed_children (Tuplet
)
824 class Time_modification(Music_xml_node
):
825 def get_fraction (self
):
826 b
= self
.get_maybe_exist_named_child ('actual-notes')
827 a
= self
.get_maybe_exist_named_child ('normal-notes')
828 return (int(a
.get_text ()), int (b
.get_text ()))
830 class Accidental (Music_xml_node
):
832 Music_xml_node
.__init
__ (self
)
833 self
.editorial
= False
834 self
.cautionary
= False
836 class Music_xml_spanner (Music_xml_node
):
838 if hasattr (self
, 'type'):
843 if hasattr (self
, 'size'):
844 return string
.atoi (self
.size
)
848 class Wedge (Music_xml_spanner
):
851 class Tuplet (Music_xml_spanner
):
854 class Bracket (Music_xml_spanner
):
857 class Dashes (Music_xml_spanner
):
860 class Slur (Music_xml_spanner
):
864 class Beam (Music_xml_spanner
):
866 return self
.get_text ()
867 def is_primary (self
):
868 return self
.number
== "1"
870 class Wavy_line (Music_xml_spanner
):
873 class Pedal (Music_xml_spanner
):
876 class Glissando (Music_xml_spanner
):
879 class Slide (Music_xml_spanner
):
882 class Octave_shift (Music_xml_spanner
):
883 # default is 8 for the octave-shift!
885 if hasattr (self
, 'size'):
886 return string
.atoi (self
.size
)
890 class Chord (Music_xml_node
):
893 class Dot (Music_xml_node
):
896 # Rests in MusicXML are <note> blocks with a <rest> inside. This class is only
897 # for the inner <rest> element, not the whole rest block.
898 class Rest (Music_xml_node
):
900 Music_xml_node
.__init
__ (self
)
901 self
._is
_whole
_measure
= False
902 def is_whole_measure (self
):
903 return self
._is
_whole
_measure
905 ch
= self
.get_maybe_exist_typed_child (get_class (u
'display-step'))
907 step
= ch
.get_text ().strip ()
911 def get_octave (self
):
912 ch
= self
.get_maybe_exist_typed_child (get_class (u
'display-octave'))
914 step
= ch
.get_text ().strip ()
919 class Type (Music_xml_node
):
921 class Grace (Music_xml_node
):
923 class Staff (Music_xml_node
):
926 class Direction (Music_xml_node
):
928 class DirType (Music_xml_node
):
931 class Bend (Music_xml_node
):
932 def bend_alter (self
):
933 alter
= self
.get_maybe_exist_named_child ('bend-alter')
935 return alter
.get_text()
939 class Words (Music_xml_node
):
942 class Harmony (Music_xml_node
):
945 class ChordPitch (Music_xml_node
):
946 def step_class_name (self
):
948 def alter_class_name (self
):
951 ch
= self
.get_unique_typed_child (get_class (self
.step_class_name ()))
952 return ch
.get_text ().strip ()
953 def get_alteration (self
):
954 ch
= self
.get_maybe_exist_typed_child (get_class (self
.alter_class_name ()))
957 alter
= int (ch
.get_text ().strip ())
960 class Root (ChordPitch
):
963 class Bass (ChordPitch
):
964 def step_class_name (self
):
966 def alter_class_name (self
):
969 class ChordModification (Music_xml_node
):
971 ch
= self
.get_maybe_exist_typed_child (get_class (u
'degree-type'))
972 return {'add': 1, 'alter': 1, 'subtract': -1}.get (ch
.get_text ().strip (), 0)
973 def get_value (self
):
974 ch
= self
.get_maybe_exist_typed_child (get_class (u
'degree-value'))
977 value
= int (ch
.get_text ().strip ())
979 def get_alter (self
):
980 ch
= self
.get_maybe_exist_typed_child (get_class (u
'degree-alter'))
983 value
= int (ch
.get_text ().strip ())
987 class Frame (Music_xml_node
):
988 def get_frets (self
):
989 return self
.get_named_child_value_number ('frame-frets', 4)
990 def get_strings (self
):
991 return self
.get_named_child_value_number ('frame-strings', 6)
992 def get_first_fret (self
):
993 return self
.get_named_child_value_number ('first-fret', 1)
995 class Frame_Note (Music_xml_node
):
996 def get_string (self
):
997 return self
.get_named_child_value_number ('string', 1)
999 return self
.get_named_child_value_number ('fret', 0)
1000 def get_fingering (self
):
1001 return self
.get_named_child_value_number ('fingering', -1)
1002 def get_barre (self
):
1003 n
= self
.get_maybe_exist_named_child ('barre')
1005 return getattr (n
, 'type', '')
1009 class FiguredBass (Music_xml_node
):
1012 class BeatUnit (Music_xml_node
):
1015 class BeatUnitDot (Music_xml_node
):
1018 class PerMinute (Music_xml_node
):
1023 ## need this, not all classes are instantiated
1024 ## for every input file. Only add those classes, that are either directly
1025 ## used by class name or extend Music_xml_node in some way!
1027 '#comment': Hash_comment
,
1029 'accidental': Accidental
,
1030 'attributes': Attributes
,
1032 'bar-style': BarStyle
,
1035 'beat-unit': BeatUnit
,
1036 'beat-unit-dot': BeatUnitDot
,
1038 'bracket' : Bracket
,
1041 'degree' : ChordModification
,
1043 'direction': Direction
,
1044 'direction-type': DirType
,
1045 'duration': Duration
,
1047 'frame-note': Frame_Note
,
1048 'figured-bass': FiguredBass
,
1049 'glissando': Glissando
,
1052 'identification': Identification
,
1055 'notations': Notations
,
1057 'octave-shift': Octave_shift
,
1059 'part-group': Part_group
,
1060 'part-list': Part_list
,
1062 'per-minute': PerMinute
,
1066 'score-part': Score_part
,
1070 'syllabic': Syllabic
,
1072 'time-modification': Time_modification
,
1075 'unpitched': Unpitched
,
1076 'wavy-line': Wavy_line
,
1082 def name2class_name (name
):
1083 name
= name
.replace ('-', '_')
1084 name
= name
.replace ('#', 'hash_')
1085 name
= name
[0].upper() + name
[1:].lower()
1089 def get_class (name
):
1090 classname
= class_dict
.get (name
)
1094 class_name
= name2class_name (name
)
1095 klass
= new
.classobj (class_name
, (Music_xml_node
,) , {})
1096 class_dict
[name
] = klass
1099 def lxml_demarshal_node (node
):
1102 # Ignore comment nodes, which are also returned by the etree parser!
1103 if name
is None or node
.__class
__.__name
__ == "_Comment":
1105 klass
= get_class (name
)
1108 py_node
._original
= node
1109 py_node
._name
= name
1110 py_node
._data
= node
.text
1111 py_node
._children
= [lxml_demarshal_node (cn
) for cn
in node
.getchildren()]
1112 py_node
._children
= filter (lambda x
: x
, py_node
._children
)
1114 for c
in py_node
._children
:
1117 for (k
, v
) in node
.items ():
1118 py_node
.__dict
__[k
] = v
1119 py_node
._attribute
_dict
[k
] = v
1123 def minidom_demarshal_node (node
):
1124 name
= node
.nodeName
1126 klass
= get_class (name
)
1128 py_node
._name
= name
1129 py_node
._children
= [minidom_demarshal_node (cn
) for cn
in node
.childNodes
]
1130 for c
in py_node
._children
:
1134 for (nm
, value
) in node
.attributes
.items ():
1135 py_node
.__dict
__[nm
] = value
1136 py_node
._attribute
_dict
[nm
] = value
1138 py_node
._data
= None
1139 if node
.nodeType
== node
.TEXT_NODE
and node
.data
:
1140 py_node
._data
= node
.data
1142 py_node
._original
= node
1146 if __name__
== '__main__':
1149 tree
= lxml
.etree
.parse ('beethoven.xml')
1150 mxl_tree
= lxml_demarshal_node (tree
.getroot ())
1151 ks
= class_dict
.keys ()
1153 print '\n'.join (ks
)