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 rational_to_lily_duration (rational_len):
156 d = musicexp.Duration ()
157 d.duration_log = {1: 0, 2: 1, 4:2, 8:3, 16:4, 32:5, 64:6, 128:7, 256:8, 512:9}.get (rational_len.denominator (), -1)
158 d.factor = Rational (rational_len.numerator ())
161 def musicxml_partial_to_lily (partial_len):
163 p = musicexp.Partial ()
164 p.partial = rational_to_lily_duration (partial_len)
169 def group_tuplets (music_list, events):
172 """Collect Musics from
173 MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
180 for (ev_chord, tuplet_elt, fraction) in events:
181 while (j < len (music_list)):
182 if music_list[j] == ev_chord:
185 if tuplet_elt.type == 'start':
186 indices.append ((j, None, fraction))
187 elif tuplet_elt.type == 'stop':
188 indices[-1] = (indices[-1][0], j, indices[-1][2])
192 for (i1, i2, frac) in indices:
196 new_list.extend (music_list[last:i1])
197 seq = musicexp.SequentialMusic ()
199 seq.elements = music_list[i1:last]
201 tsm = musicexp.TimeScaledMusic ()
204 tsm.numerator = frac[0]
205 tsm.denominator = frac[1]
207 new_list.append (tsm)
209 new_list.extend (music_list[last:])
213 def musicxml_clef_to_lily (attributes):
214 change = musicexp.ClefChange ()
215 (change.type, change.position, change.octave) = attributes.get_clef_information ()
218 def musicxml_time_to_lily (attributes):
219 (beats, type) = attributes.get_time_signature ()
221 change = musicexp.TimeSignatureChange()
222 change.fraction = (beats, type)
226 def musicxml_key_to_lily (attributes):
227 start_pitch = musicexp.Pitch ()
228 (fifths, mode) = attributes.get_key_signature ()
235 start_pitch.alteration = a
237 error_message ('unknown mode %s' % mode)
239 fifth = musicexp.Pitch()
246 for x in range (fifths):
247 start_pitch = start_pitch.transposed (fifth)
249 start_pitch.octave = 0
251 change = musicexp.KeySignatureChange()
253 change.tonic = start_pitch
256 def musicxml_attributes_to_lily (attrs):
259 'clef': musicxml_clef_to_lily,
260 'time': musicxml_time_to_lily,
261 'key': musicxml_key_to_lily
263 for (k, func) in attr_dispatch.items ():
264 children = attrs.get_named_children (k)
266 elts.append (func (attrs))
270 spanner_event_dict = {
271 'slur' : musicexp.SlurEvent,
272 'beam' : musicexp.BeamEvent,
273 'glissando' : musicexp.GlissandoEvent,
274 'pedal' : musicexp.PedalEvent,
275 'wavy-line' : musicexp.TrillSpanEvent,
276 'octave-shift' : musicexp.OctaveShiftEvent,
277 'wedge' : musicexp.HairpinEvent
279 spanner_type_dict = {
292 def musicxml_spanner_to_lily_event (mxl_event):
295 name = mxl_event.get_name()
296 func = spanner_event_dict.get (name)
300 error_message ('unknown span event %s' % mxl_event)
303 type = mxl_event.get_type ()
304 span_direction = spanner_type_dict.get (type)
305 # really check for None, because some types will be translated to 0, which
306 # would otherwise also lead to the unknown span warning
307 if span_direction != None:
308 ev.span_direction = span_direction
310 error_message ('unknown span type %s for %s' % (type, name))
312 ev.set_span_type (type)
313 ev.line_type = getattr (mxl_event, 'line-type', 'solid')
315 # assign the size, which is used for octave-shift, etc.
316 ev.size = mxl_event.get_size ()
320 def musicxml_direction_to_indicator (direction):
321 return { "above": 1, "upright": 1, "below": -1, "downright": -1 }.get (direction, '')
323 def musicxml_fermata_to_lily_event (mxl_event):
324 ev = musicexp.ArticulationEvent ()
326 if hasattr (mxl_event, 'type'):
327 dir = musicxml_direction_to_indicator (mxl_event.type)
329 ev.force_direction = dir
332 def musicxml_tremolo_to_lily_event (mxl_event):
333 ev = musicexp.TremoloEvent ()
334 ev.bars = mxl_event.get_text ()
337 def musicxml_bend_to_lily_event (mxl_event):
338 ev = musicexp.BendEvent ()
339 ev.alter = mxl_event.bend_alter ()
343 def musicxml_fingering_event (mxl_event):
344 ev = musicexp.ShortArticulationEvent ()
345 ev.type = mxl_event.get_text ()
348 def musicxml_accidental_mark (mxl_event):
349 ev = musicexp.MarkupEvent ()
350 contents = { "sharp": "\\sharp",
351 "natural": "\\natural",
353 "double-sharp": "\\doublesharp",
354 "sharp-sharp": "\\sharp\\sharp",
355 "flat-flat": "\\flat\\flat",
356 "flat-flat": "\\doubleflat",
357 "natural-sharp": "\\natural\\sharp",
358 "natural-flat": "\\natural\\flat",
359 "quarter-flat": "\\semiflat",
360 "quarter-sharp": "\\semisharp",
361 "three-quarters-flat": "\\sesquiflat",
362 "three-quarters-sharp": "\\sesquisharp",
363 }.get (mxl_event.get_text ())
365 ev.contents = contents
370 # translate articulations, ornaments and other notations into ArticulationEvents
372 # -) string (ArticulationEvent with that name)
373 # -) function (function(mxl_event) needs to return a full ArticulationEvent-derived object
374 # -) (class, name) (like string, only that a different class than ArticulationEvent is used)
375 # TODO: Some translations are missing!
376 articulations_dict = {
377 "accent": (musicexp.ShortArticulationEvent, ">"),
378 "accidental-mark": musicxml_accidental_mark,
379 "bend": musicxml_bend_to_lily_event,
380 "breath-mark": (musicexp.NoDirectionArticulationEvent, "breathe"),
381 #"caesura": "caesura",
382 #"delayed-turn": "?",
383 #"detached-legato": "",
385 #"double-tongue": "",
386 "down-bow": "downbow",
388 "fingering": musicxml_fingering_event,
392 "harmonic": "flageolet",
394 "inverted-mordent": "prall",
395 "inverted-turn": "reverseturn",
396 "mordent": "mordent",
400 #"portato": (musicexp.ShortArticulationEvent, "_"), # does not exist in MusicXML
405 #"snap-pizzicato": "",
407 "staccatissimo": (musicexp.ShortArticulationEvent, "|"),
408 "staccato": (musicexp.ShortArticulationEvent, "."),
409 "stopped": (musicexp.ShortArticulationEvent, "+"),
412 "strong-accent": (musicexp.ShortArticulationEvent, "^"),
414 "tenuto": (musicexp.ShortArticulationEvent, "-"),
415 #"thumb-position": "",
418 "tremolo": musicxml_tremolo_to_lily_event,
419 "trill-mark": "trill",
420 #"triple-tongue": "",
425 articulation_spanners = [ "wavy-line" ]
427 def musicxml_articulation_to_lily_event (mxl_event):
428 # wavy-line elements are treated as trill spanners, not as articulation ornaments
429 if mxl_event.get_name () in articulation_spanners:
430 return musicxml_spanner_to_lily_event (mxl_event)
432 tmp_tp = articulations_dict.get (mxl_event.get_name ())
436 if isinstance (tmp_tp, str):
437 ev = musicexp.ArticulationEvent ()
439 elif isinstance (tmp_tp, tuple):
443 ev = tmp_tp (mxl_event)
445 # Some articulations use the type attribute, other the placement...
447 if hasattr (mxl_event, 'type'):
448 dir = musicxml_direction_to_indicator (mxl_event.type)
449 if hasattr (mxl_event, 'placement'):
450 dir = musicxml_direction_to_indicator (mxl_event.placement)
454 def musicxml_dynamics_to_lily_event (dynentry):
455 dynamics_available = ( "p", "pp", "ppp", "pppp", "ppppp", "pppppp",
456 "f", "ff", "fff", "ffff", "fffff", "ffffff",
457 "mp", "mf", "sf", "sfp", "sfpp", "fp",
458 "rf", "rfz", "sfz", "sffz", "fz" )
459 if not dynentry.get_name() in dynamics_available:
461 event = musicexp.DynamicsEvent ()
462 event.type = dynentry.get_name ()
466 direction_spanners = [ 'octave-shift', 'pedal', 'wedge' ]
468 def musicxml_direction_to_lily (n):
469 # TODO: Handle the <staff> element!
471 dirtype_children = []
472 for dt in n.get_typed_children (musicxml.DirType):
473 dirtype_children += dt.get_all_children ()
475 for entry in dirtype_children:
476 if entry.get_name () == "dynamics":
477 for dynentry in entry.get_all_children ():
478 ev = musicxml_dynamics_to_lily_event (dynentry)
482 # octave shifts. pedal marks, hairpins etc. are spanners:
483 if entry.get_name() in direction_spanners:
484 event = musicxml_spanner_to_lily_event (entry)
491 instrument_drumtype_dict = {
492 'Acoustic Snare Drum': 'acousticsnare',
493 'Side Stick': 'sidestick',
494 'Open Triangle': 'opentriangle',
495 'Mute Triangle': 'mutetriangle',
496 'Tambourine': 'tambourine',
497 'Bass Drum': 'bassdrum',
500 def musicxml_note_to_lily_main_event (n):
504 mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
507 pitch = musicxml_pitch_to_lily (mxl_pitch)
508 event = musicexp.NoteEvent()
511 acc = n.get_maybe_exist_named_child ('accidental')
513 # let's not force accs everywhere.
514 event.cautionary = acc.editorial
516 elif n.get_maybe_exist_typed_child (musicxml.Rest):
517 # rests can have display-octave and display-step, which are
518 # treated like an ordinary note pitch
519 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
520 event = musicexp.RestEvent()
521 pitch = musicxml_restdisplay_to_lily (rest)
523 elif n.instrument_name:
524 event = musicexp.NoteEvent ()
525 drum_type = instrument_drumtype_dict.get (n.instrument_name)
527 event.drum_type = drum_type
529 n.message ("drum %s type unknown, please add to instrument_drumtype_dict" % n.instrument_name)
530 event.drum_type = 'acousticsnare'
533 n.message ("cannot find suitable event")
535 event.duration = musicxml_duration_to_lily (n)
541 def __init__ (self, here, dest):
545 class LilyPondVoiceBuilder:
548 self.pending_dynamics = []
549 self.end_moment = Rational (0)
550 self.begin_moment = Rational (0)
551 self.pending_multibar = Rational (0)
552 self.ignore_skips = False
554 def _insert_multibar (self):
555 r = musicexp.MultiMeasureRest ()
556 r.duration = musicexp.Duration()
557 r.duration.duration_log = 0
558 r.duration.factor = self.pending_multibar
559 self.elements.append (r)
560 self.begin_moment = self.end_moment
561 self.end_moment = self.begin_moment + self.pending_multibar
562 self.pending_multibar = Rational (0)
564 def add_multibar_rest (self, duration):
565 self.pending_multibar += duration
567 def set_duration (self, duration):
568 self.end_moment = self.begin_moment + duration
569 def current_duration (self):
570 return self.end_moment - self.begin_moment
572 def add_music (self, music, duration):
573 assert isinstance (music, musicexp.Music)
574 if self.pending_multibar > Rational (0):
575 self._insert_multibar ()
577 self.elements.append (music)
578 self.begin_moment = self.end_moment
579 self.set_duration (duration)
581 # Insert all pending dynamics right after the note/rest:
582 if isinstance (music, musicexp.EventChord) and self.pending_dynamics:
583 for d in self.pending_dynamics:
585 self.pending_dynamics = []
587 # Insert some music command that does not affect the position in the measure
588 def add_command (self, command):
589 assert isinstance (command, musicexp.Music)
590 if self.pending_multibar > Rational (0):
591 self._insert_multibar ()
592 self.elements.append (command)
593 def add_partial (self, command):
594 self.ignore_skips = True
595 self.add_command (command)
597 def add_dynamics (self, dynamic):
598 # store the dynamic item(s) until we encounter the next note/rest:
599 self.pending_dynamics.append (dynamic)
601 def add_bar_check (self, number):
602 b = musicexp.BarCheck ()
603 b.bar_number = number
604 self.add_music (b, Rational (0))
606 def jumpto (self, moment):
607 current_end = self.end_moment + self.pending_multibar
608 diff = moment - current_end
610 if diff < Rational (0):
611 error_message ('Negative skip %s' % diff)
614 if diff > Rational (0) and not self.ignore_skips:
615 skip = musicexp.SkipEvent()
616 skip.duration.duration_log = 0
617 skip.duration.factor = diff
619 evc = musicexp.EventChord ()
620 evc.elements.append (skip)
621 self.add_music (evc, diff)
623 if diff > Rational (0) and moment == 0:
624 self.ignore_skips = False
626 def last_event_chord (self, starting_at):
630 # if the position matches, find the last EventChord, do not cross a bar line!
631 at = len( self.elements ) - 1
633 not isinstance (self.elements[at], musicexp.EventChord) and
634 not isinstance (self.elements[at], musicexp.BarCheck)):
639 and isinstance (self.elements[at], musicexp.EventChord)
640 and self.begin_moment == starting_at):
641 value = self.elements[at]
643 self.jumpto (starting_at)
647 def correct_negative_skip (self, goto):
648 self.end_moment = goto
649 self.begin_moment = goto
650 evc = musicexp.EventChord ()
651 self.elements.append (evc)
653 def musicxml_voice_to_lily_voice (voice):
658 # TODO: Make sure that the keys in the dict don't get reordered, since
659 # we need the correct ordering of the lyrics stanzas! By default,
660 # a dict will reorder its keys
661 for k in voice.get_lyrics_numbers ():
664 voice_builder = LilyPondVoiceBuilder()
666 for n in voice._elements:
667 if n.get_name () == 'forward':
670 if isinstance (n, musicxml.Partial) and n.partial > 0:
671 a = musicxml_partial_to_lily (n.partial)
673 voice_builder.add_partial (a)
676 if isinstance (n, musicxml.Direction):
677 for a in musicxml_direction_to_lily (n):
678 if a.wait_for_note ():
679 voice_builder.add_dynamics (a)
681 voice_builder.add_command (a)
684 if not n.get_maybe_exist_named_child ('chord'):
686 voice_builder.jumpto (n._when)
687 except NegativeSkip, neg:
688 voice_builder.correct_negative_skip (n._when)
689 n.message ("Negative skip? from %s to %s, diff %s" % (neg.here, neg.dest, neg.dest - neg.here))
691 if isinstance (n, musicxml.Attributes):
692 if n.is_first () and n._measure_position == Rational (0):
694 number = int (n.get_parent ().number)
698 voice_builder.add_bar_check (number)
700 for a in musicxml_attributes_to_lily (n):
701 voice_builder.add_music (a, Rational (0))
704 if not n.__class__.__name__ == 'Note':
705 error_message ('not a Note or Attributes? %s' % n)
708 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
710 and rest.is_whole_measure ()):
712 voice_builder.add_multibar_rest (n._duration)
715 if n.is_first () and n._measure_position == Rational (0):
717 num = int (n.get_parent ().number)
721 voice_builder.add_bar_check (num)
723 main_event = musicxml_note_to_lily_main_event (n)
725 if hasattr (main_event, 'drum_type') and main_event.drum_type:
726 modes_found['drummode'] = True
729 ev_chord = voice_builder.last_event_chord (n._when)
731 ev_chord = musicexp.EventChord()
732 voice_builder.add_music (ev_chord, n._duration)
734 grace = n.get_maybe_exist_typed_child (musicxml.Grace)
737 if n.get_maybe_exist_typed_child (musicxml.Chord) and ev_chord.grace_elements:
738 grace_chord = ev_chord.grace_elements.get_last_event_chord ()
740 grace_chord = musicexp.EventChord ()
741 ev_chord.append_grace (grace_chord)
742 if hasattr (grace, 'slash'):
743 # TODO: use grace_type = "appoggiatura" for slurred grace notes
744 if grace.slash == "yes":
745 ev_chord.grace_type = "acciaccatura"
746 elif grace.slash == "no":
747 ev_chord.grace_type = "grace"
748 # now that we have inserted the chord into the grace music, insert
749 # everything into that chord instead of the ev_chord
750 ev_chord = grace_chord
751 ev_chord.append (main_event)
753 ev_chord.append (main_event)
754 # When a note/chord has grace notes (duration==0), the duration of the
755 # event chord is not yet known, but the event chord was already added
756 # with duration 0. The following correct this when we hit the real note!
757 if voice_builder.current_duration () == 0 and n._duration > 0:
758 voice_builder.set_duration (n._duration)
760 notations = n.get_maybe_exist_typed_child (musicxml.Notations)
764 # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
765 # +tied | +slur | +tuplet | glissando | slide |
766 # ornaments | technical | articulations | dynamics |
767 # +fermata | arpeggiate | non-arpeggiate |
768 # accidental-mark | other-notation
770 if notations.get_tuplet():
771 tuplet_event = notations.get_tuplet()
772 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
775 frac = mod.get_fraction ()
777 tuplet_events.append ((ev_chord, tuplet_event, frac))
779 slurs = [s for s in notations.get_named_children ('slur')
780 if s.get_type () in ('start','stop')]
783 error_message ('more than 1 slur?')
785 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
786 ev_chord.append (lily_ev)
788 mxl_tie = notations.get_tie ()
789 if mxl_tie and mxl_tie.type == 'start':
790 ev_chord.append (musicexp.TieEvent ())
792 fermatas = notations.get_named_children ('fermata')
794 ev = musicxml_fermata_to_lily_event (a)
798 arpeggiate = notations.get_named_children ('arpeggiate')
800 ev_chord.append (musicexp.ArpeggioEvent ())
802 glissandos = notations.get_named_children ('glissando')
804 ev = musicxml_spanner_to_lily_event (a)
808 # Articulations can contain the following child elements:
809 # accent | strong-accent | staccato | tenuto |
810 # detached-legato | staccatissimo | spiccato |
811 # scoop | plop | doit | falloff | breath-mark |
812 # caesura | stress | unstress
813 # Technical can contain the following child elements:
814 # up-bow | down-bow | harmonic | open-string |
815 # thumb-position | fingering | pluck | double-tongue |
816 # triple-tongue | stopped | snap-pizzicato | fret |
817 # string | hammer-on | pull-off | bend | tap | heel |
818 # toe | fingernails | other-technical
819 # Ornaments can contain the following child elements:
820 # trill-mark | turn | delayed-turn | inverted-turn |
821 # shake | wavy-line | mordent | inverted-mordent |
822 # schleifer | tremolo | other-ornament, accidental-mark
823 ornaments = notations.get_named_children ('ornaments')
825 for ch in a.get_named_children ('tremolo'):
826 ev = musicxml_tremolo_to_lily_event (ch)
830 ornaments += notations.get_named_children ('articulations')
831 ornaments += notations.get_named_children ('technical')
834 for ch in a.get_all_children ():
835 ev = musicxml_articulation_to_lily_event (ch)
839 dynamics = notations.get_named_children ('dynamics')
841 for ch in a.get_all_children ():
842 ev = musicxml_dynamics_to_lily_event (ch)
848 note_lyrics_processed = []
849 note_lyrics_elements = n.get_typed_children (musicxml.Lyric)
850 for l in note_lyrics_elements:
851 if l.get_number () < 0:
852 for k in lyrics.keys ():
853 lyrics[k].append (l.lyric_to_text ())
854 note_lyrics_processed.append (k)
856 lyrics[l.number].append(l.lyric_to_text ())
857 note_lyrics_processed.append (l.number)
858 for lnr in lyrics.keys ():
859 if not lnr in note_lyrics_processed:
860 lyrics[lnr].append ("\skip4")
863 mxl_beams = [b for b in n.get_named_children ('beam')
864 if (b.get_type () in ('begin', 'end')
865 and b.is_primary ())]
867 beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
869 ev_chord.append (beam_ev)
872 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
875 frac = mod.get_fraction ()
877 tuplet_events.append ((ev_chord, tuplet_event, frac))
879 ## force trailing mm rests to be written out.
880 voice_builder.add_music (musicexp.EventChord (), Rational (0))
882 ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
884 seq_music = musicexp.SequentialMusic ()
886 if 'drummode' in modes_found.keys ():
887 ## \key <pitch> barfs in drummode.
888 ly_voice = [e for e in ly_voice
889 if not isinstance(e, musicexp.KeySignatureChange)]
891 seq_music.elements = ly_voice
893 for k in lyrics.keys ():
894 lyrics_dict[k] = musicexp.Lyrics ()
895 lyrics_dict[k].lyrics_syllables = lyrics[k]
898 if len (modes_found) > 1:
899 error_message ('Too many modes found %s' % modes_found.keys ())
901 return_value = seq_music
902 for mode in modes_found.keys ():
903 v = musicexp.ModeChangingMusicWrapper()
904 v.element = return_value
908 return (return_value, lyrics_dict)
911 def musicxml_id_to_lily (id):
912 digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five',
913 'Six', 'Seven', 'Eight', 'Nine', 'Ten']
916 d = digits.index (digit)
917 id = re.sub ('%d' % d, digit, id)
919 id = re.sub ('[^a-zA-Z]', 'X', id)
923 def musicxml_pitch_to_lily (mxl_pitch):
925 p.alteration = mxl_pitch.get_alteration ()
926 p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
927 p.octave = mxl_pitch.get_octave () - 4
930 def musicxml_restdisplay_to_lily (mxl_rest):
932 step = mxl_rest.get_step ()
935 p.step = (ord (step) - ord ('A') + 7 - 2) % 7
936 octave = mxl_rest.get_octave ()
938 p.octave = octave - 4
941 def voices_in_part (part):
942 """Return a Name -> Voice dictionary for PART"""
944 part.extract_voices ()
945 voice_dict = part.get_voices ()
949 def voices_in_part_in_parts (parts):
950 """return a Part -> Name -> Voice dictionary"""
951 return dict([(p, voices_in_part (p)) for p in parts])
954 def get_all_voices (parts):
955 all_voices = voices_in_part_in_parts (parts)
958 for p, name_voice in all_voices.items ():
961 for n, v in name_voice.items ():
962 progress ("Converting to LilyPond expressions...")
963 # musicxml_voice_to_lily_voice returns (lily_voice, {nr->lyrics, nr->lyrics})
964 part_ly_voices[n] = (musicxml_voice_to_lily_voice (v), v)
966 all_ly_voices[p] = part_ly_voices
971 def option_parser ():
972 p = ly.get_option_parser(usage=_ ("musicxml2ly FILE.xml"),
973 version=('''%prog (LilyPond) @TOPLEVEL_VERSION@\n\n'''
975 _ ("""This program is free software. It is covered by the GNU General Public
976 License and you are welcome to change it and/or distribute copies of it
977 under certain conditions. Invoke as `%s --warranty' for more
978 information.""") % 'lilypond'
980 Copyright (c) 2005--2007 by
981 Han-Wen Nienhuys <hanwen@xs4all.nl> and
982 Jan Nieuwenhuizen <janneke@gnu.org>
984 description=_ ("Convert %s to LilyPond input.") % 'MusicXML' + "\n")
985 p.add_option ('-v', '--verbose',
988 help=_ ("be verbose"))
990 p.add_option ('', '--lxml',
994 help=_ ("Use lxml.etree; uses less memory and cpu time."))
996 p.add_option ('-o', '--output',
1002 help=_ ("set output filename to FILE"))
1003 p.add_option_group ('bugs',
1004 description=(_ ("Report bugs via")
1005 + ''' http://post.gmane.org/post.php'''
1006 '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
1009 def music_xml_voice_name_to_lily_name (part, name):
1010 str = "Part%sVoice%s" % (part.id, name)
1011 return musicxml_id_to_lily (str)
1013 def music_xml_lyrics_name_to_lily_name (part, name, lyricsnr):
1014 str = "Part%sVoice%sLyrics%s" % (part.id, name, lyricsnr)
1015 return musicxml_id_to_lily (str)
1017 def print_voice_definitions (printer, part_list, voices):
1019 for (part, nv_dict) in voices.items():
1020 part_dict[part.id] = (part, nv_dict)
1022 for part in part_list:
1023 (p, nv_dict) = part_dict.get (part.id, (None, {}))
1024 for (name, ((voice, lyrics), mxlvoice)) in nv_dict.items ():
1025 k = music_xml_voice_name_to_lily_name (p, name)
1026 printer.dump ('%s = ' % k)
1027 voice.print_ly (printer)
1030 for l in lyrics.keys ():
1031 lname = music_xml_lyrics_name_to_lily_name (p, name, l)
1032 printer.dump ('%s = ' %lname )
1033 lyrics[l].print_ly (printer)
1038 return dict ([(elt,1) for elt in l]).keys ()
1040 # format the information about the staff in the form
1043 # [voiceid1, [lyricsid11, lyricsid12,...] ...],
1044 # [voiceid2, [lyricsid21, lyricsid22,...] ...],
1048 # raw_voices is of the form [(voicename, lyrics)*]
1049 def format_staff_info (part, staff_id, raw_voices):
1051 for (v, lyrics) in raw_voices:
1052 voice_name = music_xml_voice_name_to_lily_name (part, v)
1053 voice_lyrics = [music_xml_lyrics_name_to_lily_name (part, v, l)
1054 for l in lyrics.keys ()]
1055 voices.append ([voice_name, voice_lyrics])
1056 return [staff_id, voices]
1058 def update_score_setup (score_structure, part_list, voices):
1059 part_dict = dict ([(p.id, p) for p in voices.keys ()])
1060 final_part_dict = {}
1062 for part_definition in part_list:
1063 part_name = part_definition.id
1064 part = part_dict.get (part_name)
1066 error_message ('unknown part in part-list: %s' % part_name)
1069 nv_dict = voices.get (part)
1070 staves = reduce (lambda x,y: x+ y,
1071 [mxlvoice._staves.keys ()
1072 for (v, mxlvoice) in nv_dict.values ()],
1075 if len (staves) > 1:
1077 staves = uniq_list (staves)
1080 thisstaff_raw_voices = [(voice_name, lyrics)
1081 for (voice_name, ((music, lyrics), mxlvoice)) in nv_dict.items ()
1082 if mxlvoice._start_staff == s]
1083 staves_info.append (format_staff_info (part, s, thisstaff_raw_voices))
1085 thisstaff_raw_voices = [(voice_name, lyrics)
1086 for (voice_name, ((music, lyrics), mxlvoice)) in nv_dict.items ()]
1087 staves_info.append (format_staff_info (part, None, thisstaff_raw_voices))
1088 score_structure.setPartInformation (part_name, staves_info)
1090 def print_ly_preamble (printer, filename):
1091 printer.dump_version ()
1092 printer.print_verbatim ('%% automatically converted from %s\n' % filename)
1094 def read_musicxml (filename, use_lxml):
1098 tree = lxml.etree.parse (filename)
1099 mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
1102 from xml.dom import minidom, Node
1104 doc = minidom.parse(filename)
1105 node = doc.documentElement
1106 return musicxml.minidom_demarshal_node (node)
1111 def convert (filename, options):
1112 progress ("Reading MusicXML from %s ..." % filename)
1114 tree = read_musicxml (filename, options.use_lxml)
1116 score_structure = None
1117 mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
1119 score_structure = extract_score_layout (mxl_pl)
1120 part_list = mxl_pl.get_named_children ("score-part")
1122 # score information is contained in the <work>, <identification> or <movement-title> tags
1123 score_information = extract_score_information (tree)
1124 parts = tree.get_typed_children (musicxml.Part)
1125 voices = get_all_voices (parts)
1126 update_score_setup (score_structure, part_list, voices)
1128 if not options.output_name:
1129 options.output_name = os.path.basename (filename)
1130 options.output_name = os.path.splitext (options.output_name)[0]
1131 elif re.match (".*\.ly", options.output_name):
1132 options.output_name = os.path.splitext (options.output_name)[0]
1135 defs_ly_name = options.output_name + '-defs.ly'
1136 driver_ly_name = options.output_name + '.ly'
1138 printer = musicexp.Output_printer()
1139 progress ("Output to `%s'" % defs_ly_name)
1140 printer.set_file (codecs.open (defs_ly_name, 'wb', encoding='utf-8'))
1142 print_ly_preamble (printer, filename)
1143 score_information.print_ly (printer)
1144 print_voice_definitions (printer, part_list, voices)
1149 progress ("Output to `%s'" % driver_ly_name)
1150 printer = musicexp.Output_printer()
1151 printer.set_file (codecs.open (driver_ly_name, 'wb', encoding='utf-8'))
1152 print_ly_preamble (printer, filename)
1153 printer.dump (r'\include "%s"' % os.path.basename (defs_ly_name))
1154 score_structure.print_ly (printer)
1159 def get_existing_filename_with_extension (filename, ext):
1160 if os.path.exists (filename):
1162 newfilename = filename + ".xml"
1163 if os.path.exists (newfilename):
1165 newfilename = filename + "xml"
1166 if os.path.exists (newfilename):
1171 opt_parser = option_parser()
1173 (options, args) = opt_parser.parse_args ()
1175 opt_parser.print_usage()
1178 # Allow the user to leave out the .xml or xml on the filename
1179 filename = get_existing_filename_with_extension (args[0], "xml")
1180 if filename and os.path.exists (filename):
1181 voices = convert (filename, options)
1183 progress ("Unable to find input file %s" % args[0])
1185 if __name__ == '__main__':