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 if mxl_event.get_name () != "tremolo":
321 ev = musicexp.TremoloEvent ()
322 ev.bars = mxl_event.get_text ()
325 def musicxml_bend_to_lily_event (mxl_event):
326 if mxl_event.get_name () != "bend":
328 ev = musicexp.BendEvent ()
329 ev.alter = mxl_event.bend_alter ()
333 short_articulations_dict = {
337 "staccatissimo": "|",
339 "strong-accent": "^",
340 #"portato": "_", # does not exist in MusicXML
341 #"fingering": "", # fingering is special cased, as get_text() will be the event's name
343 # TODO: Some translations are missing!
344 articulations_dict = {
346 "trill-mark": "trill",
348 #"delayed-turn": "?",
349 "inverted-turn": "reverseturn",
352 "mordent": "mordent",
353 "inverted-mordent": "prall",
357 "down-bow": "downbow",
358 "harmonic": "flageolet",
360 #"thumb-position": "",
362 #"double-tongue": "",
363 #"triple-tongue": "",
364 #"snap-pizzicato": "",
369 #"bend": "bendAfter #%s", # bend is special-cased, as we need to process the bend-alter subelement!
375 #"detached-legato": "",
381 "breath-mark": "breathe",
382 #"caesura": "caesura",
386 articulation_spanners = [ "wavy-line" ]
388 def musicxml_articulation_to_lily_event (mxl_event):
389 # wavy-line elements are treated as trill spanners, not as articulation ornaments
390 if mxl_event.get_name () in articulation_spanners:
391 return musicxml_spanner_to_lily_event (mxl_event)
393 # special case, because of the bend-alter subelement
394 if mxl_event.get_name() == "bend":
395 return musicxml_bend_to_lily_event (mxl_event)
397 # If we can write a shorthand, use them!
398 if mxl_event.get_name() == "fingering":
399 ev = musicexp.ShortArticulationEvent ()
400 tp = mxl_event.get_text()
401 # In all other cases, use the dicts to translate the xml tag name to a proper lilypond command
402 elif short_articulations_dict.get (mxl_event.get_name ()):
403 ev = musicexp.ShortArticulationEvent ()
404 tp = short_articulations_dict.get (mxl_event.get_name ())
406 ev = musicexp.ArticulationEvent ()
407 tp = articulations_dict.get (mxl_event.get_name ())
414 # Some articulations use the type attribute, other the placement...
416 if hasattr (mxl_event, 'type'):
417 dir = musicxml_direction_to_indicator (mxl_event.type)
418 if hasattr (mxl_event, 'placement'):
419 dir = musicxml_direction_to_indicator (mxl_event.placement)
420 # \breathe cannot have any direction modifier (^, _, -)!
421 if dir and tp != "breathe":
422 ev.force_direction = dir
426 def musicxml_dynamics_to_lily_event (dynentry):
427 dynamics_available = ( "p", "pp", "ppp", "pppp", "ppppp", "pppppp",
428 "f", "ff", "fff", "ffff", "fffff", "ffffff",
429 "mp", "mf", "sf", "sfp", "sfpp", "fp",
430 "rf", "rfz", "sfz", "sffz", "fz" )
431 if not dynentry.get_name() in dynamics_available:
433 event = musicexp.DynamicsEvent ()
434 event.type = dynentry.get_name ()
438 direction_spanners = [ 'octave-shift', 'pedal', 'wedge' ]
440 def musicxml_direction_to_lily (n):
441 # TODO: Handle the <staff> element!
443 dirtype_children = []
444 for dt in n.get_typed_children (musicxml.DirType):
445 dirtype_children += dt.get_all_children ()
447 for entry in dirtype_children:
448 if entry.get_name () == "dynamics":
449 for dynentry in entry.get_all_children ():
450 ev = musicxml_dynamics_to_lily_event (dynentry)
454 # octave shifts. pedal marks, hairpins etc. are spanners:
455 if entry.get_name() in direction_spanners:
456 event = musicxml_spanner_to_lily_event (entry)
463 instrument_drumtype_dict = {
464 'Acoustic Snare Drum': 'acousticsnare',
465 'Side Stick': 'sidestick',
466 'Open Triangle': 'opentriangle',
467 'Mute Triangle': 'mutetriangle',
468 'Tambourine': 'tambourine'
471 def musicxml_note_to_lily_main_event (n):
475 mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
478 pitch = musicxml_pitch_to_lily (mxl_pitch)
479 event = musicexp.NoteEvent()
482 acc = n.get_maybe_exist_named_child ('accidental')
484 # let's not force accs everywhere.
485 event.cautionary = acc.editorial
487 elif n.get_maybe_exist_typed_child (musicxml.Rest):
488 # rests can have display-octave and display-step, which are
489 # treated like an ordinary note pitch
490 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
491 event = musicexp.RestEvent()
492 pitch = musicxml_restdisplay_to_lily (rest)
494 elif n.instrument_name:
495 event = musicexp.NoteEvent ()
496 drum_type = instrument_drumtype_dict.get (n.instrument_name)
498 event.drum_type = drum_type
500 n.message ("drum %s type unknow, please add to instrument_drumtype_dict" % n.instrument_name)
501 event.drum_type = 'acousticsnare'
504 n.message ("cannot find suitable event")
506 event.duration = musicxml_duration_to_lily (n)
512 def __init__ (self, here, dest):
516 class LilyPondVoiceBuilder:
519 self.pending_dynamics = []
520 self.end_moment = Rational (0)
521 self.begin_moment = Rational (0)
522 self.pending_multibar = Rational (0)
524 def _insert_multibar (self):
525 r = musicexp.MultiMeasureRest ()
526 r.duration = musicexp.Duration()
527 r.duration.duration_log = 0
528 r.duration.factor = self.pending_multibar
529 self.elements.append (r)
530 self.begin_moment = self.end_moment
531 self.end_moment = self.begin_moment + self.pending_multibar
532 self.pending_multibar = Rational (0)
534 def add_multibar_rest (self, duration):
535 self.pending_multibar += duration
537 def set_duration (self, duration):
538 self.end_moment = self.begin_moment + duration
539 def current_duration (self):
540 return self.end_moment - self.begin_moment
542 def add_music (self, music, duration):
543 assert isinstance (music, musicexp.Music)
544 if self.pending_multibar > Rational (0):
545 self._insert_multibar ()
547 self.elements.append (music)
548 self.begin_moment = self.end_moment
549 self.set_duration (duration)
551 # Insert all pending dynamics right after the note/rest:
552 if duration > Rational (0):
553 for d in self.pending_dynamics:
554 self.elements.append (d)
555 self.pending_dynamics = []
557 # Insert some music command that does not affect the position in the measure
558 def add_command (self, command):
559 assert isinstance (command, musicexp.Music)
560 if self.pending_multibar > Rational (0):
561 self._insert_multibar ()
562 self.elements.append (command)
564 def add_dynamics (self, dynamic):
565 # store the dynamic item(s) until we encounter the next note/rest:
566 self.pending_dynamics.append (dynamic)
568 def add_bar_check (self, number):
569 b = musicexp.BarCheck ()
570 b.bar_number = number
571 self.add_music (b, Rational (0))
573 def jumpto (self, moment):
574 current_end = self.end_moment + self.pending_multibar
575 diff = moment - current_end
577 if diff < Rational (0):
578 error_message ('Negative skip %s' % diff)
581 if diff > Rational (0):
582 skip = musicexp.SkipEvent()
583 skip.duration.duration_log = 0
584 skip.duration.factor = diff
586 evc = musicexp.EventChord ()
587 evc.elements.append (skip)
588 self.add_music (evc, diff)
590 def last_event_chord (self, starting_at):
594 # if the position matches, find the last EventChord, do not cross a bar line!
595 at = len( self.elements ) - 1
597 not isinstance (self.elements[at], musicexp.EventChord) and
598 not isinstance (self.elements[at], musicexp.BarCheck)):
603 and isinstance (self.elements[at], musicexp.EventChord)
604 and self.begin_moment == starting_at):
605 value = self.elements[at]
607 self.jumpto (starting_at)
611 def correct_negative_skip (self, goto):
612 self.end_moment = goto
613 self.begin_moment = goto
614 evc = musicexp.EventChord ()
615 self.elements.append (evc)
617 def musicxml_voice_to_lily_voice (voice):
622 for k in voice.get_lyrics_numbers ():
625 voice_builder = LilyPondVoiceBuilder()
627 for n in voice._elements:
628 if n.get_name () == 'forward':
631 if isinstance (n, musicxml.Direction):
632 for a in musicxml_direction_to_lily (n):
633 if a.wait_for_note ():
634 voice_builder.add_dynamics (a)
636 voice_builder.add_command (a)
639 if not n.get_maybe_exist_named_child ('chord'):
641 voice_builder.jumpto (n._when)
642 except NegativeSkip, neg:
643 voice_builder.correct_negative_skip (n._when)
644 n.message ("Negative skip? from %s to %s, diff %s" % (neg.here, neg.dest, neg.dest - neg.here))
646 if isinstance (n, musicxml.Attributes):
647 if n.is_first () and n._measure_position == Rational (0):
649 number = int (n.get_parent ().number)
653 voice_builder.add_bar_check (number)
654 for a in musicxml_attributes_to_lily (n):
655 voice_builder.add_music (a, Rational (0))
658 if not n.__class__.__name__ == 'Note':
659 error_message ('not a Note or Attributes? %s' % n)
662 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
664 and rest.is_whole_measure ()):
666 voice_builder.add_multibar_rest (n._duration)
669 if n.is_first () and n._measure_position == Rational (0):
671 num = int (n.get_parent ().number)
674 voice_builder.add_bar_check (num)
676 main_event = musicxml_note_to_lily_main_event (n)
678 if hasattr (main_event, 'drum_type') and main_event.drum_type:
679 modes_found['drummode'] = True
682 ev_chord = voice_builder.last_event_chord (n._when)
684 ev_chord = musicexp.EventChord()
685 voice_builder.add_music (ev_chord, n._duration)
687 grace = n.get_maybe_exist_typed_child (musicxml.Grace)
690 if n.get_maybe_exist_typed_child (musicxml.Chord) and ev_chord.grace_elements:
691 grace_chord = ev_chord.grace_elements.get_last_event_chord ()
693 grace_chord = musicexp.EventChord ()
694 ev_chord.append_grace (grace_chord)
695 if hasattr (grace, 'slash'):
696 # TODO: use grace_type = "appoggiatura" for slurred grace notes
697 if grace.slash == "yes":
698 ev_chord.grace_type = "acciaccatura"
699 elif grace.slash == "no":
700 ev_chord.grace_type = "grace"
701 # now that we have inserted the chord into the grace music, insert
702 # everything into that chord instead of the ev_chord
703 ev_chord = grace_chord
704 ev_chord.append (main_event)
706 ev_chord.append (main_event)
707 # When a note/chord has grace notes (duration==0), the duration of the
708 # event chord is not yet known, but the event chord was already added
709 # with duration 0. The following correct this when we hit the real note!
710 if voice_builder.current_duration () == 0 and n._duration > 0:
711 voice_builder.set_duration (n._duration)
713 notations = n.get_maybe_exist_typed_child (musicxml.Notations)
717 # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
718 # +tied | +slur | +tuplet | glissando | slide |
719 # ornaments | technical | articulations | dynamics |
720 # +fermata | arpeggiate | non-arpeggiate |
721 # accidental-mark | other-notation
723 if notations.get_tuplet():
724 tuplet_event = notations.get_tuplet()
725 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
728 frac = mod.get_fraction ()
730 tuplet_events.append ((ev_chord, tuplet_event, frac))
732 slurs = [s for s in notations.get_named_children ('slur')
733 if s.get_type () in ('start','stop')]
736 error_message ('more than 1 slur?')
738 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
739 ev_chord.append (lily_ev)
741 mxl_tie = notations.get_tie ()
742 if mxl_tie and mxl_tie.type == 'start':
743 ev_chord.append (musicexp.TieEvent ())
745 fermatas = notations.get_named_children ('fermata')
747 ev = musicxml_fermata_to_lily_event (a)
751 arpeggiate = notations.get_named_children ('arpeggiate')
753 ev_chord.append (musicexp.ArpeggioEvent ())
755 glissandos = notations.get_named_children ('glissando')
757 ev = musicxml_spanner_to_lily_event (a)
761 # Articulations can contain the following child elements:
762 # accent | strong-accent | staccato | tenuto |
763 # detached-legato | staccatissimo | spiccato |
764 # scoop | plop | doit | falloff | breath-mark |
765 # caesura | stress | unstress
766 # Technical can contain the following child elements:
767 # up-bow | down-bow | harmonic | open-string |
768 # thumb-position | fingering | pluck | double-tongue |
769 # triple-tongue | stopped | snap-pizzicato | fret |
770 # string | hammer-on | pull-off | bend | tap | heel |
771 # toe | fingernails | other-technical
772 # Ornaments can contain the following child elements:
773 # trill-mark | turn | delayed-turn | inverted-turn |
774 # shake | wavy-line | mordent | inverted-mordent |
775 # schleifer | tremolo | other-ornament, accidental-mark
776 ornaments = notations.get_named_children ('ornaments')
778 for ch in a.get_named_children ('tremolo'):
779 ev = musicxml_tremolo_to_lily_event (ch)
783 ornaments += notations.get_named_children ('articulations')
784 ornaments += notations.get_named_children ('technical')
787 for ch in a.get_all_children ():
788 ev = musicxml_articulation_to_lily_event (ch)
792 dynamics = notations.get_named_children ('dynamics')
794 for ch in a.get_all_children ():
795 ev = musicxml_dynamics_to_lily_event (ch)
801 note_lyrics_processed = []
802 note_lyrics_elements = n.get_typed_children (musicxml.Lyric)
803 for l in note_lyrics_elements:
804 if l.get_number () < 0:
805 for k in lyrics.keys ():
806 lyrics[k].append (l.lyric_to_text ())
807 note_lyrics_processed.append (k)
809 lyrics[l.number].append(l.lyric_to_text ())
810 note_lyrics_processed.append (l.number)
811 for lnr in lyrics.keys ():
812 if not lnr in note_lyrics_processed:
813 lyrics[lnr].append ("\skip4")
816 mxl_beams = [b for b in n.get_named_children ('beam')
817 if (b.get_type () in ('begin', 'end')
818 and b.is_primary ())]
820 beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
822 ev_chord.append (beam_ev)
825 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
828 frac = mod.get_fraction ()
830 tuplet_events.append ((ev_chord, tuplet_event, frac))
832 ## force trailing mm rests to be written out.
833 voice_builder.add_music (musicexp.EventChord (), Rational (0))
835 ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
837 seq_music = musicexp.SequentialMusic ()
839 if 'drummode' in modes_found.keys ():
840 ## \key <pitch> barfs in drummode.
841 ly_voice = [e for e in ly_voice
842 if not isinstance(e, musicexp.KeySignatureChange)]
844 seq_music.elements = ly_voice
846 for k in lyrics.keys ():
847 lyrics_dict[k] = musicexp.Lyrics ()
848 lyrics_dict[k].lyrics_syllables = lyrics[k]
851 if len (modes_found) > 1:
852 error_message ('Too many modes found %s' % modes_found.keys ())
854 return_value = seq_music
855 for mode in modes_found.keys ():
856 v = musicexp.ModeChangingMusicWrapper()
857 v.element = return_value
861 return (return_value, lyrics_dict)
864 def musicxml_id_to_lily (id):
865 digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five',
866 'Six', 'Seven', 'Eight', 'Nine', 'Ten']
869 d = digits.index (digit)
870 id = re.sub ('%d' % d, digit, id)
872 id = re.sub ('[^a-zA-Z]', 'X', id)
876 def musicxml_pitch_to_lily (mxl_pitch):
878 p.alteration = mxl_pitch.get_alteration ()
879 p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
880 p.octave = mxl_pitch.get_octave () - 4
883 def musicxml_restdisplay_to_lily (mxl_rest):
885 step = mxl_rest.get_step ()
888 p.step = (ord (step) - ord ('A') + 7 - 2) % 7
889 octave = mxl_rest.get_octave ()
891 p.octave = octave - 4
894 def voices_in_part (part):
895 """Return a Name -> Voice dictionary for PART"""
897 part.extract_voices ()
898 voice_dict = part.get_voices ()
902 def voices_in_part_in_parts (parts):
903 """return a Part -> Name -> Voice dictionary"""
904 return dict([(p, voices_in_part (p)) for p in parts])
907 def get_all_voices (parts):
908 all_voices = voices_in_part_in_parts (parts)
911 for p, name_voice in all_voices.items ():
914 for n, v in name_voice.items ():
915 progress ("Converting to LilyPond expressions...")
916 # musicxml_voice_to_lily_voice returns (lily_voice, {nr->lyrics, nr->lyrics})
917 part_ly_voices[n] = (musicxml_voice_to_lily_voice (v), v)
919 all_ly_voices[p] = part_ly_voices
924 def option_parser ():
925 p = ly.get_option_parser(usage=_ ("musicxml2ly FILE.xml"),
926 version=('''%prog (LilyPond) @TOPLEVEL_VERSION@\n\n'''
928 _ ("""This program is free software. It is covered by the GNU General Public
929 License and you are welcome to change it and/or distribute copies of it
930 under certain conditions. Invoke as `%s --warranty' for more
931 information.""") % 'lilypond'
933 Copyright (c) 2005--2007 by
934 Han-Wen Nienhuys <hanwen@xs4all.nl> and
935 Jan Nieuwenhuizen <janneke@gnu.org>
937 description=_ ("Convert %s to LilyPond input.") % 'MusicXML' + "\n")
938 p.add_option ('-v', '--verbose',
941 help=_ ("be verbose"))
943 p.add_option ('', '--lxml',
947 help=_ ("Use lxml.etree; uses less memory and cpu time."))
949 p.add_option ('-o', '--output',
955 help=_ ("set output filename to FILE"))
956 p.add_option_group ('bugs',
957 description=(_ ("Report bugs via")
958 + ''' http://post.gmane.org/post.php'''
959 '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
962 def music_xml_voice_name_to_lily_name (part, name):
963 str = "Part%sVoice%s" % (part.id, name)
964 return musicxml_id_to_lily (str)
966 def music_xml_lyrics_name_to_lily_name (part, name, lyricsnr):
967 str = "Part%sVoice%sLyrics%s" % (part.id, name, lyricsnr)
968 return musicxml_id_to_lily (str)
970 def print_voice_definitions (printer, part_list, voices):
972 for (part, nv_dict) in voices.items():
973 part_dict[part.id] = (part, nv_dict)
975 for part in part_list:
976 (p, nv_dict) = part_dict.get (part.id, (None, {}))
977 for (name, ((voice, lyrics), mxlvoice)) in nv_dict.items ():
978 k = music_xml_voice_name_to_lily_name (p, name)
979 printer.dump ('%s = ' % k)
980 voice.print_ly (printer)
983 for l in lyrics.keys ():
984 lname = music_xml_lyrics_name_to_lily_name (p, name, l)
985 printer.dump ('%s = ' %lname )
986 lyrics[l].print_ly (printer)
991 return dict ([(elt,1) for elt in l]).keys ()
993 # format the information about the staff in the form
996 # [voiceid1, [lyricsid11, lyricsid12,...] ...],
997 # [voiceid2, [lyricsid21, lyricsid22,...] ...],
1001 # raw_voices is of the form [(voicename, lyrics)*]
1002 def format_staff_info (part, staff_id, raw_voices):
1004 for (v, lyrics) in raw_voices:
1005 voice_name = music_xml_voice_name_to_lily_name (part, v)
1006 voice_lyrics = [music_xml_lyrics_name_to_lily_name (part, v, l)
1007 for l in lyrics.keys ()]
1008 voices.append ([voice_name, voice_lyrics])
1009 return [staff_id, voices]
1011 def update_score_setup (score_structure, part_list, voices):
1012 part_dict = dict ([(p.id, p) for p in voices.keys ()])
1013 final_part_dict = {}
1015 for part_definition in part_list:
1016 part_name = part_definition.id
1017 part = part_dict.get (part_name)
1019 error_message ('unknown part in part-list: %s' % part_name)
1022 nv_dict = voices.get (part)
1023 staves = reduce (lambda x,y: x+ y,
1024 [mxlvoice._staves.keys ()
1025 for (v, mxlvoice) in nv_dict.values ()],
1028 if len (staves) > 1:
1030 staves = uniq_list (staves)
1033 thisstaff_raw_voices = [(voice_name, lyrics)
1034 for (voice_name, ((music, lyrics), mxlvoice)) in nv_dict.items ()
1035 if mxlvoice._start_staff == s]
1036 staves_info.append (format_staff_info (part, s, thisstaff_raw_voices))
1038 thisstaff_raw_voices = [(voice_name, lyrics)
1039 for (voice_name, ((music, lyrics), mxlvoice)) in nv_dict.items ()]
1040 staves_info.append (format_staff_info (part, None, thisstaff_raw_voices))
1041 score_structure.setPartInformation (part_name, staves_info)
1043 def print_ly_preamble (printer, filename):
1044 printer.dump_version ()
1045 printer.print_verbatim ('%% automatically converted from %s\n' % filename)
1047 def read_musicxml (filename, use_lxml):
1051 tree = lxml.etree.parse (filename)
1052 mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
1055 from xml.dom import minidom, Node
1057 doc = minidom.parse(filename)
1058 node = doc.documentElement
1059 return musicxml.minidom_demarshal_node (node)
1064 def convert (filename, options):
1065 progress ("Reading MusicXML from %s ..." % filename)
1067 tree = read_musicxml (filename, options.use_lxml)
1069 score_structure = None
1070 mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
1072 score_structure = extract_score_layout (mxl_pl)
1073 part_list = mxl_pl.get_named_children ("score-part")
1075 # score information is contained in the <work>, <identification> or <movement-title> tags
1076 score_information = extract_score_information (tree)
1077 parts = tree.get_typed_children (musicxml.Part)
1078 voices = get_all_voices (parts)
1079 update_score_setup (score_structure, part_list, voices)
1081 if not options.output_name:
1082 options.output_name = os.path.basename (filename)
1083 options.output_name = os.path.splitext (options.output_name)[0]
1084 elif re.match (".*\.ly", options.output_name):
1085 options.output_name = os.path.splitext (options.output_name)[0]
1088 defs_ly_name = options.output_name + '-defs.ly'
1089 driver_ly_name = options.output_name + '.ly'
1091 printer = musicexp.Output_printer()
1092 progress ("Output to `%s'" % defs_ly_name)
1093 printer.set_file (codecs.open (defs_ly_name, 'wb', encoding='utf-8'))
1095 print_ly_preamble (printer, filename)
1096 score_information.print_ly (printer)
1097 print_voice_definitions (printer, part_list, voices)
1102 progress ("Output to `%s'" % driver_ly_name)
1103 printer = musicexp.Output_printer()
1104 printer.set_file (codecs.open (driver_ly_name, 'wb', encoding='utf-8'))
1105 print_ly_preamble (printer, filename)
1106 printer.dump (r'\include "%s"' % os.path.basename (defs_ly_name))
1107 score_structure.print_ly (printer)
1112 def get_existing_filename_with_extension (filename, ext):
1113 if os.path.exists (filename):
1115 newfilename = filename + ".xml"
1116 if os.path.exists (newfilename):
1118 newfilename = filename + "xml"
1119 if os.path.exists (newfilename):
1124 opt_parser = option_parser()
1126 (options, args) = opt_parser.parse_args ()
1128 opt_parser.print_usage()
1131 # Allow the user to leave out the .xml or xml on the filename
1132 filename = get_existing_filename_with_extension (args[0], "xml")
1133 if filename and os.path.exists (filename):
1134 voices = convert (filename, options)
1136 progress ("Unable to find input file %s" % args[0])
1138 if __name__ == '__main__':