9 from gettext import gettext as _
20 from rational import Rational
24 sys.stderr.write (str + '\n')
27 def error_message (str):
28 sys.stderr.write (str + '\n')
31 # score information is contained in the <work>, <identification> or <movement-title> tags
32 # extract those into a hash, indexed by proper lilypond header attributes
33 def extract_score_information (tree):
34 header = musicexp.Header ()
35 def set_if_exists (field, value):
37 header.set_field (field, musicxml.escape_ly_output_string (value))
39 work = tree.get_maybe_exist_named_child ('work')
41 set_if_exists ('title', work.get_work_title ())
42 set_if_exists ('worknumber', work.get_work_number ())
43 set_if_exists ('opus', work.get_opus ())
45 movement_title = tree.get_maybe_exist_named_child ('movement-title')
47 set_if_exists ('title', movement_title.get_text ())
49 identifications = tree.get_named_children ('identification')
50 for ids in identifications:
51 set_if_exists ('copyright', ids.get_rights ())
52 set_if_exists ('composer', ids.get_composer ())
53 set_if_exists ('arranger', ids.get_arranger ())
54 set_if_exists ('editor', ids.get_editor ())
55 set_if_exists ('poet', ids.get_poet ())
57 set_if_exists ('tagline', ids.get_encoding_software ())
58 set_if_exists ('encodingsoftware', ids.get_encoding_software ())
59 set_if_exists ('encodingdate', ids.get_encoding_date ())
60 set_if_exists ('encoder', ids.get_encoding_person ())
61 set_if_exists ('encodingdescription', ids.get_encoding_description ())
66 def extract_score_layout (part_list):
67 layout = musicexp.StaffGroup (None)
68 currentgroups_dict = {}
73 def insert_into_layout (object):
74 if len (currentgroups) > 0:
75 group_to_insert = currentgroups_dict.get (currentgroups [-1], layout)
77 group_to_insert = layout
78 group_to_insert.appendStaff (object)
79 return group_to_insert
81 def read_score_part (el):
82 if not isinstance (el, musicxml.Score_part):
84 staff = musicexp.Staff ()
86 partname = el.get_maybe_exist_named_child ('part-name')
87 # Finale gives unnamed parts the name "MusicXML Part" automatically!
88 if partname and partname.get_text() != "MusicXML Part":
89 staff.instrument_name = partname.get_text ()
90 if el.get_maybe_exist_named_child ('part-abbreviation'):
91 staff.short_instrument_name = el.get_maybe_exist_named_child ('part-abbreviation').get_text ()
92 # TODO: Read in the MIDI device / instrument
96 parts_groups = part_list.get_all_children ()
97 # the start/end group tags are not necessarily ordered correctly, so
98 # we can't go through the children sequentially!
100 if len (parts_groups) == 1 and isinstance (parts_group[1], musicxml.Score_part):
101 return read_score_part (parts_group[1])
103 for el in parts_groups:
104 if isinstance (el, musicxml.Score_part):
105 staff = read_score_part (el)
106 insert_into_layout (staff)
107 elif isinstance (el, musicxml.Part_group):
108 if el.type == "start":
109 group = musicexp.StaffGroup ()
110 staff_group = insert_into_layout (group)
111 # If we're inserting a nested staffgroup, we need to use InnerStaffGroup
112 if staff_group != layout:
113 group.stafftype = "InnerStaffGroup"
114 if hasattr (el, 'number'):
117 currentgroups_dict[id] = group
118 currentgroups.append (id)
119 if el.get_maybe_exist_named_child ('group-name'):
120 group.instrument_name = el.get_maybe_exist_named_child ('group-name').get_text ()
121 if el.get_maybe_exist_named_child ('group-abbreviation'):
122 group.short_instrument_name = el.get_maybe_exist_named_child ('group-abbreviation').get_text ()
123 if el.get_maybe_exist_named_child ('group-symbol'):
124 group.symbol = el.get_maybe_exist_named_child ('group-symbol').get_text ()
125 if el.get_maybe_exist_named_child ('group-barline'):
126 group.spanbar = el.get_maybe_exist_named_child ('group-barline').get_text ()
128 elif el.type == "stop":
129 # end the part-group, i.e. simply remove it from the lists
130 if hasattr (el, 'number'):
132 elif len (currentgroups) > 0:
135 del currentgroups_dict[pid]
136 currentgroups.remove (pid)
141 def musicxml_duration_to_lily (mxl_note):
142 d = musicexp.Duration ()
143 # if the note has no Type child, then that method spits out a warning and
144 # returns 0, i.e. a whole note
145 d.duration_log = mxl_note.get_duration_log ()
147 d.dots = len (mxl_note.get_typed_children (musicxml.Dot))
148 # Grace notes by specification have duration 0, so no time modification
149 # factor is possible. It even messes up the output with *0/1
150 if not mxl_note.get_maybe_exist_typed_child (musicxml.Grace):
151 d.factor = mxl_note._duration / d.get_length ()
155 def group_tuplets (music_list, events):
158 """Collect Musics from
159 MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
166 for (ev_chord, tuplet_elt, fraction) in events:
167 while (j < len (music_list)):
168 if music_list[j] == ev_chord:
171 if tuplet_elt.type == 'start':
172 indices.append ((j, None, fraction))
173 elif tuplet_elt.type == 'stop':
174 indices[-1] = (indices[-1][0], j, indices[-1][2])
178 for (i1, i2, frac) in indices:
182 new_list.extend (music_list[last:i1])
183 seq = musicexp.SequentialMusic ()
185 seq.elements = music_list[i1:last]
187 tsm = musicexp.TimeScaledMusic ()
190 tsm.numerator = frac[0]
191 tsm.denominator = frac[1]
193 new_list.append (tsm)
195 new_list.extend (music_list[last:])
199 def musicxml_clef_to_lily (attributes):
200 change = musicexp.ClefChange ()
201 (change.type, change.position, change.octave) = attributes.get_clef_information ()
204 def musicxml_time_to_lily (attributes):
205 (beats, type) = attributes.get_time_signature ()
207 change = musicexp.TimeSignatureChange()
208 change.fraction = (beats, type)
212 def musicxml_key_to_lily (attributes):
213 start_pitch = musicexp.Pitch ()
214 (fifths, mode) = attributes.get_key_signature ()
221 start_pitch.alteration = a
223 error_message ('unknown mode %s' % mode)
225 fifth = musicexp.Pitch()
232 for x in range (fifths):
233 start_pitch = start_pitch.transposed (fifth)
235 start_pitch.octave = 0
237 change = musicexp.KeySignatureChange()
239 change.tonic = start_pitch
242 def musicxml_attributes_to_lily (attrs):
245 'clef': musicxml_clef_to_lily,
246 'time': musicxml_time_to_lily,
247 'key': musicxml_key_to_lily
249 for (k, func) in attr_dispatch.items ():
250 children = attrs.get_named_children (k)
252 elts.append (func (attrs))
256 spanner_event_dict = {
257 'slur' : musicexp.SlurEvent,
258 'beam' : musicexp.BeamEvent,
259 'glissando' : musicexp.GlissandoEvent,
260 'pedal' : musicexp.PedalEvent,
261 'wavy-line' : musicexp.TrillSpanEvent,
262 'octave-shift' : musicexp.OctaveShiftEvent,
263 'wedge' : musicexp.HairpinEvent
265 spanner_type_dict = {
278 def musicxml_spanner_to_lily_event (mxl_event):
281 name = mxl_event.get_name()
282 func = spanner_event_dict.get (name)
286 error_message ('unknown span event %s' % mxl_event)
289 type = mxl_event.get_type ()
290 span_direction = spanner_type_dict.get (type)
291 # really check for None, because some types will be translated to 0, which
292 # would otherwise also lead to the unknown span warning
293 if span_direction != None:
294 ev.span_direction = span_direction
296 error_message ('unknown span type %s for %s' % (type, name))
298 ev.set_span_type (type)
299 ev.line_type = getattr (mxl_event, 'line-type', 'solid')
301 # assign the size, which is used for octave-shift, etc.
302 ev.size = mxl_event.get_size ()
306 def musicxml_direction_to_indicator (direction):
307 return { "above": 1, "upright": 1, "below": -1, "downright": -1 }.get (direction, '')
309 def musicxml_fermata_to_lily_event (mxl_event):
310 ev = musicexp.ArticulationEvent ()
312 if hasattr (mxl_event, 'type'):
313 dir = musicxml_direction_to_indicator (mxl_event.type)
315 ev.force_direction = dir
318 def musicxml_tremolo_to_lily_event (mxl_event):
319 ev = musicexp.TremoloEvent ()
320 ev.bars = mxl_event.get_text ()
323 def musicxml_bend_to_lily_event (mxl_event):
324 ev = musicexp.BendEvent ()
325 ev.alter = mxl_event.bend_alter ()
329 def musicxml_fingering_event (mxl_event):
330 ev = musicexp.ShortArticulationEvent ()
331 ev.type = mxl_event.get_text ()
334 def musicxml_accidental_mark (mxl_event):
335 ev = musicexp.MarkupEvent ()
336 contents = { "sharp": "\\sharp",
337 "natural": "\\natural",
339 "double-sharp": "\\doublesharp",
340 "sharp-sharp": "\\sharp\\sharp",
341 "flat-flat": "\\flat\\flat",
342 "flat-flat": "\\doubleflat",
343 "natural-sharp": "\\natural\\sharp",
344 "natural-flat": "\\natural\\flat",
345 "quarter-flat": "\\semiflat",
346 "quarter-sharp": "\\semisharp",
347 "three-quarters-flat": "\\sesquiflat",
348 "three-quarters-sharp": "\\sesquisharp",
349 }.get (mxl_event.get_text ())
351 ev.contents = contents
356 # translate articulations, ornaments and other notations into ArticulationEvents
358 # -) string (ArticulationEvent with that name)
359 # -) function (function(mxl_event) needs to return a full ArticulationEvent-derived object
360 # -) (class, name) (like string, only that a different class than ArticulationEvent is used)
361 # TODO: Some translations are missing!
362 articulations_dict = {
363 "accent": (musicexp.ShortArticulationEvent, ">"),
364 "accidental-mark": musicxml_accidental_mark,
365 "bend": musicxml_bend_to_lily_event,
366 "breath-mark": (musicexp.NoDirectionArticulationEvent, "breathe"),
367 #"caesura": "caesura",
368 #"delayed-turn": "?",
369 #"detached-legato": "",
371 #"double-tongue": "",
372 "down-bow": "downbow",
374 "fingering": musicxml_fingering_event,
378 "harmonic": "flageolet",
380 "inverted-mordent": "prall",
381 "inverted-turn": "reverseturn",
382 "mordent": "mordent",
386 #"portato": (musicexp.ShortArticulationEvent, "_"), # does not exist in MusicXML
391 #"snap-pizzicato": "",
393 "staccatissimo": (musicexp.ShortArticulationEvent, "|"),
394 "staccato": (musicexp.ShortArticulationEvent, "."),
395 "stopped": (musicexp.ShortArticulationEvent, "+"),
398 "strong-accent": (musicexp.ShortArticulationEvent, "^"),
400 "tenuto": (musicexp.ShortArticulationEvent, "-"),
401 #"thumb-position": "",
404 "tremolo": musicxml_tremolo_to_lily_event,
405 "trill-mark": "trill",
406 #"triple-tongue": "",
411 articulation_spanners = [ "wavy-line" ]
413 def musicxml_articulation_to_lily_event (mxl_event):
414 # wavy-line elements are treated as trill spanners, not as articulation ornaments
415 if mxl_event.get_name () in articulation_spanners:
416 return musicxml_spanner_to_lily_event (mxl_event)
418 tmp_tp = articulations_dict.get (mxl_event.get_name ())
422 if isinstance (tmp_tp, str):
423 ev = musicexp.ArticulationEvent ()
425 elif isinstance (tmp_tp, tuple):
429 ev = tmp_tp (mxl_event)
431 # Some articulations use the type attribute, other the placement...
433 if hasattr (mxl_event, 'type'):
434 dir = musicxml_direction_to_indicator (mxl_event.type)
435 if hasattr (mxl_event, 'placement'):
436 dir = musicxml_direction_to_indicator (mxl_event.placement)
440 def musicxml_dynamics_to_lily_event (dynentry):
441 dynamics_available = ( "p", "pp", "ppp", "pppp", "ppppp", "pppppp",
442 "f", "ff", "fff", "ffff", "fffff", "ffffff",
443 "mp", "mf", "sf", "sfp", "sfpp", "fp",
444 "rf", "rfz", "sfz", "sffz", "fz" )
445 if not dynentry.get_name() in dynamics_available:
447 event = musicexp.DynamicsEvent ()
448 event.type = dynentry.get_name ()
452 direction_spanners = [ 'octave-shift', 'pedal', 'wedge' ]
454 def musicxml_direction_to_lily (n):
455 # TODO: Handle the <staff> element!
457 dirtype_children = []
458 for dt in n.get_typed_children (musicxml.DirType):
459 dirtype_children += dt.get_all_children ()
461 for entry in dirtype_children:
462 if entry.get_name () == "dynamics":
463 for dynentry in entry.get_all_children ():
464 ev = musicxml_dynamics_to_lily_event (dynentry)
468 # octave shifts. pedal marks, hairpins etc. are spanners:
469 if entry.get_name() in direction_spanners:
470 event = musicxml_spanner_to_lily_event (entry)
477 instrument_drumtype_dict = {
478 'Acoustic Snare Drum': 'acousticsnare',
479 'Side Stick': 'sidestick',
480 'Open Triangle': 'opentriangle',
481 'Mute Triangle': 'mutetriangle',
482 'Tambourine': 'tambourine',
483 'Bass Drum': 'bassdrum',
486 def musicxml_note_to_lily_main_event (n):
490 mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
493 pitch = musicxml_pitch_to_lily (mxl_pitch)
494 event = musicexp.NoteEvent()
497 acc = n.get_maybe_exist_named_child ('accidental')
499 # let's not force accs everywhere.
500 event.cautionary = acc.editorial
502 elif n.get_maybe_exist_typed_child (musicxml.Rest):
503 # rests can have display-octave and display-step, which are
504 # treated like an ordinary note pitch
505 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
506 event = musicexp.RestEvent()
507 pitch = musicxml_restdisplay_to_lily (rest)
509 elif n.instrument_name:
510 event = musicexp.NoteEvent ()
511 drum_type = instrument_drumtype_dict.get (n.instrument_name)
513 event.drum_type = drum_type
515 n.message ("drum %s type unknown, please add to instrument_drumtype_dict" % n.instrument_name)
516 event.drum_type = 'acousticsnare'
519 n.message ("cannot find suitable event")
521 event.duration = musicxml_duration_to_lily (n)
527 def __init__ (self, here, dest):
531 class LilyPondVoiceBuilder:
534 self.pending_dynamics = []
535 self.end_moment = Rational (0)
536 self.begin_moment = Rational (0)
537 self.pending_multibar = Rational (0)
539 def _insert_multibar (self):
540 r = musicexp.MultiMeasureRest ()
541 r.duration = musicexp.Duration()
542 r.duration.duration_log = 0
543 r.duration.factor = self.pending_multibar
544 self.elements.append (r)
545 self.begin_moment = self.end_moment
546 self.end_moment = self.begin_moment + self.pending_multibar
547 self.pending_multibar = Rational (0)
549 def add_multibar_rest (self, duration):
550 self.pending_multibar += duration
552 def set_duration (self, duration):
553 self.end_moment = self.begin_moment + duration
554 def current_duration (self):
555 return self.end_moment - self.begin_moment
557 def add_music (self, music, duration):
558 assert isinstance (music, musicexp.Music)
559 if self.pending_multibar > Rational (0):
560 self._insert_multibar ()
562 self.elements.append (music)
563 self.begin_moment = self.end_moment
564 self.set_duration (duration)
566 # Insert all pending dynamics right after the note/rest:
567 if isinstance (music, musicexp.EventChord) and self.pending_dynamics:
568 for d in self.pending_dynamics:
570 self.pending_dynamics = []
572 # Insert some music command that does not affect the position in the measure
573 def add_command (self, command):
574 assert isinstance (command, musicexp.Music)
575 if self.pending_multibar > Rational (0):
576 self._insert_multibar ()
577 self.elements.append (command)
579 def add_dynamics (self, dynamic):
580 # store the dynamic item(s) until we encounter the next note/rest:
581 self.pending_dynamics.append (dynamic)
583 def add_bar_check (self, number):
584 b = musicexp.BarCheck ()
585 b.bar_number = number
586 self.add_music (b, Rational (0))
588 def jumpto (self, moment):
589 current_end = self.end_moment + self.pending_multibar
590 diff = moment - current_end
592 if diff < Rational (0):
593 error_message ('Negative skip %s' % diff)
596 if diff > Rational (0):
597 skip = musicexp.SkipEvent()
598 skip.duration.duration_log = 0
599 skip.duration.factor = diff
601 evc = musicexp.EventChord ()
602 evc.elements.append (skip)
603 self.add_music (evc, diff)
605 def last_event_chord (self, starting_at):
609 # if the position matches, find the last EventChord, do not cross a bar line!
610 at = len( self.elements ) - 1
612 not isinstance (self.elements[at], musicexp.EventChord) and
613 not isinstance (self.elements[at], musicexp.BarCheck)):
618 and isinstance (self.elements[at], musicexp.EventChord)
619 and self.begin_moment == starting_at):
620 value = self.elements[at]
622 self.jumpto (starting_at)
626 def correct_negative_skip (self, goto):
627 self.end_moment = goto
628 self.begin_moment = goto
629 evc = musicexp.EventChord ()
630 self.elements.append (evc)
632 def musicxml_voice_to_lily_voice (voice):
637 # TODO: Make sure that the keys in the dict don't get reordered, since
638 # we need the correct ordering of the lyrics stanzas! By default,
639 # a dict will reorder its keys
640 for k in voice.get_lyrics_numbers ():
643 voice_builder = LilyPondVoiceBuilder()
645 for n in voice._elements:
646 if n.get_name () == 'forward':
649 if isinstance (n, musicxml.Direction):
650 for a in musicxml_direction_to_lily (n):
651 if a.wait_for_note ():
652 voice_builder.add_dynamics (a)
654 voice_builder.add_command (a)
657 if not n.get_maybe_exist_named_child ('chord'):
659 voice_builder.jumpto (n._when)
660 except NegativeSkip, neg:
661 voice_builder.correct_negative_skip (n._when)
662 n.message ("Negative skip? from %s to %s, diff %s" % (neg.here, neg.dest, neg.dest - neg.here))
664 if isinstance (n, musicxml.Attributes):
665 if n.is_first () and n._measure_position == Rational (0):
667 number = int (n.get_parent ().number)
671 voice_builder.add_bar_check (number)
672 for a in musicxml_attributes_to_lily (n):
673 voice_builder.add_music (a, Rational (0))
676 if not n.__class__.__name__ == 'Note':
677 error_message ('not a Note or Attributes? %s' % n)
680 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
682 and rest.is_whole_measure ()):
684 voice_builder.add_multibar_rest (n._duration)
687 if n.is_first () and n._measure_position == Rational (0):
689 num = int (n.get_parent ().number)
692 voice_builder.add_bar_check (num)
694 main_event = musicxml_note_to_lily_main_event (n)
696 if hasattr (main_event, 'drum_type') and main_event.drum_type:
697 modes_found['drummode'] = True
700 ev_chord = voice_builder.last_event_chord (n._when)
702 ev_chord = musicexp.EventChord()
703 voice_builder.add_music (ev_chord, n._duration)
705 grace = n.get_maybe_exist_typed_child (musicxml.Grace)
708 if n.get_maybe_exist_typed_child (musicxml.Chord) and ev_chord.grace_elements:
709 grace_chord = ev_chord.grace_elements.get_last_event_chord ()
711 grace_chord = musicexp.EventChord ()
712 ev_chord.append_grace (grace_chord)
713 if hasattr (grace, 'slash'):
714 # TODO: use grace_type = "appoggiatura" for slurred grace notes
715 if grace.slash == "yes":
716 ev_chord.grace_type = "acciaccatura"
717 elif grace.slash == "no":
718 ev_chord.grace_type = "grace"
719 # now that we have inserted the chord into the grace music, insert
720 # everything into that chord instead of the ev_chord
721 ev_chord = grace_chord
722 ev_chord.append (main_event)
724 ev_chord.append (main_event)
725 # When a note/chord has grace notes (duration==0), the duration of the
726 # event chord is not yet known, but the event chord was already added
727 # with duration 0. The following correct this when we hit the real note!
728 if voice_builder.current_duration () == 0 and n._duration > 0:
729 voice_builder.set_duration (n._duration)
731 notations = n.get_maybe_exist_typed_child (musicxml.Notations)
735 # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
736 # +tied | +slur | +tuplet | glissando | slide |
737 # ornaments | technical | articulations | dynamics |
738 # +fermata | arpeggiate | non-arpeggiate |
739 # accidental-mark | other-notation
741 if notations.get_tuplet():
742 tuplet_event = notations.get_tuplet()
743 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
746 frac = mod.get_fraction ()
748 tuplet_events.append ((ev_chord, tuplet_event, frac))
750 slurs = [s for s in notations.get_named_children ('slur')
751 if s.get_type () in ('start','stop')]
754 error_message ('more than 1 slur?')
756 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
757 ev_chord.append (lily_ev)
759 mxl_tie = notations.get_tie ()
760 if mxl_tie and mxl_tie.type == 'start':
761 ev_chord.append (musicexp.TieEvent ())
763 fermatas = notations.get_named_children ('fermata')
765 ev = musicxml_fermata_to_lily_event (a)
769 arpeggiate = notations.get_named_children ('arpeggiate')
771 ev_chord.append (musicexp.ArpeggioEvent ())
773 glissandos = notations.get_named_children ('glissando')
775 ev = musicxml_spanner_to_lily_event (a)
779 # Articulations can contain the following child elements:
780 # accent | strong-accent | staccato | tenuto |
781 # detached-legato | staccatissimo | spiccato |
782 # scoop | plop | doit | falloff | breath-mark |
783 # caesura | stress | unstress
784 # Technical can contain the following child elements:
785 # up-bow | down-bow | harmonic | open-string |
786 # thumb-position | fingering | pluck | double-tongue |
787 # triple-tongue | stopped | snap-pizzicato | fret |
788 # string | hammer-on | pull-off | bend | tap | heel |
789 # toe | fingernails | other-technical
790 # Ornaments can contain the following child elements:
791 # trill-mark | turn | delayed-turn | inverted-turn |
792 # shake | wavy-line | mordent | inverted-mordent |
793 # schleifer | tremolo | other-ornament, accidental-mark
794 ornaments = notations.get_named_children ('ornaments')
796 for ch in a.get_named_children ('tremolo'):
797 ev = musicxml_tremolo_to_lily_event (ch)
801 ornaments += notations.get_named_children ('articulations')
802 ornaments += notations.get_named_children ('technical')
805 for ch in a.get_all_children ():
806 ev = musicxml_articulation_to_lily_event (ch)
810 dynamics = notations.get_named_children ('dynamics')
812 for ch in a.get_all_children ():
813 ev = musicxml_dynamics_to_lily_event (ch)
819 note_lyrics_processed = []
820 note_lyrics_elements = n.get_typed_children (musicxml.Lyric)
821 for l in note_lyrics_elements:
822 if l.get_number () < 0:
823 for k in lyrics.keys ():
824 lyrics[k].append (l.lyric_to_text ())
825 note_lyrics_processed.append (k)
827 lyrics[l.number].append(l.lyric_to_text ())
828 note_lyrics_processed.append (l.number)
829 for lnr in lyrics.keys ():
830 if not lnr in note_lyrics_processed:
831 lyrics[lnr].append ("\skip4")
834 mxl_beams = [b for b in n.get_named_children ('beam')
835 if (b.get_type () in ('begin', 'end')
836 and b.is_primary ())]
838 beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
840 ev_chord.append (beam_ev)
843 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
846 frac = mod.get_fraction ()
848 tuplet_events.append ((ev_chord, tuplet_event, frac))
850 ## force trailing mm rests to be written out.
851 voice_builder.add_music (musicexp.EventChord (), Rational (0))
853 ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
855 seq_music = musicexp.SequentialMusic ()
857 if 'drummode' in modes_found.keys ():
858 ## \key <pitch> barfs in drummode.
859 ly_voice = [e for e in ly_voice
860 if not isinstance(e, musicexp.KeySignatureChange)]
862 seq_music.elements = ly_voice
864 for k in lyrics.keys ():
865 lyrics_dict[k] = musicexp.Lyrics ()
866 lyrics_dict[k].lyrics_syllables = lyrics[k]
869 if len (modes_found) > 1:
870 error_message ('Too many modes found %s' % modes_found.keys ())
872 return_value = seq_music
873 for mode in modes_found.keys ():
874 v = musicexp.ModeChangingMusicWrapper()
875 v.element = return_value
879 return (return_value, lyrics_dict)
882 def musicxml_id_to_lily (id):
883 digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five',
884 'Six', 'Seven', 'Eight', 'Nine', 'Ten']
887 d = digits.index (digit)
888 id = re.sub ('%d' % d, digit, id)
890 id = re.sub ('[^a-zA-Z]', 'X', id)
894 def musicxml_pitch_to_lily (mxl_pitch):
896 p.alteration = mxl_pitch.get_alteration ()
897 p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
898 p.octave = mxl_pitch.get_octave () - 4
901 def musicxml_restdisplay_to_lily (mxl_rest):
903 step = mxl_rest.get_step ()
906 p.step = (ord (step) - ord ('A') + 7 - 2) % 7
907 octave = mxl_rest.get_octave ()
909 p.octave = octave - 4
912 def voices_in_part (part):
913 """Return a Name -> Voice dictionary for PART"""
915 part.extract_voices ()
916 voice_dict = part.get_voices ()
920 def voices_in_part_in_parts (parts):
921 """return a Part -> Name -> Voice dictionary"""
922 return dict([(p, voices_in_part (p)) for p in parts])
925 def get_all_voices (parts):
926 all_voices = voices_in_part_in_parts (parts)
929 for p, name_voice in all_voices.items ():
932 for n, v in name_voice.items ():
933 progress ("Converting to LilyPond expressions...")
934 # musicxml_voice_to_lily_voice returns (lily_voice, {nr->lyrics, nr->lyrics})
935 part_ly_voices[n] = (musicxml_voice_to_lily_voice (v), v)
937 all_ly_voices[p] = part_ly_voices
942 def option_parser ():
943 p = ly.get_option_parser(usage=_ ("musicxml2ly FILE.xml"),
944 version=('''%prog (LilyPond) @TOPLEVEL_VERSION@\n\n'''
946 _ ("""This program is free software. It is covered by the GNU General Public
947 License and you are welcome to change it and/or distribute copies of it
948 under certain conditions. Invoke as `%s --warranty' for more
949 information.""") % 'lilypond'
951 Copyright (c) 2005--2007 by
952 Han-Wen Nienhuys <hanwen@xs4all.nl> and
953 Jan Nieuwenhuizen <janneke@gnu.org>
955 description=_ ("Convert %s to LilyPond input.") % 'MusicXML' + "\n")
956 p.add_option ('-v', '--verbose',
959 help=_ ("be verbose"))
961 p.add_option ('', '--lxml',
965 help=_ ("Use lxml.etree; uses less memory and cpu time."))
967 p.add_option ('-o', '--output',
973 help=_ ("set output filename to FILE"))
974 p.add_option_group ('bugs',
975 description=(_ ("Report bugs via")
976 + ''' http://post.gmane.org/post.php'''
977 '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
980 def music_xml_voice_name_to_lily_name (part, name):
981 str = "Part%sVoice%s" % (part.id, name)
982 return musicxml_id_to_lily (str)
984 def music_xml_lyrics_name_to_lily_name (part, name, lyricsnr):
985 str = "Part%sVoice%sLyrics%s" % (part.id, name, lyricsnr)
986 return musicxml_id_to_lily (str)
988 def print_voice_definitions (printer, part_list, voices):
990 for (part, nv_dict) in voices.items():
991 part_dict[part.id] = (part, nv_dict)
993 for part in part_list:
994 (p, nv_dict) = part_dict.get (part.id, (None, {}))
995 for (name, ((voice, lyrics), mxlvoice)) in nv_dict.items ():
996 k = music_xml_voice_name_to_lily_name (p, name)
997 printer.dump ('%s = ' % k)
998 voice.print_ly (printer)
1001 for l in lyrics.keys ():
1002 lname = music_xml_lyrics_name_to_lily_name (p, name, l)
1003 printer.dump ('%s = ' %lname )
1004 lyrics[l].print_ly (printer)
1009 return dict ([(elt,1) for elt in l]).keys ()
1011 # format the information about the staff in the form
1014 # [voiceid1, [lyricsid11, lyricsid12,...] ...],
1015 # [voiceid2, [lyricsid21, lyricsid22,...] ...],
1019 # raw_voices is of the form [(voicename, lyrics)*]
1020 def format_staff_info (part, staff_id, raw_voices):
1022 for (v, lyrics) in raw_voices:
1023 voice_name = music_xml_voice_name_to_lily_name (part, v)
1024 voice_lyrics = [music_xml_lyrics_name_to_lily_name (part, v, l)
1025 for l in lyrics.keys ()]
1026 voices.append ([voice_name, voice_lyrics])
1027 return [staff_id, voices]
1029 def update_score_setup (score_structure, part_list, voices):
1030 part_dict = dict ([(p.id, p) for p in voices.keys ()])
1031 final_part_dict = {}
1033 for part_definition in part_list:
1034 part_name = part_definition.id
1035 part = part_dict.get (part_name)
1037 error_message ('unknown part in part-list: %s' % part_name)
1040 nv_dict = voices.get (part)
1041 staves = reduce (lambda x,y: x+ y,
1042 [mxlvoice._staves.keys ()
1043 for (v, mxlvoice) in nv_dict.values ()],
1046 if len (staves) > 1:
1048 staves = uniq_list (staves)
1051 thisstaff_raw_voices = [(voice_name, lyrics)
1052 for (voice_name, ((music, lyrics), mxlvoice)) in nv_dict.items ()
1053 if mxlvoice._start_staff == s]
1054 staves_info.append (format_staff_info (part, s, thisstaff_raw_voices))
1056 thisstaff_raw_voices = [(voice_name, lyrics)
1057 for (voice_name, ((music, lyrics), mxlvoice)) in nv_dict.items ()]
1058 staves_info.append (format_staff_info (part, None, thisstaff_raw_voices))
1059 score_structure.setPartInformation (part_name, staves_info)
1061 def print_ly_preamble (printer, filename):
1062 printer.dump_version ()
1063 printer.print_verbatim ('%% automatically converted from %s\n' % filename)
1065 def read_musicxml (filename, use_lxml):
1069 tree = lxml.etree.parse (filename)
1070 mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
1073 from xml.dom import minidom, Node
1075 doc = minidom.parse(filename)
1076 node = doc.documentElement
1077 return musicxml.minidom_demarshal_node (node)
1082 def convert (filename, options):
1083 progress ("Reading MusicXML from %s ..." % filename)
1085 tree = read_musicxml (filename, options.use_lxml)
1087 score_structure = None
1088 mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
1090 score_structure = extract_score_layout (mxl_pl)
1091 part_list = mxl_pl.get_named_children ("score-part")
1093 # score information is contained in the <work>, <identification> or <movement-title> tags
1094 score_information = extract_score_information (tree)
1095 parts = tree.get_typed_children (musicxml.Part)
1096 voices = get_all_voices (parts)
1097 update_score_setup (score_structure, part_list, voices)
1099 if not options.output_name:
1100 options.output_name = os.path.basename (filename)
1101 options.output_name = os.path.splitext (options.output_name)[0]
1102 elif re.match (".*\.ly", options.output_name):
1103 options.output_name = os.path.splitext (options.output_name)[0]
1106 defs_ly_name = options.output_name + '-defs.ly'
1107 driver_ly_name = options.output_name + '.ly'
1109 printer = musicexp.Output_printer()
1110 progress ("Output to `%s'" % defs_ly_name)
1111 printer.set_file (codecs.open (defs_ly_name, 'wb', encoding='utf-8'))
1113 print_ly_preamble (printer, filename)
1114 score_information.print_ly (printer)
1115 print_voice_definitions (printer, part_list, voices)
1120 progress ("Output to `%s'" % driver_ly_name)
1121 printer = musicexp.Output_printer()
1122 printer.set_file (codecs.open (driver_ly_name, 'wb', encoding='utf-8'))
1123 print_ly_preamble (printer, filename)
1124 printer.dump (r'\include "%s"' % os.path.basename (defs_ly_name))
1125 score_structure.print_ly (printer)
1130 def get_existing_filename_with_extension (filename, ext):
1131 if os.path.exists (filename):
1133 newfilename = filename + ".xml"
1134 if os.path.exists (newfilename):
1136 newfilename = filename + "xml"
1137 if os.path.exists (newfilename):
1142 opt_parser = option_parser()
1144 (options, args) = opt_parser.parse_args ()
1146 opt_parser.print_usage()
1149 # Allow the user to leave out the .xml or xml on the filename
1150 filename = get_existing_filename_with_extension (args[0], "xml")
1151 if filename and os.path.exists (filename):
1152 voices = convert (filename, options)
1154 progress ("Unable to find input file %s" % args[0])
1156 if __name__ == '__main__':