11 from gettext import gettext as _
22 from rational import Rational
24 # Store command-line options in a global variable, so we can access them everythwere
28 ly.stderr_write (str + '\n')
31 def error_message (str):
32 ly.stderr_write (str + '\n')
35 needed_additional_definitions = []
36 additional_definitions = {
37 "snappizzicato": """#(define-markup-command (snappizzicato layout props) ()
38 (interpret-markup layout props
40 (ly:stencil-translate-axis
42 (make-circle-stencil 0.7 0.1 #f)
44 (list 'draw-line 0.1 0 0.1 0 1)
45 '(-0.1 . 0.1) '(0.1 . 1)
56 def round_to_two_digits (val):
57 return round (val * 100) / 100
59 def extract_layout_information (tree):
60 paper = musicexp.Paper ()
61 defaults = tree.get_maybe_exist_named_child ('defaults')
65 scaling = defaults.get_maybe_exist_named_child ('scaling')
67 mm = scaling.get_named_child ('millimeters')
68 mm = string.atof (mm.get_text ())
69 tn = scaling.get_maybe_exist_named_child ('tenths')
70 tn = string.atof (tn.get_text ())
72 paper.global_staff_size = mm * 72.27 / 25.4
73 # We need the scaling (i.e. the size of staff tenths for everything!
77 def from_tenths (txt):
78 return round_to_two_digits (string.atof (txt) * tenths / 10)
79 def set_paper_variable (varname, parent, element_name):
80 el = parent.get_maybe_exist_named_child (element_name)
81 if el: # Convert to cm from tenths
82 setattr (paper, varname, from_tenths (el.get_text ()))
84 pagelayout = defaults.get_maybe_exist_named_child ('page-layout')
86 # TODO: How can one have different margins for even and odd pages???
87 set_paper_variable ("page_height", pagelayout, 'page-height')
88 set_paper_variable ("page_width", pagelayout, 'page-width')
90 pmargins = pagelayout.get_named_children ('page-margins')
92 set_paper_variable ("left_margin", pm, 'left-margin')
93 set_paper_variable ("right_margin", pm, 'right-margin')
94 set_paper_variable ("bottom_margin", pm, 'bottom-margin')
95 set_paper_variable ("top_margin", pm, 'top-margin')
97 systemlayout = defaults.get_maybe_exist_named_child ('system-layout')
99 sl = systemlayout.get_maybe_exist_named_child ('system-margins')
101 set_paper_variable ("system_left_margin", sl, 'left-margin')
102 set_paper_variable ("system_right_margin", sl, 'right-margin')
103 set_paper_variable ("system_distance", systemlayout, 'system-distance')
104 set_paper_variable ("top_system_distance", systemlayout, 'top-system-distance')
106 stafflayout = defaults.get_named_children ('staff-layout')
107 for sl in stafflayout:
108 nr = getattr (sl, 'number', 1)
109 dist = sl.get_named_child ('staff-distance')
110 #TODO: the staff distance needs to be set in the Staff context!!!
112 # TODO: Finish appearance?, music-font?, word-font?, lyric-font*, lyric-language*
113 appearance = defaults.get_named_child ('appearance')
115 lws = appearance.get_named_children ('line-width')
117 # Possible types are: beam, bracket, dashes,
118 # enclosure, ending, extend, heavy barline, leger,
119 # light barline, octave shift, pedal, slur middle, slur tip,
120 # staff, stem, tie middle, tie tip, tuplet bracket, and wedge
122 w = from_tenths (lw.get_text ())
123 # TODO: Do something with these values!
124 nss = appearance.get_named_children ('note-size')
126 # Possible types are: cue, grace and large
128 sz = from_tenths (ns.get_text ())
129 # TODO: Do something with these values!
130 # <other-appearance> elements have no specified meaning
132 rawmusicfont = defaults.get_named_child ('music-font')
134 # TODO: Convert the font
136 rawwordfont = defaults.get_named_child ('word-font')
138 # TODO: Convert the font
140 rawlyricsfonts = defaults.get_named_children ('lyric-font')
141 for lyricsfont in rawlyricsfonts:
142 # TODO: Convert the font
149 # score information is contained in the <work>, <identification> or <movement-title> tags
150 # extract those into a hash, indexed by proper lilypond header attributes
151 def extract_score_information (tree):
152 header = musicexp.Header ()
153 def set_if_exists (field, value):
155 header.set_field (field, musicxml.escape_ly_output_string (value))
157 work = tree.get_maybe_exist_named_child ('work')
159 set_if_exists ('title', work.get_work_title ())
160 set_if_exists ('worknumber', work.get_work_number ())
161 set_if_exists ('opus', work.get_opus ())
163 movement_title = tree.get_maybe_exist_named_child ('movement-title')
165 set_if_exists ('title', movement_title.get_text ())
167 identifications = tree.get_named_children ('identification')
168 for ids in identifications:
169 set_if_exists ('copyright', ids.get_rights ())
170 set_if_exists ('composer', ids.get_composer ())
171 set_if_exists ('arranger', ids.get_arranger ())
172 set_if_exists ('editor', ids.get_editor ())
173 set_if_exists ('poet', ids.get_poet ())
175 set_if_exists ('tagline', ids.get_encoding_software ())
176 set_if_exists ('encodingsoftware', ids.get_encoding_software ())
177 set_if_exists ('encodingdate', ids.get_encoding_date ())
178 set_if_exists ('encoder', ids.get_encoding_person ())
179 set_if_exists ('encodingdescription', ids.get_encoding_description ())
188 return len (self.start) + len (self.end) == 0
189 def add_start (self, g):
190 self.start[getattr (g, 'number', "1")] = g
191 def add_end (self, g):
192 self.end[getattr (g, 'number', "1")] = g
193 def print_ly (self, printer):
194 error_message ("Unprocessed PartGroupInfo %s encountered" % self)
195 def ly_expression (self):
196 error_message ("Unprocessed PartGroupInfo %s encountered" % self)
199 def staff_attributes_to_string_tunings (mxl_attr):
200 details = mxl_attr.get_maybe_exist_named_child ('staff-details')
204 staff_lines = details.get_maybe_exist_named_child ('staff-lines')
206 lines = string.atoi (staff_lines.get_text ())
209 staff_tunings = details.get_named_children ('staff-tuning')
210 for i in staff_tunings:
214 line = string.atoi (i.line) - 1
219 step = i.get_named_child (u'tuning-step')
220 step = step.get_text ().strip ()
221 p.step = musicxml_step_to_lily (step)
223 octave = i.get_named_child (u'tuning-octave')
224 octave = octave.get_text ().strip ()
225 p.octave = int (octave) - 4
227 alter = i.get_named_child (u'tuning-alter')
229 p.alteration = int (alter.get_text ().strip ())
230 # lilypond seems to use the opposite ordering than MusicXML...
236 def staff_attributes_to_lily_staff (mxl_attr):
238 return musicexp.Staff ()
240 (staff_id, attributes) = mxl_attr.items ()[0]
242 # distinguish by clef:
243 # percussion (percussion and rhythmic), tab, and everything else
245 clef = attributes.get_maybe_exist_named_child ('clef')
247 sign = clef.get_maybe_exist_named_child ('sign')
249 clef_sign = {"percussion": "percussion", "TAB": "tab"}.get (sign.get_text (), None)
252 details = attributes.get_maybe_exist_named_child ('staff-details')
254 staff_lines = details.get_maybe_exist_named_child ('staff-lines')
256 lines = string.atoi (staff_lines.get_text ())
259 if clef_sign == "percussion" and lines == 1:
260 staff = musicexp.RhythmicStaff ()
261 elif clef_sign == "percussion":
262 staff = musicexp.DrumStaff ()
263 # staff.drum_style_table = ???
264 elif clef_sign == "tab":
265 staff = musicexp.TabStaff ()
266 staff.string_tunings = staff_attributes_to_string_tunings (attributes)
267 # staff.tablature_format = ???
269 # TODO: Handle case with lines <> 5!
270 staff = musicexp.Staff ()
275 def extract_score_layout (part_list, staffinfo):
276 layout = musicexp.StaffGroup (None)
280 def read_score_part (el):
281 if not isinstance (el, musicxml.Score_part):
283 # Depending on the attributes of the first measure, we create different
284 # types of staves (Staff, RhythmicStaff, DrumStaff, TabStaff, etc.)
285 staff = staff_attributes_to_lily_staff (staffinfo.get (el.id, None))
289 partname = el.get_maybe_exist_named_child ('part-name')
290 # Finale gives unnamed parts the name "MusicXML Part" automatically!
291 if partname and partname.get_text() != "MusicXML Part":
292 staff.instrument_name = partname.get_text ()
293 if el.get_maybe_exist_named_child ('part-abbreviation'):
294 staff.short_instrument_name = el.get_maybe_exist_named_child ('part-abbreviation').get_text ()
295 # TODO: Read in the MIDI device / instrument
298 def read_score_group (el):
299 if not isinstance (el, musicxml.Part_group):
301 group = musicexp.StaffGroup ()
302 if hasattr (el, 'number'):
305 #currentgroups_dict[id] = group
306 #currentgroups.append (id)
307 if el.get_maybe_exist_named_child ('group-name'):
308 group.instrument_name = el.get_maybe_exist_named_child ('group-name').get_text ()
309 if el.get_maybe_exist_named_child ('group-abbreviation'):
310 group.short_instrument_name = el.get_maybe_exist_named_child ('group-abbreviation').get_text ()
311 if el.get_maybe_exist_named_child ('group-symbol'):
312 group.symbol = el.get_maybe_exist_named_child ('group-symbol').get_text ()
313 if el.get_maybe_exist_named_child ('group-barline'):
314 group.spanbar = el.get_maybe_exist_named_child ('group-barline').get_text ()
318 parts_groups = part_list.get_all_children ()
320 # the start/end group tags are not necessarily ordered correctly and groups
321 # might even overlap, so we can't go through the children sequentially!
323 # 1) Replace all Score_part objects by their corresponding Staff objects,
324 # also collect all group start/stop points into one PartGroupInfo object
326 group_info = PartGroupInfo ()
327 for el in parts_groups:
328 if isinstance (el, musicxml.Score_part):
329 if not group_info.is_empty ():
330 staves.append (group_info)
331 group_info = PartGroupInfo ()
332 staff = read_score_part (el)
334 staves.append (staff)
335 elif isinstance (el, musicxml.Part_group):
336 if el.type == "start":
337 group_info.add_start (el)
338 elif el.type == "stop":
339 group_info.add_end (el)
340 if not group_info.is_empty ():
341 staves.append (group_info)
343 # 2) Now, detect the groups:
346 while pos < len (staves):
348 if isinstance (el, PartGroupInfo):
350 if len (group_starts) > 0:
351 prev_start = group_starts[-1]
352 elif len (el.end) > 0: # no group to end here
354 if len (el.end) > 0: # closes an existing group
355 ends = el.end.keys ()
356 prev_started = staves[prev_start].start.keys ()
358 intersection = filter(lambda x:x in ends, prev_started)
359 if len (intersection) > 0:
360 grpid = intersection[0]
362 # Close the last started group
363 grpid = staves[prev_start].start.keys () [0]
364 # Find the corresponding closing tag and remove it!
367 while j < len (staves) and not foundclosing:
368 if isinstance (staves[j], PartGroupInfo) and staves[j].end.has_key (grpid):
370 del staves[j].end[grpid]
371 if staves[j].is_empty ():
374 grpobj = staves[prev_start].start[grpid]
375 group = read_score_group (grpobj)
376 # remove the id from both the start and end
377 if el.end.has_key (grpid):
379 del staves[prev_start].start[grpid]
382 # replace the staves with the whole group
383 for j in staves[(prev_start + 1):pos]:
385 j.stafftype = "InnerStaffGroup"
386 group.append_staff (j)
387 del staves[(prev_start + 1):pos]
388 staves.insert (prev_start + 1, group)
389 # reset pos so that we continue at the correct position
391 # remove an empty start group
392 if staves[prev_start].is_empty ():
393 del staves[prev_start]
394 group_starts.remove (prev_start)
396 elif len (el.start) > 0: # starts new part groups
397 group_starts.append (pos)
400 if len (staves) == 1:
403 layout.append_staff (i)
408 def musicxml_duration_to_lily (mxl_note):
409 d = musicexp.Duration ()
410 # if the note has no Type child, then that method spits out a warning and
411 # returns 0, i.e. a whole note
412 d.duration_log = mxl_note.get_duration_log ()
414 d.dots = len (mxl_note.get_typed_children (musicxml.Dot))
415 # Grace notes by specification have duration 0, so no time modification
416 # factor is possible. It even messes up the output with *0/1
417 if not mxl_note.get_maybe_exist_typed_child (musicxml.Grace):
418 d.factor = mxl_note._duration / d.get_length ()
422 def rational_to_lily_duration (rational_len):
423 d = musicexp.Duration ()
424 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)
425 d.factor = Rational (rational_len.numerator ())
426 if d.duration_log < 0:
427 error_message ("Encountered rational duration with denominator %s, "
428 "unable to convert to lilypond duration" %
429 rational_len.denominator ())
430 # TODO: Test the above error message
435 def musicxml_partial_to_lily (partial_len):
437 p = musicexp.Partial ()
438 p.partial = rational_to_lily_duration (partial_len)
443 # Detect repeats and alternative endings in the chord event list (music_list)
444 # and convert them to the corresponding musicexp objects, containing nested
446 def group_repeats (music_list):
447 repeat_replaced = True
450 # Walk through the list of expressions, looking for repeat structure
451 # (repeat start/end, corresponding endings). If we find one, try to find the
452 # last event of the repeat, replace the whole structure and start over again.
453 # For nested repeats, as soon as we encounter another starting repeat bar,
454 # treat that one first, and start over for the outer repeat.
455 while repeat_replaced and i < 100:
457 repeat_start = -1 # position of repeat start / end
458 repeat_end = -1 # position of repeat start / end
460 ending_start = -1 # position of current ending start
461 endings = [] # list of already finished endings
463 last = len (music_list) - 1
464 repeat_replaced = False
466 while pos < len (music_list) and not repeat_replaced:
468 repeat_finished = False
469 if isinstance (e, RepeatMarker):
470 if not repeat_times and e.times:
471 repeat_times = e.times
472 if e.direction == -1:
474 repeat_finished = True
480 elif e.direction == 1:
486 elif isinstance (e, EndingMarker):
487 if e.direction == -1:
493 elif e.direction == 1:
496 endings.append ([ending_start, pos])
499 elif not isinstance (e, musicexp.BarLine):
500 # As soon as we encounter an element when repeat start and end
501 # is set and we are not inside an alternative ending,
502 # this whole repeat structure is finished => replace it
503 if repeat_start >= 0 and repeat_end > 0 and ending_start < 0:
504 repeat_finished = True
506 # Finish off all repeats without explicit ending bar (e.g. when
507 # we convert only one page of a multi-page score with repeats)
508 if pos == last and repeat_start >= 0:
509 repeat_finished = True
513 if ending_start >= 0:
514 endings.append ([ending_start, pos])
518 # We found the whole structure replace it!
519 r = musicexp.RepeatedMusic ()
520 if repeat_times <= 0:
522 r.repeat_count = repeat_times
523 # don't erase the first element for "implicit" repeats (i.e. no
524 # starting repeat bars at the very beginning)
525 start = repeat_start+1
526 if repeat_start == music_start:
528 r.set_music (music_list[start:repeat_end])
529 for (start, end) in endings:
530 s = musicexp.SequentialMusic ()
531 s.elements = music_list[start+1:end]
533 del music_list[repeat_start:final_marker+1]
534 music_list.insert (repeat_start, r)
535 repeat_replaced = True
537 # TODO: Implement repeats until the end without explicit ending bar
542 def group_tuplets (music_list, events):
545 """Collect Musics from
546 MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
553 for (ev_chord, tuplet_elt, fraction) in events:
554 while (j < len (music_list)):
555 if music_list[j] == ev_chord:
558 if tuplet_elt.type == 'start':
559 indices.append ((j, None, fraction))
560 elif tuplet_elt.type == 'stop':
561 indices[-1] = (indices[-1][0], j, indices[-1][2])
565 for (i1, i2, frac) in indices:
569 new_list.extend (music_list[last:i1])
570 seq = musicexp.SequentialMusic ()
572 seq.elements = music_list[i1:last]
574 tsm = musicexp.TimeScaledMusic ()
577 tsm.numerator = frac[0]
578 tsm.denominator = frac[1]
580 new_list.append (tsm)
582 new_list.extend (music_list[last:])
586 def musicxml_clef_to_lily (attributes):
587 change = musicexp.ClefChange ()
588 (change.type, change.position, change.octave) = attributes.get_clef_information ()
591 def musicxml_time_to_lily (attributes):
592 (beats, type) = attributes.get_time_signature ()
594 change = musicexp.TimeSignatureChange()
595 change.fraction = (beats, type)
599 def musicxml_key_to_lily (attributes):
600 start_pitch = musicexp.Pitch ()
601 (fifths, mode) = attributes.get_key_signature ()
608 start_pitch.alteration = a
610 error_message ('unknown mode %s' % mode)
612 fifth = musicexp.Pitch()
619 for x in range (fifths):
620 start_pitch = start_pitch.transposed (fifth)
622 start_pitch.octave = 0
624 change = musicexp.KeySignatureChange()
626 change.tonic = start_pitch
629 def musicxml_attributes_to_lily (attrs):
632 'clef': musicxml_clef_to_lily,
633 'time': musicxml_time_to_lily,
634 'key': musicxml_key_to_lily
636 for (k, func) in attr_dispatch.items ():
637 children = attrs.get_named_children (k)
639 elts.append (func (attrs))
643 class Marker (musicexp.Music):
647 def print_ly (self, printer):
648 sys.stderr.write ("Encountered unprocessed marker %s\n" % self)
650 def ly_expression (self):
652 class RepeatMarker (Marker):
654 Marker.__init__ (self)
656 class EndingMarker (Marker):
659 # Convert the <barline> element to musicxml.BarLine (for non-standard barlines)
660 # and to RepeatMarker and EndingMarker objects for repeat and
661 # alternatives start/stops
662 def musicxml_barline_to_lily (barline):
663 # retval contains all possible markers in the order:
664 # 0..bw_ending, 1..bw_repeat, 2..barline, 3..fw_repeat, 4..fw_ending
666 bartype_element = barline.get_maybe_exist_named_child ("bar-style")
667 repeat_element = barline.get_maybe_exist_named_child ("repeat")
668 ending_element = barline.get_maybe_exist_named_child ("ending")
672 bartype = bartype_element.get_text ()
674 if repeat_element and hasattr (repeat_element, 'direction'):
675 repeat = RepeatMarker ()
676 repeat.direction = {"forward": -1, "backward": 1}.get (repeat_element.direction, 0)
678 if ( (repeat_element.direction == "forward" and bartype == "heavy-light") or
679 (repeat_element.direction == "backward" and bartype == "light-heavy") ):
681 if hasattr (repeat_element, 'times'):
683 repeat.times = int (repeat_element.times)
686 repeat.event = barline
687 if repeat.direction == -1:
692 if ending_element and hasattr (ending_element, 'type'):
693 ending = EndingMarker ()
694 ending.direction = {"start": -1, "stop": 1, "discontinue": 1}.get (ending_element.type, 0)
695 ending.event = barline
696 if ending.direction == -1:
702 b = musicexp.BarLine ()
706 return retval.values ()
708 spanner_event_dict = {
709 'slur' : musicexp.SlurEvent,
710 'beam' : musicexp.BeamEvent,
711 'glissando' : musicexp.GlissandoEvent,
712 'pedal' : musicexp.PedalEvent,
713 'wavy-line' : musicexp.TrillSpanEvent,
714 'octave-shift' : musicexp.OctaveShiftEvent,
715 'wedge' : musicexp.HairpinEvent
717 spanner_type_dict = {
730 def musicxml_spanner_to_lily_event (mxl_event):
733 name = mxl_event.get_name()
734 func = spanner_event_dict.get (name)
738 error_message ('unknown span event %s' % mxl_event)
741 type = mxl_event.get_type ()
742 span_direction = spanner_type_dict.get (type)
743 # really check for None, because some types will be translated to 0, which
744 # would otherwise also lead to the unknown span warning
745 if span_direction != None:
746 ev.span_direction = span_direction
748 error_message ('unknown span type %s for %s' % (type, name))
750 ev.set_span_type (type)
751 ev.line_type = getattr (mxl_event, 'line-type', 'solid')
753 # assign the size, which is used for octave-shift, etc.
754 ev.size = mxl_event.get_size ()
758 def musicxml_direction_to_indicator (direction):
759 return { "above": 1, "upright": 1, "up":1, "below": -1, "downright": -1, "down": -1 }.get (direction, 0)
761 def musicxml_fermata_to_lily_event (mxl_event):
762 ev = musicexp.ArticulationEvent ()
764 if hasattr (mxl_event, 'type'):
765 dir = musicxml_direction_to_indicator (mxl_event.type)
766 if dir and options.convert_directions:
767 ev.force_direction = dir
770 def musicxml_arpeggiate_to_lily_event (mxl_event):
771 ev = musicexp.ArpeggioEvent ()
772 ev.direction = musicxml_direction_to_indicator (getattr (mxl_event, 'direction', None))
775 def musicxml_tremolo_to_lily_event (mxl_event):
776 ev = musicexp.TremoloEvent ()
777 txt = mxl_event.get_text ()
779 ev.bars = mxl_event.get_text ()
784 def musicxml_falloff_to_lily_event (mxl_event):
785 ev = musicexp.BendEvent ()
789 def musicxml_doit_to_lily_event (mxl_event):
790 ev = musicexp.BendEvent ()
794 def musicxml_bend_to_lily_event (mxl_event):
795 ev = musicexp.BendEvent ()
796 ev.alter = mxl_event.bend_alter ()
799 def musicxml_caesura_to_lily_event (mxl_event):
800 ev = musicexp.MarkupEvent ()
801 # FIXME: default to straight or curved caesura?
802 ev.contents = "\\musicglyph #\"scripts.caesura.straight\""
803 ev.force_direction = 1
806 def musicxml_fingering_event (mxl_event):
807 ev = musicexp.ShortArticulationEvent ()
808 ev.type = mxl_event.get_text ()
811 def musicxml_snappizzicato_event (mxl_event):
812 needed_additional_definitions.append ("snappizzicato")
813 ev = musicexp.MarkupEvent ()
814 ev.contents = "\\snappizzicato"
817 def musicxml_string_event (mxl_event):
818 ev = musicexp.NoDirectionArticulationEvent ()
819 ev.type = mxl_event.get_text ()
822 def musicxml_accidental_mark (mxl_event):
823 ev = musicexp.MarkupEvent ()
824 contents = { "sharp": "\\sharp",
825 "natural": "\\natural",
827 "double-sharp": "\\doublesharp",
828 "sharp-sharp": "\\sharp\\sharp",
829 "flat-flat": "\\flat\\flat",
830 "flat-flat": "\\doubleflat",
831 "natural-sharp": "\\natural\\sharp",
832 "natural-flat": "\\natural\\flat",
833 "quarter-flat": "\\semiflat",
834 "quarter-sharp": "\\semisharp",
835 "three-quarters-flat": "\\sesquiflat",
836 "three-quarters-sharp": "\\sesquisharp",
837 }.get (mxl_event.get_text ())
839 ev.contents = contents
844 # translate articulations, ornaments and other notations into ArticulationEvents
846 # -) string (ArticulationEvent with that name)
847 # -) function (function(mxl_event) needs to return a full ArticulationEvent-derived object
848 # -) (class, name) (like string, only that a different class than ArticulationEvent is used)
849 # TODO: Some translations are missing!
850 articulations_dict = {
851 "accent": (musicexp.ShortArticulationEvent, ">"), # or "accent"
852 "accidental-mark": musicxml_accidental_mark,
853 "bend": musicxml_bend_to_lily_event,
854 "breath-mark": (musicexp.NoDirectionArticulationEvent, "breathe"),
855 "caesura": musicxml_caesura_to_lily_event,
856 #"delayed-turn": "?",
857 "detached-legato": (musicexp.ShortArticulationEvent, "_"), # or "portato"
858 "doit": musicxml_doit_to_lily_event,
859 #"double-tongue": "",
860 "down-bow": "downbow",
861 "falloff": musicxml_falloff_to_lily_event,
862 "fingering": musicxml_fingering_event,
866 "harmonic": "flageolet",
868 "inverted-mordent": "prall",
869 "inverted-turn": "reverseturn",
870 "mordent": "mordent",
871 "open-string": "open",
878 "snap-pizzicato": musicxml_snappizzicato_event,
880 "staccatissimo": (musicexp.ShortArticulationEvent, "|"), # or "staccatissimo"
881 "staccato": (musicexp.ShortArticulationEvent, "."), # or "staccato"
882 "stopped": (musicexp.ShortArticulationEvent, "+"), # or "stopped"
884 "string": musicxml_string_event,
885 "strong-accent": (musicexp.ShortArticulationEvent, "^"), # or "marcato"
887 "tenuto": (musicexp.ShortArticulationEvent, "-"), # or "tenuto"
888 #"thumb-position": "",
891 "tremolo": musicxml_tremolo_to_lily_event,
892 "trill-mark": "trill",
893 #"triple-tongue": "",
898 articulation_spanners = [ "wavy-line" ]
900 def musicxml_articulation_to_lily_event (mxl_event):
901 # wavy-line elements are treated as trill spanners, not as articulation ornaments
902 if mxl_event.get_name () in articulation_spanners:
903 return musicxml_spanner_to_lily_event (mxl_event)
905 tmp_tp = articulations_dict.get (mxl_event.get_name ())
909 if isinstance (tmp_tp, str):
910 ev = musicexp.ArticulationEvent ()
912 elif isinstance (tmp_tp, tuple):
916 ev = tmp_tp (mxl_event)
918 # Some articulations use the type attribute, other the placement...
920 if hasattr (mxl_event, 'type') and options.convert_directions:
921 dir = musicxml_direction_to_indicator (mxl_event.type)
922 if hasattr (mxl_event, 'placement') and options.convert_directions:
923 dir = musicxml_direction_to_indicator (mxl_event.placement)
925 ev.force_direction = dir
929 def musicxml_dynamics_to_lily_event (dynentry):
930 dynamics_available = ( "p", "pp", "ppp", "pppp", "ppppp", "pppppp",
931 "f", "ff", "fff", "ffff", "fffff", "ffffff",
932 "mp", "mf", "sf", "sfp", "sfpp", "fp",
933 "rf", "rfz", "sfz", "sffz", "fz" )
934 if not dynentry.get_name() in dynamics_available:
936 event = musicexp.DynamicsEvent ()
937 event.type = dynentry.get_name ()
940 # Convert single-color two-byte strings to numbers 0.0 - 1.0
941 def hexcolorval_to_nr (hex_val):
943 v = int (hex_val, 16)
950 def hex_to_color (hex_val):
951 res = re.match (r'#([0-9a-f][0-9a-f]|)([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])$', hex_val, re.IGNORECASE)
953 return map (lambda x: hexcolorval_to_nr (x), res.group (2,3,4))
957 def musicxml_words_to_lily_event (words):
958 event = musicexp.TextEvent ()
959 text = words.get_text ()
960 text = re.sub ('^ *\n? *', '', text)
961 text = re.sub (' *\n? *$', '', text)
964 if hasattr (words, 'default-y') and options.convert_directions:
965 offset = getattr (words, 'default-y')
967 off = string.atoi (offset)
969 event.force_direction = 1
971 event.force_direction = -1
973 event.force_direction = 0
975 if hasattr (words, 'font-weight'):
976 font_weight = { "normal": '', "bold": '\\bold' }.get (getattr (words, 'font-weight'), '')
978 event.markup += font_weight
980 if hasattr (words, 'font-size'):
981 size = getattr (words, 'font-size')
983 "xx-small": '\\teeny',
989 "xx-large": '\\bigger\\huge'
992 event.markup += font_size
994 if hasattr (words, 'color'):
995 color = getattr (words, 'color')
996 rgb = hex_to_color (color)
998 event.markup += "\\with-color #(rgb-color %s %s %s)" % (rgb[0], rgb[1], rgb[2])
1000 if hasattr (words, 'font-style'):
1001 font_style = { "italic": '\\italic' }.get (getattr (words, 'font-style'), '')
1003 event.markup += font_style
1005 # TODO: How should I best convert the font-family attribute?
1007 # TODO: How can I represent the underline, overline and line-through
1008 # attributes in Lilypond? Values of these attributes indicate
1009 # the number of lines
1014 direction_spanners = [ 'octave-shift', 'pedal', 'wedge' ]
1016 def musicxml_direction_to_lily (n):
1017 # TODO: Handle the <staff> element!
1019 dirtype_children = []
1020 for dt in n.get_typed_children (musicxml.DirType):
1021 dirtype_children += dt.get_all_children ()
1023 for entry in dirtype_children:
1025 if entry.get_name () == "dynamics":
1026 for dynentry in entry.get_all_children ():
1027 ev = musicxml_dynamics_to_lily_event (dynentry)
1031 if entry.get_name () == "words":
1032 ev = musicxml_words_to_lily_event (entry)
1036 # octave shifts. pedal marks, hairpins etc. are spanners:
1037 if entry.get_name() in direction_spanners:
1038 event = musicxml_spanner_to_lily_event (entry)
1045 def musicxml_frame_to_lily_event (frame):
1046 ev = musicexp.FretEvent ()
1047 ev.strings = frame.get_strings ()
1048 ev.frets = frame.get_frets ()
1049 #offset = frame.get_first_fret () - 1
1051 for fn in frame.get_named_children ('frame-note'):
1052 fret = fn.get_fret ()
1055 el = [ fn.get_string (), fret ]
1056 fingering = fn.get_fingering ()
1058 el.append (fingering)
1059 ev.elements.append (el)
1062 barre[0] = el[0] # start string
1063 barre[2] = el[1] # fret
1065 barre[1] = el[0] # end string
1070 def musicxml_harmony_to_lily (n):
1072 for f in n.get_named_children ('frame'):
1073 ev = musicxml_frame_to_lily_event (f)
1079 instrument_drumtype_dict = {
1080 'Acoustic Snare Drum': 'acousticsnare',
1081 'Side Stick': 'sidestick',
1082 'Open Triangle': 'opentriangle',
1083 'Mute Triangle': 'mutetriangle',
1084 'Tambourine': 'tambourine',
1085 'Bass Drum': 'bassdrum',
1088 def musicxml_note_to_lily_main_event (n):
1093 mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
1095 pitch = musicxml_pitch_to_lily (mxl_pitch)
1096 event = musicexp.NoteEvent ()
1099 acc = n.get_maybe_exist_named_child ('accidental')
1101 # let's not force accs everywhere.
1102 event.cautionary = acc.editorial
1104 elif n.get_maybe_exist_typed_child (musicxml.Unpitched):
1105 # Unpitched elements have display-step and can also have
1107 unpitched = n.get_maybe_exist_typed_child (musicxml.Unpitched)
1108 event = musicexp.NoteEvent ()
1109 event.pitch = musicxml_unpitched_to_lily (unpitched)
1111 elif n.get_maybe_exist_typed_child (musicxml.Rest):
1112 # rests can have display-octave and display-step, which are
1113 # treated like an ordinary note pitch
1114 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
1115 event = musicexp.RestEvent ()
1116 pitch = musicxml_restdisplay_to_lily (rest)
1119 elif n.instrument_name:
1120 event = musicexp.NoteEvent ()
1121 drum_type = instrument_drumtype_dict.get (n.instrument_name)
1123 event.drum_type = drum_type
1125 n.message ("drum %s type unknown, please add to instrument_drumtype_dict" % n.instrument_name)
1126 event.drum_type = 'acousticsnare'
1129 n.message ("cannot find suitable event")
1132 event.duration = musicxml_duration_to_lily (n)
1139 def __init__ (self, here, dest):
1143 class LilyPondVoiceBuilder:
1144 def __init__ (self):
1146 self.pending_dynamics = []
1147 self.end_moment = Rational (0)
1148 self.begin_moment = Rational (0)
1149 self.pending_multibar = Rational (0)
1150 self.ignore_skips = False
1152 def _insert_multibar (self):
1153 r = musicexp.MultiMeasureRest ()
1154 r.duration = musicexp.Duration()
1155 r.duration.duration_log = 0
1156 r.duration.factor = self.pending_multibar
1157 self.elements.append (r)
1158 self.begin_moment = self.end_moment
1159 self.end_moment = self.begin_moment + self.pending_multibar
1160 self.pending_multibar = Rational (0)
1162 def add_multibar_rest (self, duration):
1163 self.pending_multibar += duration
1165 def set_duration (self, duration):
1166 self.end_moment = self.begin_moment + duration
1167 def current_duration (self):
1168 return self.end_moment - self.begin_moment
1170 def add_music (self, music, duration):
1171 assert isinstance (music, musicexp.Music)
1172 if self.pending_multibar > Rational (0):
1173 self._insert_multibar ()
1175 self.elements.append (music)
1176 self.begin_moment = self.end_moment
1177 self.set_duration (duration)
1179 # Insert all pending dynamics right after the note/rest:
1180 if isinstance (music, musicexp.ChordEvent) and self.pending_dynamics:
1181 for d in self.pending_dynamics:
1183 self.pending_dynamics = []
1185 # Insert some music command that does not affect the position in the measure
1186 def add_command (self, command):
1187 assert isinstance (command, musicexp.Music)
1188 if self.pending_multibar > Rational (0):
1189 self._insert_multibar ()
1190 self.elements.append (command)
1191 def add_barline (self, barline):
1192 # TODO: Implement merging of default barline and custom bar line
1193 self.add_music (barline, Rational (0))
1194 def add_partial (self, command):
1195 self.ignore_skips = True
1196 self.add_command (command)
1198 def add_dynamics (self, dynamic):
1199 # store the dynamic item(s) until we encounter the next note/rest:
1200 self.pending_dynamics.append (dynamic)
1202 def add_bar_check (self, number):
1203 b = musicexp.BarLine ()
1204 b.bar_number = number
1205 self.add_barline (b)
1207 def jumpto (self, moment):
1208 current_end = self.end_moment + self.pending_multibar
1209 diff = moment - current_end
1211 if diff < Rational (0):
1212 error_message ('Negative skip %s' % diff)
1215 if diff > Rational (0) and not (self.ignore_skips and moment == 0):
1216 skip = musicexp.SkipEvent()
1218 duration_log = {1: 0, 2: 1, 4:2, 8:3, 16:4, 32:5, 64:6, 128:7, 256:8, 512:9}.get (diff.denominator (), -1)
1220 if duration_log > 0: # denominator is a power of 2...
1221 if diff.numerator () == 3:
1225 duration_factor = Rational (diff.numerator ())
1228 duration_factor = diff
1229 skip.duration.duration_log = duration_log
1230 skip.duration.factor = duration_factor
1231 skip.duration.dots = duration_dots
1233 evc = musicexp.ChordEvent ()
1234 evc.elements.append (skip)
1235 self.add_music (evc, diff)
1237 if diff > Rational (0) and moment == 0:
1238 self.ignore_skips = False
1240 def last_event_chord (self, starting_at):
1244 # if the position matches, find the last ChordEvent, do not cross a bar line!
1245 at = len( self.elements ) - 1
1247 not isinstance (self.elements[at], musicexp.ChordEvent) and
1248 not isinstance (self.elements[at], musicexp.BarLine)):
1253 and isinstance (self.elements[at], musicexp.ChordEvent)
1254 and self.begin_moment == starting_at):
1255 value = self.elements[at]
1257 self.jumpto (starting_at)
1261 def correct_negative_skip (self, goto):
1262 self.end_moment = goto
1263 self.begin_moment = goto
1264 evc = musicexp.ChordEvent ()
1265 self.elements.append (evc)
1269 def __init__ (self):
1270 self.voicedata = None
1271 self.ly_voice = None
1272 self.lyrics_dict = {}
1273 self.lyrics_order = []
1275 def musicxml_step_to_lily (step):
1277 return (ord (step) - ord ('A') + 7 - 2) % 7
1281 def musicxml_voice_to_lily_voice (voice):
1285 return_value = VoiceData ()
1286 return_value.voicedata = voice
1288 # First pitch needed for relative mode (if selected in command-line options)
1291 # Needed for melismata detection (ignore lyrics on those notes!):
1295 ignore_lyrics = False
1297 current_staff = None
1299 # Make sure that the keys in the dict don't get reordered, since
1300 # we need the correct ordering of the lyrics stanzas! By default,
1301 # a dict will reorder its keys
1302 return_value.lyrics_order = voice.get_lyrics_numbers ()
1303 for k in return_value.lyrics_order:
1306 voice_builder = LilyPondVoiceBuilder()
1308 for n in voice._elements:
1309 if n.get_name () == 'forward':
1311 staff = n.get_maybe_exist_named_child ('staff')
1313 staff = staff.get_text ()
1314 if current_staff and staff <> current_staff and not n.get_maybe_exist_named_child ('chord'):
1315 voice_builder.add_command (musicexp.StaffChange (staff))
1316 current_staff = staff
1318 if isinstance (n, musicxml.Partial) and n.partial > 0:
1319 a = musicxml_partial_to_lily (n.partial)
1321 voice_builder.add_partial (a)
1324 if isinstance (n, musicxml.Direction):
1325 for a in musicxml_direction_to_lily (n):
1326 if a.wait_for_note ():
1327 voice_builder.add_dynamics (a)
1329 voice_builder.add_command (a)
1332 if isinstance (n, musicxml.Harmony):
1333 for a in musicxml_harmony_to_lily (n):
1334 if a.wait_for_note ():
1335 voice_builder.add_dynamics (a)
1337 voice_builder.add_command (a)
1340 is_chord = n.get_maybe_exist_named_child ('chord')
1343 voice_builder.jumpto (n._when)
1344 except NegativeSkip, neg:
1345 voice_builder.correct_negative_skip (n._when)
1346 n.message ("Negative skip? from %s to %s, diff %s" % (neg.here, neg.dest, neg.dest - neg.here))
1348 if isinstance (n, musicxml.Attributes):
1349 if n.is_first () and n._measure_position == Rational (0):
1351 number = int (n.get_parent ().number)
1355 voice_builder.add_bar_check (number)
1357 for a in musicxml_attributes_to_lily (n):
1358 voice_builder.add_command (a)
1361 if isinstance (n, musicxml.Barline):
1362 barlines = musicxml_barline_to_lily (n)
1364 if isinstance (a, musicexp.BarLine):
1365 voice_builder.add_barline (a)
1366 elif isinstance (a, RepeatMarker) or isinstance (a, EndingMarker):
1367 voice_builder.add_command (a)
1370 if not n.__class__.__name__ == 'Note':
1371 error_message ('not a Note or Attributes? %s' % n)
1374 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
1376 and rest.is_whole_measure ()):
1378 voice_builder.add_multibar_rest (n._duration)
1381 if n.is_first () and n._measure_position == Rational (0):
1383 num = int (n.get_parent ().number)
1387 voice_builder.add_bar_check (num)
1389 main_event = musicxml_note_to_lily_main_event (n)
1390 if main_event and not first_pitch:
1391 first_pitch = main_event.pitch
1392 ignore_lyrics = inside_slur or is_tied or is_chord
1394 if main_event and hasattr (main_event, 'drum_type') and main_event.drum_type:
1395 modes_found['drummode'] = True
1397 ev_chord = voice_builder.last_event_chord (n._when)
1399 ev_chord = musicexp.ChordEvent()
1400 voice_builder.add_music (ev_chord, n._duration)
1402 grace = n.get_maybe_exist_typed_child (musicxml.Grace)
1405 if n.get_maybe_exist_typed_child (musicxml.Chord) and ev_chord.grace_elements:
1406 grace_chord = ev_chord.grace_elements.get_last_event_chord ()
1408 grace_chord = musicexp.ChordEvent ()
1409 ev_chord.append_grace (grace_chord)
1410 if hasattr (grace, 'slash'):
1411 # TODO: use grace_type = "appoggiatura" for slurred grace notes
1412 if grace.slash == "yes":
1413 ev_chord.grace_type = "acciaccatura"
1414 # now that we have inserted the chord into the grace music, insert
1415 # everything into that chord instead of the ev_chord
1416 ev_chord = grace_chord
1417 ev_chord.append (main_event)
1418 ignore_lyrics = True
1420 ev_chord.append (main_event)
1421 # When a note/chord has grace notes (duration==0), the duration of the
1422 # event chord is not yet known, but the event chord was already added
1423 # with duration 0. The following correct this when we hit the real note!
1424 if voice_builder.current_duration () == 0 and n._duration > 0:
1425 voice_builder.set_duration (n._duration)
1427 notations_children = n.get_typed_children (musicxml.Notations)
1431 # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
1432 # +tied | +slur | +tuplet | glissando | slide |
1433 # ornaments | technical | articulations | dynamics |
1434 # +fermata | arpeggiate | non-arpeggiate |
1435 # accidental-mark | other-notation
1436 for notations in notations_children:
1437 for tuplet_event in notations.get_tuplets():
1438 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
1441 frac = mod.get_fraction ()
1443 tuplet_events.append ((ev_chord, tuplet_event, frac))
1445 slurs = [s for s in notations.get_named_children ('slur')
1446 if s.get_type () in ('start','stop')]
1449 error_message ('more than 1 slur?')
1450 # record the slur status for the next note in the loop
1452 if slurs[0].get_type () == 'start':
1454 elif slurs[0].get_type () == 'stop':
1456 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
1457 ev_chord.append (lily_ev)
1460 mxl_tie = notations.get_tie ()
1461 if mxl_tie and mxl_tie.type == 'start':
1462 ev_chord.append (musicexp.TieEvent ())
1467 fermatas = notations.get_named_children ('fermata')
1469 ev = musicxml_fermata_to_lily_event (a)
1471 ev_chord.append (ev)
1473 arpeggiate = notations.get_named_children ('arpeggiate')
1474 for a in arpeggiate:
1475 ev = musicxml_arpeggiate_to_lily_event (a)
1477 ev_chord.append (ev)
1479 glissandos = notations.get_named_children ('glissando')
1480 for a in glissandos:
1481 ev = musicxml_spanner_to_lily_event (a)
1483 ev_chord.append (ev)
1485 # Articulations can contain the following child elements:
1486 # accent | strong-accent | staccato | tenuto |
1487 # detached-legato | staccatissimo | spiccato |
1488 # scoop | plop | doit | falloff | breath-mark |
1489 # caesura | stress | unstress
1490 # Technical can contain the following child elements:
1491 # up-bow | down-bow | harmonic | open-string |
1492 # thumb-position | fingering | pluck | double-tongue |
1493 # triple-tongue | stopped | snap-pizzicato | fret |
1494 # string | hammer-on | pull-off | bend | tap | heel |
1495 # toe | fingernails | other-technical
1496 # Ornaments can contain the following child elements:
1497 # trill-mark | turn | delayed-turn | inverted-turn |
1498 # shake | wavy-line | mordent | inverted-mordent |
1499 # schleifer | tremolo | other-ornament, accidental-mark
1500 ornaments = notations.get_named_children ('ornaments')
1501 ornaments += notations.get_named_children ('articulations')
1502 ornaments += notations.get_named_children ('technical')
1505 for ch in a.get_all_children ():
1506 ev = musicxml_articulation_to_lily_event (ch)
1508 ev_chord.append (ev)
1510 dynamics = notations.get_named_children ('dynamics')
1512 for ch in a.get_all_children ():
1513 ev = musicxml_dynamics_to_lily_event (ch)
1515 ev_chord.append (ev)
1517 # Extract the lyrics
1518 if not rest and not ignore_lyrics:
1519 note_lyrics_processed = []
1520 note_lyrics_elements = n.get_typed_children (musicxml.Lyric)
1521 for l in note_lyrics_elements:
1522 if l.get_number () < 0:
1523 for k in lyrics.keys ():
1524 lyrics[k].append (l.lyric_to_text ())
1525 note_lyrics_processed.append (k)
1527 lyrics[l.number].append(l.lyric_to_text ())
1528 note_lyrics_processed.append (l.number)
1529 for lnr in lyrics.keys ():
1530 if not lnr in note_lyrics_processed:
1531 lyrics[lnr].append ("\skip4")
1534 mxl_beams = [b for b in n.get_named_children ('beam')
1535 if (b.get_type () in ('begin', 'end')
1536 and b.is_primary ())]
1538 beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
1540 ev_chord.append (beam_ev)
1543 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
1546 frac = mod.get_fraction ()
1548 tuplet_events.append ((ev_chord, tuplet_event, frac))
1550 ## force trailing mm rests to be written out.
1551 voice_builder.add_music (musicexp.ChordEvent (), Rational (0))
1553 ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
1554 ly_voice = group_repeats (ly_voice)
1556 seq_music = musicexp.SequentialMusic ()
1558 if 'drummode' in modes_found.keys ():
1559 ## \key <pitch> barfs in drummode.
1560 ly_voice = [e for e in ly_voice
1561 if not isinstance(e, musicexp.KeySignatureChange)]
1563 seq_music.elements = ly_voice
1564 for k in lyrics.keys ():
1565 return_value.lyrics_dict[k] = musicexp.Lyrics ()
1566 return_value.lyrics_dict[k].lyrics_syllables = lyrics[k]
1569 if len (modes_found) > 1:
1570 error_message ('Too many modes found %s' % modes_found.keys ())
1572 if options.relative:
1573 v = musicexp.RelativeMusic ()
1574 v.element = seq_music
1575 v.basepitch = first_pitch
1578 return_value.ly_voice = seq_music
1579 for mode in modes_found.keys ():
1580 v = musicexp.ModeChangingMusicWrapper()
1581 v.element = seq_music
1583 return_value.ly_voice = v
1587 def musicxml_id_to_lily (id):
1588 digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five',
1589 'Six', 'Seven', 'Eight', 'Nine', 'Ten']
1591 for digit in digits:
1592 d = digits.index (digit)
1593 id = re.sub ('%d' % d, digit, id)
1595 id = re.sub ('[^a-zA-Z]', 'X', id)
1598 def musicxml_pitch_to_lily (mxl_pitch):
1599 p = musicexp.Pitch ()
1600 p.alteration = mxl_pitch.get_alteration ()
1601 p.step = musicxml_step_to_lily (mxl_pitch.get_step ())
1602 p.octave = mxl_pitch.get_octave () - 4
1605 def musicxml_unpitched_to_lily (mxl_unpitched):
1607 step = mxl_unpitched.get_step ()
1609 p = musicexp.Pitch ()
1610 p.step = musicxml_step_to_lily (step)
1611 octave = mxl_unpitched.get_octave ()
1613 p.octave = octave - 4
1616 def musicxml_restdisplay_to_lily (mxl_rest):
1618 step = mxl_rest.get_step ()
1620 p = musicexp.Pitch ()
1621 p.step = musicxml_step_to_lily (step)
1622 octave = mxl_rest.get_octave ()
1624 p.octave = octave - 4
1627 def voices_in_part (part):
1628 """Return a Name -> Voice dictionary for PART"""
1630 part.extract_voices ()
1631 voices = part.get_voices ()
1632 part_info = part.get_staff_attributes ()
1634 return (voices, part_info)
1636 def voices_in_part_in_parts (parts):
1637 """return a Part -> Name -> Voice dictionary"""
1638 return dict([(p.id, voices_in_part (p)) for p in parts])
1641 def get_all_voices (parts):
1642 all_voices = voices_in_part_in_parts (parts)
1645 all_ly_staffinfo = {}
1646 for p, (name_voice, staff_info) in all_voices.items ():
1649 for n, v in name_voice.items ():
1650 progress ("Converting to LilyPond expressions...")
1651 # musicxml_voice_to_lily_voice returns (lily_voice, {nr->lyrics, nr->lyrics})
1652 part_ly_voices[n] = musicxml_voice_to_lily_voice (v)
1654 all_ly_voices[p] = part_ly_voices
1655 all_ly_staffinfo[p] = staff_info
1657 return (all_ly_voices, all_ly_staffinfo)
1660 def option_parser ():
1661 p = ly.get_option_parser(usage=_ ("musicxml2ly [options] FILE.xml"),
1662 version=('''%prog (LilyPond) @TOPLEVEL_VERSION@\n\n'''
1664 _ ("""This program is free software. It is covered by the GNU General Public
1665 License and you are welcome to change it and/or distribute copies of it
1666 under certain conditions. Invoke as `%s --warranty' for more
1667 information.""") % 'lilypond'
1669 Copyright (c) 2005--2007 by
1670 Han-Wen Nienhuys <hanwen@xs4all.nl>,
1671 Jan Nieuwenhuizen <janneke@gnu.org> and
1672 Reinhold Kainhofer <reinhold@kainhofer.com>
1674 description=_ ("Convert %s to LilyPond input.") % 'MusicXML' + "\n")
1675 p.add_option ('-v', '--verbose',
1676 action="store_true",
1678 help=_ ("be verbose"))
1680 p.add_option ('', '--lxml',
1681 action="store_true",
1684 help=_ ("Use lxml.etree; uses less memory and cpu time."))
1686 p.add_option ('-z', '--compressed',
1687 action = "store_true",
1688 dest = 'compressed',
1690 help = _ ("Input file is a zip-compressed MusicXML file."))
1692 p.add_option ('-r', '--relative',
1693 action = "store_true",
1695 help = _ ("Convert pitches in relative mode."))
1697 p.add_option ('-l', '--language',
1699 help = _ ("Use a different language file, e.g. 'deutsch' for deutsch.ly."))
1701 p.add_option ('--no-articulation-directions', '--nd',
1702 action = "store_false",
1704 dest = "convert_directions",
1705 help = _ ("Do not convert directions (^, _ or -) for articulations."))
1707 p.add_option ('-o', '--output',
1713 help=_ ("set output filename to FILE"))
1714 p.add_option_group ('bugs',
1715 description=(_ ("Report bugs via")
1716 + ''' http://post.gmane.org/post.php'''
1717 '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
1720 def music_xml_voice_name_to_lily_name (part_id, name):
1721 str = "Part%sVoice%s" % (part_id, name)
1722 return musicxml_id_to_lily (str)
1724 def music_xml_lyrics_name_to_lily_name (part_id, name, lyricsnr):
1725 str = "Part%sVoice%sLyrics%s" % (part_id, name, lyricsnr)
1726 return musicxml_id_to_lily (str)
1728 def print_voice_definitions (printer, part_list, voices):
1729 for part in part_list:
1731 nv_dict = voices.get (part_id, {})
1732 for (name, voice) in nv_dict.items ():
1733 k = music_xml_voice_name_to_lily_name (part_id, name)
1734 printer.dump ('%s = ' % k)
1735 voice.ly_voice.print_ly (printer)
1737 for l in voice.lyrics_order:
1738 lname = music_xml_lyrics_name_to_lily_name (part_id, name, l)
1739 printer.dump ('%s = ' %lname )
1740 voice.lyrics_dict[l].print_ly (printer)
1745 return dict ([(elt,1) for elt in l]).keys ()
1747 # format the information about the staff in the form
1750 # [voiceid1, [lyricsid11, lyricsid12,...] ...],
1751 # [voiceid2, [lyricsid21, lyricsid22,...] ...],
1755 # raw_voices is of the form [(voicename, lyricsids)*]
1756 def format_staff_info (part_id, staff_id, raw_voices):
1758 for (v, lyricsids) in raw_voices:
1759 voice_name = music_xml_voice_name_to_lily_name (part_id, v)
1760 voice_lyrics = [music_xml_lyrics_name_to_lily_name (part_id, v, l)
1762 voices.append ([voice_name, voice_lyrics])
1763 return [staff_id, voices]
1765 def update_score_setup (score_structure, part_list, voices):
1767 for part_definition in part_list:
1768 part_id = part_definition.id
1769 nv_dict = voices.get (part_id)
1771 error_message ('unknown part in part-list: %s' % part_id)
1774 staves = reduce (lambda x,y: x+ y,
1775 [voice.voicedata._staves.keys ()
1776 for voice in nv_dict.values ()],
1779 if len (staves) > 1:
1781 staves = uniq_list (staves)
1784 thisstaff_raw_voices = [(voice_name, voice.lyrics_order)
1785 for (voice_name, voice) in nv_dict.items ()
1786 if voice.voicedata._start_staff == s]
1787 staves_info.append (format_staff_info (part_id, s, thisstaff_raw_voices))
1789 thisstaff_raw_voices = [(voice_name, voice.lyrics_order)
1790 for (voice_name, voice) in nv_dict.items ()]
1791 staves_info.append (format_staff_info (part_id, None, thisstaff_raw_voices))
1792 score_structure.set_part_information (part_id, staves_info)
1794 def print_ly_preamble (printer, filename):
1795 printer.dump_version ()
1796 printer.print_verbatim ('%% automatically converted from %s\n' % filename)
1798 def print_ly_additional_definitions (printer, filename):
1799 if needed_additional_definitions:
1801 printer.print_verbatim ('%% additional definitions required by the score:')
1803 for a in set(needed_additional_definitions):
1804 printer.print_verbatim (additional_definitions.get (a, ''))
1807 # Read in the tree from the given I/O object (either file or string) and
1808 # demarshall it using the classes from the musicxml.py file
1809 def read_xml (io_object, use_lxml):
1812 tree = lxml.etree.parse (io_object)
1813 mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
1816 from xml.dom import minidom, Node
1817 doc = minidom.parse(io_object)
1818 node = doc.documentElement
1819 return musicxml.minidom_demarshal_node (node)
1823 def read_musicxml (filename, compressed, use_lxml):
1826 progress ("Input file %s is compressed, extracting raw MusicXML data" % filename)
1827 z = zipfile.ZipFile (filename, "r")
1828 container_xml = z.read ("META-INF/container.xml")
1829 if not container_xml:
1831 container = read_xml (StringIO.StringIO (container_xml), use_lxml)
1834 rootfiles = container.get_maybe_exist_named_child ('rootfiles')
1837 rootfile_list = rootfiles.get_named_children ('rootfile')
1839 if len (rootfile_list) > 0:
1840 mxml_file = getattr (rootfile_list[0], 'full-path', None)
1842 raw_string = z.read (mxml_file)
1844 io_object = filename
1846 io_object = StringIO.StringIO (raw_string)
1848 return read_xml (io_object, use_lxml)
1851 def convert (filename, options):
1852 progress ("Reading MusicXML from %s ..." % filename)
1854 tree = read_musicxml (filename, options.compressed, options.use_lxml)
1855 parts = tree.get_typed_children (musicxml.Part)
1856 (voices, staff_info) = get_all_voices (parts)
1858 score_structure = None
1859 mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
1861 score_structure = extract_score_layout (mxl_pl, staff_info)
1862 part_list = mxl_pl.get_named_children ("score-part")
1864 # score information is contained in the <work>, <identification> or <movement-title> tags
1865 score_information = extract_score_information (tree)
1866 layout_information = extract_layout_information (tree)
1867 update_score_setup (score_structure, part_list, voices)
1869 if not options.output_name:
1870 options.output_name = os.path.basename (filename)
1871 options.output_name = os.path.splitext (options.output_name)[0]
1872 elif re.match (".*\.ly", options.output_name):
1873 options.output_name = os.path.splitext (options.output_name)[0]
1876 defs_ly_name = options.output_name + '-defs.ly'
1877 driver_ly_name = options.output_name + '.ly'
1879 printer = musicexp.Output_printer()
1880 progress ("Output to `%s'" % defs_ly_name)
1881 printer.set_file (codecs.open (defs_ly_name, 'wb', encoding='utf-8'))
1883 print_ly_preamble (printer, filename)
1884 print_ly_additional_definitions (printer, filename)
1885 if score_information:
1886 score_information.print_ly (printer)
1887 if layout_information:
1888 layout_information.print_ly (printer)
1889 print_voice_definitions (printer, part_list, voices)
1894 progress ("Output to `%s'" % driver_ly_name)
1895 printer = musicexp.Output_printer()
1896 printer.set_file (codecs.open (driver_ly_name, 'wb', encoding='utf-8'))
1897 print_ly_preamble (printer, filename)
1898 printer.dump (r'\include "%s"' % os.path.basename (defs_ly_name))
1899 score_structure.print_ly (printer)
1904 def get_existing_filename_with_extension (filename, ext):
1905 if os.path.exists (filename):
1907 newfilename = filename + "." + ext
1908 if os.path.exists (newfilename):
1910 newfilename = filename + ext
1911 if os.path.exists (newfilename):
1916 opt_parser = option_parser()
1919 (options, args) = opt_parser.parse_args ()
1921 opt_parser.print_usage()
1924 if options.language:
1925 musicexp.set_pitch_language (options.language)
1926 needed_additional_definitions.append (options.language)
1927 additional_definitions[options.language] = "\\include \"%s.ly\"\n" % options.language
1929 # Allow the user to leave out the .xml or xml on the filename
1930 filename = get_existing_filename_with_extension (args[0], "xml")
1932 filename = get_existing_filename_with_extension (args[0], "mxl")
1933 options.compressed = True
1934 if filename and os.path.exists (filename):
1935 voices = convert (filename, options)
1937 progress ("Unable to find input file %s" % args[0])
1939 if __name__ == '__main__':