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 ())
70 return len (self.start) + len (self.end) == 0
71 def add_start (self, g):
72 self.start[getattr (g, 'number', "1")] = g
73 def add_end (self, g):
74 self.end[getattr (g, 'number', "1")] = g
75 def print_ly (self, printer):
76 error_message ("Unprocessed PartGroupInfo %s encountered" % self)
77 def ly_expression (self):
78 error_message ("Unprocessed PartGroupInfo %s encountered" % self)
82 def staff_attributes_to_string_tunings (mxl_attr):
83 details = mxl_attr.get_maybe_exist_named_child ('staff-details')
87 staff_lines = details.get_maybe_exist_named_child ('staff-lines')
89 lines = string.atoi (staff_lines.get_text ())
92 staff_tunings = details.get_named_children ('staff-tuning')
93 for i in staff_tunings:
97 line = string.atoi (i.line) - 1
102 step = i.get_named_child (u'tuning-step')
103 step = step.get_text ().strip ()
104 p.step = (ord (step) - ord ('A') + 7 - 2) % 7
106 octave = i.get_named_child (u'tuning-octave')
107 octave = octave.get_text ().strip ()
108 p.octave = int (octave) - 4
110 alter = i.get_named_child (u'tuning-alter')
112 p.alteration = int (alter.get_text ().strip ())
113 # lilypond seems to use the opposite ordering than MusicXML...
119 def staff_attributes_to_lily_staff (mxl_attr):
121 return musicexp.Staff ()
123 (staff_id, attributes) = mxl_attr.items ()[0]
125 # distinguish by clef:
126 # percussion (percussion and rhythmic), tab, and everything else
128 clef = attributes.get_maybe_exist_named_child ('clef')
130 sign = clef.get_maybe_exist_named_child ('sign')
132 clef_sign = {"percussion": "percussion", "TAB": "tab"}.get (sign.get_text (), None)
135 details = attributes.get_maybe_exist_named_child ('staff-details')
137 staff_lines = details.get_maybe_exist_named_child ('staff-lines')
139 lines = string.atoi (staff_lines.get_text ())
142 if clef_sign == "percussion" and lines == 1:
143 staff = musicexp.RhythmicStaff ()
144 elif clef_sign == "percussion":
145 staff = musicexp.DrumStaff ()
146 # staff.drum_style_table = ???
147 elif clef_sign == "tab":
148 staff = musicexp.TabStaff ()
149 staff.string_tunings = staff_attributes_to_string_tunings (attributes)
150 # staff.tablature_format = ???
152 # TODO: Handle case with lines <> 5!
153 staff = musicexp.Staff ()
158 def extract_score_layout (part_list, staffinfo):
159 layout = musicexp.StaffGroup (None)
163 def read_score_part (el):
164 if not isinstance (el, musicxml.Score_part):
166 # Depending on the attributes of the first measure, we create different
167 # types of staves (Staff, RhythmicStaff, DrumStaff, TabStaff, etc.)
168 staff = staff_attributes_to_lily_staff (staffinfo.get (el.id, None))
172 partname = el.get_maybe_exist_named_child ('part-name')
173 # Finale gives unnamed parts the name "MusicXML Part" automatically!
174 if partname and partname.get_text() != "MusicXML Part":
175 staff.instrument_name = partname.get_text ()
176 if el.get_maybe_exist_named_child ('part-abbreviation'):
177 staff.short_instrument_name = el.get_maybe_exist_named_child ('part-abbreviation').get_text ()
178 # TODO: Read in the MIDI device / instrument
181 def read_score_group (el):
182 if not isinstance (el, musicxml.Part_group):
184 group = musicexp.StaffGroup ()
185 if hasattr (el, 'number'):
188 #currentgroups_dict[id] = group
189 #currentgroups.append (id)
190 if el.get_maybe_exist_named_child ('group-name'):
191 group.instrument_name = el.get_maybe_exist_named_child ('group-name').get_text ()
192 if el.get_maybe_exist_named_child ('group-abbreviation'):
193 group.short_instrument_name = el.get_maybe_exist_named_child ('group-abbreviation').get_text ()
194 if el.get_maybe_exist_named_child ('group-symbol'):
195 group.symbol = el.get_maybe_exist_named_child ('group-symbol').get_text ()
196 if el.get_maybe_exist_named_child ('group-barline'):
197 group.spanbar = el.get_maybe_exist_named_child ('group-barline').get_text ()
201 parts_groups = part_list.get_all_children ()
203 # the start/end group tags are not necessarily ordered correctly and groups
204 # might even overlap, so we can't go through the children sequentially!
206 # 1) Replace all Score_part objects by their corresponding Staff objects,
207 # also collect all group start/stop points into one PartGroupInfo object
209 group_info = PartGroupInfo ()
210 for el in parts_groups:
211 if isinstance (el, musicxml.Score_part):
212 if not group_info.is_empty ():
213 staves.append (group_info)
214 group_info = PartGroupInfo ()
215 staff = read_score_part (el)
217 staves.append (staff)
218 elif isinstance (el, musicxml.Part_group):
219 if el.type == "start":
220 group_info.add_start (el)
221 elif el.type == "stop":
222 group_info.add_end (el)
223 if not group_info.is_empty ():
224 staves.append (group_info)
226 # 2) Now, detect the groups:
229 while pos < len (staves):
231 if isinstance (el, PartGroupInfo):
233 if len (group_starts) > 0:
234 prev_start = group_starts[-1]
235 elif len (el.end) > 0: # no group to end here
237 if len (el.end) > 0: # closes an existing group
238 ends = el.end.keys ()
239 prev_started = staves[prev_start].start.keys ()
241 intersection = filter(lambda x:x in ends, prev_started)
242 if len (intersection) > 0:
243 grpid = intersection[0]
245 # Close the last started group
246 grpid = staves[prev_start].start.keys () [0]
247 # Find the corresponding closing tag and remove it!
250 while j < len (staves) and not foundclosing:
251 if isinstance (staves[j], PartGroupInfo) and staves[j].end.has_key (grpid):
253 del staves[j].end[grpid]
254 if staves[j].is_empty ():
257 grpobj = staves[prev_start].start[grpid]
258 group = read_score_group (grpobj)
259 # remove the id from both the start and end
260 if el.end.has_key (grpid):
262 del staves[prev_start].start[grpid]
265 # replace the staves with the whole group
266 for j in staves[(prev_start + 1):pos]:
268 j.stafftype = "InnerStaffGroup"
269 group.append_staff (j)
270 del staves[(prev_start + 1):pos]
271 staves.insert (prev_start + 1, group)
272 # reset pos so that we continue at the correct position
274 # remove an empty start group
275 if staves[prev_start].is_empty ():
276 del staves[prev_start]
277 group_starts.remove (prev_start)
279 elif len (el.start) > 0: # starts new part groups
280 group_starts.append (pos)
283 if len (staves) == 1:
286 layout.append_staff (i)
291 def musicxml_duration_to_lily (mxl_note):
292 d = musicexp.Duration ()
293 # if the note has no Type child, then that method spits out a warning and
294 # returns 0, i.e. a whole note
295 d.duration_log = mxl_note.get_duration_log ()
297 d.dots = len (mxl_note.get_typed_children (musicxml.Dot))
298 # Grace notes by specification have duration 0, so no time modification
299 # factor is possible. It even messes up the output with *0/1
300 if not mxl_note.get_maybe_exist_typed_child (musicxml.Grace):
301 d.factor = mxl_note._duration / d.get_length ()
305 def rational_to_lily_duration (rational_len):
306 d = musicexp.Duration ()
307 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)
308 d.factor = Rational (rational_len.numerator ())
309 if d.duration_log < 0:
310 error_message ("Encountered rational duration with denominator %s, "
311 "unable to convert to lilypond duration" %
312 rational_len.denominator ())
313 # TODO: Test the above error message
318 def musicxml_partial_to_lily (partial_len):
320 p = musicexp.Partial ()
321 p.partial = rational_to_lily_duration (partial_len)
326 # Detect repeats and alternative endings in the chord event list (music_list)
327 # and convert them to the corresponding musicexp objects, containing nested
329 def group_repeats (music_list):
330 repeat_replaced = True
333 # Walk through the list of expressions, looking for repeat structure
334 # (repeat start/end, corresponding endings). If we find one, try to find the
335 # last event of the repeat, replace the whole structure and start over again.
336 # For nested repeats, as soon as we encounter another starting repeat bar,
337 # treat that one first, and start over for the outer repeat.
338 while repeat_replaced and i < 100:
340 repeat_start = -1 # position of repeat start / end
341 repeat_end = -1 # position of repeat start / end
343 ending_start = -1 # position of current ending start
344 endings = [] # list of already finished endings
346 last = len (music_list) - 1
347 repeat_replaced = False
349 while pos < len (music_list) and not repeat_replaced:
351 repeat_finished = False
352 if isinstance (e, RepeatMarker):
353 if not repeat_times and e.times:
354 repeat_times = e.times
355 if e.direction == -1:
357 repeat_finished = True
363 elif e.direction == 1:
369 elif isinstance (e, EndingMarker):
370 if e.direction == -1:
376 elif e.direction == 1:
379 endings.append ([ending_start, pos])
382 elif not isinstance (e, musicexp.BarLine):
383 # As soon as we encounter an element when repeat start and end
384 # is set and we are not inside an alternative ending,
385 # this whole repeat structure is finished => replace it
386 if repeat_start >= 0 and repeat_end > 0 and ending_start < 0:
387 repeat_finished = True
389 # Finish off all repeats without explicit ending bar (e.g. when
390 # we convert only one page of a multi-page score with repeats)
391 if pos == last and repeat_start >= 0:
392 repeat_finished = True
396 if ending_start >= 0:
397 endings.append ([ending_start, pos])
401 # We found the whole structure replace it!
402 r = musicexp.RepeatedMusic ()
403 if repeat_times <= 0:
405 r.repeat_count = repeat_times
406 # don't erase the first element for "implicit" repeats (i.e. no
407 # starting repeat bars at the very beginning)
408 start = repeat_start+1
409 if repeat_start == music_start:
411 r.set_music (music_list[start:repeat_end])
412 for (start, end) in endings:
413 s = musicexp.SequentialMusic ()
414 s.elements = music_list[start+1:end]
416 del music_list[repeat_start:final_marker+1]
417 music_list.insert (repeat_start, r)
418 repeat_replaced = True
420 # TODO: Implement repeats until the end without explicit ending bar
425 def group_tuplets (music_list, events):
428 """Collect Musics from
429 MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
436 for (ev_chord, tuplet_elt, fraction) in events:
437 while (j < len (music_list)):
438 if music_list[j] == ev_chord:
441 if tuplet_elt.type == 'start':
442 indices.append ((j, None, fraction))
443 elif tuplet_elt.type == 'stop':
444 indices[-1] = (indices[-1][0], j, indices[-1][2])
448 for (i1, i2, frac) in indices:
452 new_list.extend (music_list[last:i1])
453 seq = musicexp.SequentialMusic ()
455 seq.elements = music_list[i1:last]
457 tsm = musicexp.TimeScaledMusic ()
460 tsm.numerator = frac[0]
461 tsm.denominator = frac[1]
463 new_list.append (tsm)
465 new_list.extend (music_list[last:])
469 def musicxml_clef_to_lily (attributes):
470 change = musicexp.ClefChange ()
471 (change.type, change.position, change.octave) = attributes.get_clef_information ()
474 def musicxml_time_to_lily (attributes):
475 (beats, type) = attributes.get_time_signature ()
477 change = musicexp.TimeSignatureChange()
478 change.fraction = (beats, type)
482 def musicxml_key_to_lily (attributes):
483 start_pitch = musicexp.Pitch ()
484 (fifths, mode) = attributes.get_key_signature ()
491 start_pitch.alteration = a
493 error_message ('unknown mode %s' % mode)
495 fifth = musicexp.Pitch()
502 for x in range (fifths):
503 start_pitch = start_pitch.transposed (fifth)
505 start_pitch.octave = 0
507 change = musicexp.KeySignatureChange()
509 change.tonic = start_pitch
512 def musicxml_attributes_to_lily (attrs):
515 'clef': musicxml_clef_to_lily,
516 'time': musicxml_time_to_lily,
517 'key': musicxml_key_to_lily
519 for (k, func) in attr_dispatch.items ():
520 children = attrs.get_named_children (k)
522 elts.append (func (attrs))
526 class Marker (musicexp.Music):
530 def print_ly (self, printer):
531 sys.stderr.write ("Encountered unprocessed marker %s\n" % self)
533 def ly_expression (self):
535 class RepeatMarker (Marker):
537 Marker.__init__ (self)
539 class EndingMarker (Marker):
542 # Convert the <barline> element to musicxml.BarLine (for non-standard barlines)
543 # and to RepeatMarker and EndingMarker objects for repeat and
544 # alternatives start/stops
545 def musicxml_barline_to_lily (barline):
546 # retval contains all possible markers in the order:
547 # 0..bw_ending, 1..bw_repeat, 2..barline, 3..fw_repeat, 4..fw_ending
549 bartype_element = barline.get_maybe_exist_named_child ("bar-style")
550 repeat_element = barline.get_maybe_exist_named_child ("repeat")
551 ending_element = barline.get_maybe_exist_named_child ("ending")
555 bartype = bartype_element.get_text ()
557 if repeat_element and hasattr (repeat_element, 'direction'):
558 repeat = RepeatMarker ()
559 repeat.direction = {"forward": -1, "backward": 1}.get (repeat_element.direction, 0)
561 if ( (repeat_element.direction == "forward" and bartype == "heavy-light") or
562 (repeat_element.direction == "backward" and bartype == "light-heavy") ):
564 if hasattr (repeat_element, 'times'):
566 repeat.times = int (repeat_element.times)
569 repeat.event = barline
570 if repeat.direction == -1:
575 if ending_element and hasattr (ending_element, 'type'):
576 ending = EndingMarker ()
577 ending.direction = {"start": -1, "stop": 1, "discontinue": 1}.get (ending_element.type, 0)
578 ending.event = barline
579 if ending.direction == -1:
585 b = musicexp.BarLine ()
589 return retval.values ()
591 spanner_event_dict = {
592 'slur' : musicexp.SlurEvent,
593 'beam' : musicexp.BeamEvent,
594 'glissando' : musicexp.GlissandoEvent,
595 'pedal' : musicexp.PedalEvent,
596 'wavy-line' : musicexp.TrillSpanEvent,
597 'octave-shift' : musicexp.OctaveShiftEvent,
598 'wedge' : musicexp.HairpinEvent
600 spanner_type_dict = {
613 def musicxml_spanner_to_lily_event (mxl_event):
616 name = mxl_event.get_name()
617 func = spanner_event_dict.get (name)
621 error_message ('unknown span event %s' % mxl_event)
624 type = mxl_event.get_type ()
625 span_direction = spanner_type_dict.get (type)
626 # really check for None, because some types will be translated to 0, which
627 # would otherwise also lead to the unknown span warning
628 if span_direction != None:
629 ev.span_direction = span_direction
631 error_message ('unknown span type %s for %s' % (type, name))
633 ev.set_span_type (type)
634 ev.line_type = getattr (mxl_event, 'line-type', 'solid')
636 # assign the size, which is used for octave-shift, etc.
637 ev.size = mxl_event.get_size ()
641 def musicxml_direction_to_indicator (direction):
642 return { "above": 1, "upright": 1, "below": -1, "downright": -1 }.get (direction, '')
644 def musicxml_fermata_to_lily_event (mxl_event):
645 ev = musicexp.ArticulationEvent ()
647 if hasattr (mxl_event, 'type'):
648 dir = musicxml_direction_to_indicator (mxl_event.type)
650 ev.force_direction = dir
654 def musicxml_arpeggiate_to_lily_event (mxl_event):
655 ev = musicexp.ArpeggioEvent ()
656 ev.direction = {"up": 1, "down": -1}.get (getattr (mxl_event, 'direction', None), 0)
660 def musicxml_tremolo_to_lily_event (mxl_event):
661 ev = musicexp.TremoloEvent ()
662 ev.bars = mxl_event.get_text ()
665 def musicxml_bend_to_lily_event (mxl_event):
666 ev = musicexp.BendEvent ()
667 ev.alter = mxl_event.bend_alter ()
671 def musicxml_fingering_event (mxl_event):
672 ev = musicexp.ShortArticulationEvent ()
673 ev.type = mxl_event.get_text ()
676 def musicxml_string_event (mxl_event):
677 ev = musicexp.NoDirectionArticulationEvent ()
678 ev.type = mxl_event.get_text ()
681 def musicxml_accidental_mark (mxl_event):
682 ev = musicexp.MarkupEvent ()
683 contents = { "sharp": "\\sharp",
684 "natural": "\\natural",
686 "double-sharp": "\\doublesharp",
687 "sharp-sharp": "\\sharp\\sharp",
688 "flat-flat": "\\flat\\flat",
689 "flat-flat": "\\doubleflat",
690 "natural-sharp": "\\natural\\sharp",
691 "natural-flat": "\\natural\\flat",
692 "quarter-flat": "\\semiflat",
693 "quarter-sharp": "\\semisharp",
694 "three-quarters-flat": "\\sesquiflat",
695 "three-quarters-sharp": "\\sesquisharp",
696 }.get (mxl_event.get_text ())
698 ev.contents = contents
703 # translate articulations, ornaments and other notations into ArticulationEvents
705 # -) string (ArticulationEvent with that name)
706 # -) function (function(mxl_event) needs to return a full ArticulationEvent-derived object
707 # -) (class, name) (like string, only that a different class than ArticulationEvent is used)
708 # TODO: Some translations are missing!
709 articulations_dict = {
710 "accent": (musicexp.ShortArticulationEvent, ">"), # or "accent"
711 "accidental-mark": musicxml_accidental_mark,
712 "bend": musicxml_bend_to_lily_event,
713 "breath-mark": (musicexp.NoDirectionArticulationEvent, "breathe"),
714 #"caesura": "caesura",
715 #"delayed-turn": "?",
716 "detached-legato": (musicexp.ShortArticulationEvent, "_"), # or "portato"
718 #"double-tongue": "",
719 "down-bow": "downbow",
721 "fingering": musicxml_fingering_event,
725 "harmonic": "flageolet",
727 "inverted-mordent": "prall",
728 "inverted-turn": "reverseturn",
729 "mordent": "mordent",
730 "open-string": "open",
737 #"snap-pizzicato": "",
739 "staccatissimo": (musicexp.ShortArticulationEvent, "|"), # or "staccatissimo"
740 "staccato": (musicexp.ShortArticulationEvent, "."), # or "staccato"
741 "stopped": (musicexp.ShortArticulationEvent, "+"), # or "stopped"
743 "string": musicxml_string_event,
744 "strong-accent": (musicexp.ShortArticulationEvent, "^"), # or "marcato"
746 "tenuto": (musicexp.ShortArticulationEvent, "-"), # or "tenuto"
747 #"thumb-position": "",
750 "tremolo": musicxml_tremolo_to_lily_event,
751 "trill-mark": "trill",
752 #"triple-tongue": "",
757 articulation_spanners = [ "wavy-line" ]
759 def musicxml_articulation_to_lily_event (mxl_event):
760 # wavy-line elements are treated as trill spanners, not as articulation ornaments
761 if mxl_event.get_name () in articulation_spanners:
762 return musicxml_spanner_to_lily_event (mxl_event)
764 tmp_tp = articulations_dict.get (mxl_event.get_name ())
768 if isinstance (tmp_tp, str):
769 ev = musicexp.ArticulationEvent ()
771 elif isinstance (tmp_tp, tuple):
775 ev = tmp_tp (mxl_event)
777 # Some articulations use the type attribute, other the placement...
779 if hasattr (mxl_event, 'type'):
780 dir = musicxml_direction_to_indicator (mxl_event.type)
781 if hasattr (mxl_event, 'placement'):
782 dir = musicxml_direction_to_indicator (mxl_event.placement)
786 def musicxml_dynamics_to_lily_event (dynentry):
787 dynamics_available = ( "p", "pp", "ppp", "pppp", "ppppp", "pppppp",
788 "f", "ff", "fff", "ffff", "fffff", "ffffff",
789 "mp", "mf", "sf", "sfp", "sfpp", "fp",
790 "rf", "rfz", "sfz", "sffz", "fz" )
791 if not dynentry.get_name() in dynamics_available:
793 event = musicexp.DynamicsEvent ()
794 event.type = dynentry.get_name ()
797 # Convert single-color two-byte strings to numbers 0.0 - 1.0
798 def hexcolorval_to_nr (hex_val):
800 v = int (hex_val, 16)
807 def hex_to_color (hex_val):
808 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)
810 return map (lambda x: hexcolorval_to_nr (x), res.group (2,3,4))
814 def musicxml_words_to_lily_event (words):
815 event = musicexp.TextEvent ()
816 text = words.get_text ()
817 text = re.sub ('^ *\n? *', '', text)
818 text = re.sub (' *\n? *$', '', text)
821 if hasattr (words, 'default-y'):
822 offset = getattr (words, 'default-y')
824 off = string.atoi (offset)
826 event.force_direction = 1
828 event.force_direction = -1
830 event.force_direction = 0
832 if hasattr (words, 'font-weight'):
833 font_weight = { "normal": '', "bold": '\\bold' }.get (getattr (words, 'font-weight'), '')
835 event.markup += font_weight
837 if hasattr (words, 'font-size'):
838 size = getattr (words, 'font-size')
840 "xx-small": '\\teeny',
846 "xx-large": '\\bigger\\huge'
849 event.markup += font_size
851 if hasattr (words, 'color'):
852 color = getattr (words, 'color')
853 rgb = hex_to_color (color)
855 event.markup += "\\with-color #(rgb-color %s %s %s)" % (rgb[0], rgb[1], rgb[2])
857 if hasattr (words, 'font-style'):
858 font_style = { "italic": '\\italic' }.get (getattr (words, 'font-style'), '')
860 event.markup += font_style
862 # TODO: How should I best convert the font-family attribute?
864 # TODO: How can I represent the underline, overline and line-through
865 # attributes in Lilypond? Values of these attributes indicate
866 # the number of lines
871 direction_spanners = [ 'octave-shift', 'pedal', 'wedge' ]
873 def musicxml_direction_to_lily (n):
874 # TODO: Handle the <staff> element!
876 dirtype_children = []
877 for dt in n.get_typed_children (musicxml.DirType):
878 dirtype_children += dt.get_all_children ()
880 for entry in dirtype_children:
882 if entry.get_name () == "dynamics":
883 for dynentry in entry.get_all_children ():
884 ev = musicxml_dynamics_to_lily_event (dynentry)
888 if entry.get_name () == "words":
889 ev = musicxml_words_to_lily_event (entry)
893 # octave shifts. pedal marks, hairpins etc. are spanners:
894 if entry.get_name() in direction_spanners:
895 event = musicxml_spanner_to_lily_event (entry)
902 def musicxml_frame_to_lily_event (frame):
903 ev = musicexp.FretEvent ()
904 ev.strings = frame.get_strings ()
905 ev.frets = frame.get_frets ()
906 #offset = frame.get_first_fret () - 1
908 for fn in frame.get_named_children ('frame-note'):
909 fret = fn.get_fret ()
912 el = [ fn.get_string (), fret ]
913 fingering = fn.get_fingering ()
915 el.append (fingering)
916 ev.elements.append (el)
919 barre[0] = el[0] # start string
920 barre[2] = el[1] # fret
922 barre[1] = el[0] # end string
927 def musicxml_harmony_to_lily (n):
929 for f in n.get_named_children ('frame'):
930 ev = musicxml_frame_to_lily_event (f)
936 instrument_drumtype_dict = {
937 'Acoustic Snare Drum': 'acousticsnare',
938 'Side Stick': 'sidestick',
939 'Open Triangle': 'opentriangle',
940 'Mute Triangle': 'mutetriangle',
941 'Tambourine': 'tambourine',
942 'Bass Drum': 'bassdrum',
945 def musicxml_note_to_lily_main_event (n):
949 mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
952 pitch = musicxml_pitch_to_lily (mxl_pitch)
953 event = musicexp.NoteEvent()
956 acc = n.get_maybe_exist_named_child ('accidental')
958 # let's not force accs everywhere.
959 event.cautionary = acc.editorial
961 elif n.get_maybe_exist_typed_child (musicxml.Rest):
962 # rests can have display-octave and display-step, which are
963 # treated like an ordinary note pitch
964 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
965 event = musicexp.RestEvent()
966 pitch = musicxml_restdisplay_to_lily (rest)
968 elif n.instrument_name:
969 event = musicexp.NoteEvent ()
970 drum_type = instrument_drumtype_dict.get (n.instrument_name)
972 event.drum_type = drum_type
974 n.message ("drum %s type unknown, please add to instrument_drumtype_dict" % n.instrument_name)
975 event.drum_type = 'acousticsnare'
978 n.message ("cannot find suitable event")
980 event.duration = musicxml_duration_to_lily (n)
986 def __init__ (self, here, dest):
990 class LilyPondVoiceBuilder:
993 self.pending_dynamics = []
994 self.end_moment = Rational (0)
995 self.begin_moment = Rational (0)
996 self.pending_multibar = Rational (0)
997 self.ignore_skips = False
999 def _insert_multibar (self):
1000 r = musicexp.MultiMeasureRest ()
1001 r.duration = musicexp.Duration()
1002 r.duration.duration_log = 0
1003 r.duration.factor = self.pending_multibar
1004 self.elements.append (r)
1005 self.begin_moment = self.end_moment
1006 self.end_moment = self.begin_moment + self.pending_multibar
1007 self.pending_multibar = Rational (0)
1009 def add_multibar_rest (self, duration):
1010 self.pending_multibar += duration
1012 def set_duration (self, duration):
1013 self.end_moment = self.begin_moment + duration
1014 def current_duration (self):
1015 return self.end_moment - self.begin_moment
1017 def add_music (self, music, duration):
1018 assert isinstance (music, musicexp.Music)
1019 if self.pending_multibar > Rational (0):
1020 self._insert_multibar ()
1022 self.elements.append (music)
1023 self.begin_moment = self.end_moment
1024 self.set_duration (duration)
1026 # Insert all pending dynamics right after the note/rest:
1027 if isinstance (music, musicexp.EventChord) and self.pending_dynamics:
1028 for d in self.pending_dynamics:
1030 self.pending_dynamics = []
1032 # Insert some music command that does not affect the position in the measure
1033 def add_command (self, command):
1034 assert isinstance (command, musicexp.Music)
1035 if self.pending_multibar > Rational (0):
1036 self._insert_multibar ()
1037 self.elements.append (command)
1038 def add_barline (self, barline):
1039 # TODO: Implement merging of default barline and custom bar line
1040 self.add_music (barline, Rational (0))
1041 def add_partial (self, command):
1042 self.ignore_skips = True
1043 self.add_command (command)
1045 def add_dynamics (self, dynamic):
1046 # store the dynamic item(s) until we encounter the next note/rest:
1047 self.pending_dynamics.append (dynamic)
1049 def add_bar_check (self, number):
1050 b = musicexp.BarLine ()
1051 b.bar_number = number
1052 self.add_barline (b)
1054 def jumpto (self, moment):
1055 current_end = self.end_moment + self.pending_multibar
1056 diff = moment - current_end
1058 if diff < Rational (0):
1059 error_message ('Negative skip %s' % diff)
1062 if diff > Rational (0) and not (self.ignore_skips and moment == 0):
1063 skip = musicexp.SkipEvent()
1064 skip.duration.duration_log = 0
1065 skip.duration.factor = diff
1067 evc = musicexp.EventChord ()
1068 evc.elements.append (skip)
1069 self.add_music (evc, diff)
1071 if diff > Rational (0) and moment == 0:
1072 self.ignore_skips = False
1074 def last_event_chord (self, starting_at):
1078 # if the position matches, find the last EventChord, do not cross a bar line!
1079 at = len( self.elements ) - 1
1081 not isinstance (self.elements[at], musicexp.EventChord) and
1082 not isinstance (self.elements[at], musicexp.BarLine)):
1087 and isinstance (self.elements[at], musicexp.EventChord)
1088 and self.begin_moment == starting_at):
1089 value = self.elements[at]
1091 self.jumpto (starting_at)
1095 def correct_negative_skip (self, goto):
1096 self.end_moment = goto
1097 self.begin_moment = goto
1098 evc = musicexp.EventChord ()
1099 self.elements.append (evc)
1103 def __init__ (self):
1104 self.voicedata = None
1105 self.ly_voice = None
1106 self.lyrics_dict = {}
1107 self.lyrics_order = []
1109 def musicxml_voice_to_lily_voice (voice):
1113 return_value = VoiceData ()
1114 return_value.voicedata = voice
1116 # Needed for melismata detection (ignore lyrics on those notes!):
1120 ignore_lyrics = False
1122 current_staff = None
1124 # Make sure that the keys in the dict don't get reordered, since
1125 # we need the correct ordering of the lyrics stanzas! By default,
1126 # a dict will reorder its keys
1127 return_value.lyrics_order = voice.get_lyrics_numbers ()
1128 for k in return_value.lyrics_order:
1131 voice_builder = LilyPondVoiceBuilder()
1133 for n in voice._elements:
1134 if n.get_name () == 'forward':
1136 staff = n.get_maybe_exist_named_child ('staff')
1138 staff = staff.get_text ()
1139 if current_staff and staff <> current_staff and not n.get_maybe_exist_named_child ('chord'):
1140 voice_builder.add_command (musicexp.StaffChange (staff))
1141 current_staff = staff
1143 if isinstance (n, musicxml.Partial) and n.partial > 0:
1144 a = musicxml_partial_to_lily (n.partial)
1146 voice_builder.add_partial (a)
1149 if isinstance (n, musicxml.Direction):
1150 for a in musicxml_direction_to_lily (n):
1151 if a.wait_for_note ():
1152 voice_builder.add_dynamics (a)
1154 voice_builder.add_command (a)
1157 if isinstance (n, musicxml.Harmony):
1158 for a in musicxml_harmony_to_lily (n):
1159 if a.wait_for_note ():
1160 voice_builder.add_dynamics (a)
1162 voice_builder.add_command (a)
1165 is_chord = n.get_maybe_exist_named_child ('chord')
1168 voice_builder.jumpto (n._when)
1169 except NegativeSkip, neg:
1170 voice_builder.correct_negative_skip (n._when)
1171 n.message ("Negative skip? from %s to %s, diff %s" % (neg.here, neg.dest, neg.dest - neg.here))
1173 if isinstance (n, musicxml.Attributes):
1174 if n.is_first () and n._measure_position == Rational (0):
1176 number = int (n.get_parent ().number)
1180 voice_builder.add_bar_check (number)
1182 for a in musicxml_attributes_to_lily (n):
1183 voice_builder.add_command (a)
1186 if isinstance (n, musicxml.Barline):
1187 barlines = musicxml_barline_to_lily (n)
1189 if isinstance (a, musicexp.BarLine):
1190 voice_builder.add_barline (a)
1191 elif isinstance (a, RepeatMarker) or isinstance (a, EndingMarker):
1192 voice_builder.add_command (a)
1195 if not n.__class__.__name__ == 'Note':
1196 error_message ('not a Note or Attributes? %s' % n)
1199 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
1201 and rest.is_whole_measure ()):
1203 voice_builder.add_multibar_rest (n._duration)
1206 if n.is_first () and n._measure_position == Rational (0):
1208 num = int (n.get_parent ().number)
1212 voice_builder.add_bar_check (num)
1214 main_event = musicxml_note_to_lily_main_event (n)
1215 ignore_lyrics = inside_slur or is_tied or is_chord
1217 if hasattr (main_event, 'drum_type') and main_event.drum_type:
1218 modes_found['drummode'] = True
1221 ev_chord = voice_builder.last_event_chord (n._when)
1223 ev_chord = musicexp.EventChord()
1224 voice_builder.add_music (ev_chord, n._duration)
1226 grace = n.get_maybe_exist_typed_child (musicxml.Grace)
1229 if n.get_maybe_exist_typed_child (musicxml.Chord) and ev_chord.grace_elements:
1230 grace_chord = ev_chord.grace_elements.get_last_event_chord ()
1232 grace_chord = musicexp.EventChord ()
1233 ev_chord.append_grace (grace_chord)
1234 if hasattr (grace, 'slash'):
1235 # TODO: use grace_type = "appoggiatura" for slurred grace notes
1236 if grace.slash == "yes":
1237 ev_chord.grace_type = "acciaccatura"
1238 elif grace.slash == "no":
1239 ev_chord.grace_type = "grace"
1240 # now that we have inserted the chord into the grace music, insert
1241 # everything into that chord instead of the ev_chord
1242 ev_chord = grace_chord
1243 ev_chord.append (main_event)
1244 ignore_lyrics = True
1246 ev_chord.append (main_event)
1247 # When a note/chord has grace notes (duration==0), the duration of the
1248 # event chord is not yet known, but the event chord was already added
1249 # with duration 0. The following correct this when we hit the real note!
1250 if voice_builder.current_duration () == 0 and n._duration > 0:
1251 voice_builder.set_duration (n._duration)
1253 notations_children = n.get_typed_children (musicxml.Notations)
1257 # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
1258 # +tied | +slur | +tuplet | glissando | slide |
1259 # ornaments | technical | articulations | dynamics |
1260 # +fermata | arpeggiate | non-arpeggiate |
1261 # accidental-mark | other-notation
1262 for notations in notations_children:
1263 if notations.get_tuplet():
1264 tuplet_event = notations.get_tuplet()
1265 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
1268 frac = mod.get_fraction ()
1270 tuplet_events.append ((ev_chord, tuplet_event, frac))
1272 slurs = [s for s in notations.get_named_children ('slur')
1273 if s.get_type () in ('start','stop')]
1276 error_message ('more than 1 slur?')
1277 # record the slur status for the next note in the loop
1279 if slurs[0].get_type () == 'start':
1281 elif slurs[0].get_type () == 'stop':
1283 lily_ev = musicxml_spanner_to_lily_event (slurs[0])
1284 ev_chord.append (lily_ev)
1287 mxl_tie = notations.get_tie ()
1288 if mxl_tie and mxl_tie.type == 'start':
1289 ev_chord.append (musicexp.TieEvent ())
1294 fermatas = notations.get_named_children ('fermata')
1296 ev = musicxml_fermata_to_lily_event (a)
1298 ev_chord.append (ev)
1300 arpeggiate = notations.get_named_children ('arpeggiate')
1301 for a in arpeggiate:
1302 ev = musicxml_arpeggiate_to_lily_event (a)
1304 ev_chord.append (ev)
1306 glissandos = notations.get_named_children ('glissando')
1307 for a in glissandos:
1308 ev = musicxml_spanner_to_lily_event (a)
1310 ev_chord.append (ev)
1312 # Articulations can contain the following child elements:
1313 # accent | strong-accent | staccato | tenuto |
1314 # detached-legato | staccatissimo | spiccato |
1315 # scoop | plop | doit | falloff | breath-mark |
1316 # caesura | stress | unstress
1317 # Technical can contain the following child elements:
1318 # up-bow | down-bow | harmonic | open-string |
1319 # thumb-position | fingering | pluck | double-tongue |
1320 # triple-tongue | stopped | snap-pizzicato | fret |
1321 # string | hammer-on | pull-off | bend | tap | heel |
1322 # toe | fingernails | other-technical
1323 # Ornaments can contain the following child elements:
1324 # trill-mark | turn | delayed-turn | inverted-turn |
1325 # shake | wavy-line | mordent | inverted-mordent |
1326 # schleifer | tremolo | other-ornament, accidental-mark
1327 ornaments = notations.get_named_children ('ornaments')
1329 for ch in a.get_named_children ('tremolo'):
1330 ev = musicxml_tremolo_to_lily_event (ch)
1332 ev_chord.append (ev)
1334 ornaments += notations.get_named_children ('articulations')
1335 ornaments += notations.get_named_children ('technical')
1338 for ch in a.get_all_children ():
1339 ev = musicxml_articulation_to_lily_event (ch)
1341 ev_chord.append (ev)
1343 dynamics = notations.get_named_children ('dynamics')
1345 for ch in a.get_all_children ():
1346 ev = musicxml_dynamics_to_lily_event (ch)
1348 ev_chord.append (ev)
1350 # Extract the lyrics
1351 if not rest and not ignore_lyrics:
1352 note_lyrics_processed = []
1353 note_lyrics_elements = n.get_typed_children (musicxml.Lyric)
1354 for l in note_lyrics_elements:
1355 if l.get_number () < 0:
1356 for k in lyrics.keys ():
1357 lyrics[k].append (l.lyric_to_text ())
1358 note_lyrics_processed.append (k)
1360 lyrics[l.number].append(l.lyric_to_text ())
1361 note_lyrics_processed.append (l.number)
1362 for lnr in lyrics.keys ():
1363 if not lnr in note_lyrics_processed:
1364 lyrics[lnr].append ("\skip4")
1367 mxl_beams = [b for b in n.get_named_children ('beam')
1368 if (b.get_type () in ('begin', 'end')
1369 and b.is_primary ())]
1371 beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
1373 ev_chord.append (beam_ev)
1376 mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
1379 frac = mod.get_fraction ()
1381 tuplet_events.append ((ev_chord, tuplet_event, frac))
1383 ## force trailing mm rests to be written out.
1384 voice_builder.add_music (musicexp.EventChord (), Rational (0))
1386 ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
1387 ly_voice = group_repeats (ly_voice)
1389 seq_music = musicexp.SequentialMusic ()
1391 if 'drummode' in modes_found.keys ():
1392 ## \key <pitch> barfs in drummode.
1393 ly_voice = [e for e in ly_voice
1394 if not isinstance(e, musicexp.KeySignatureChange)]
1396 seq_music.elements = ly_voice
1397 for k in lyrics.keys ():
1398 return_value.lyrics_dict[k] = musicexp.Lyrics ()
1399 return_value.lyrics_dict[k].lyrics_syllables = lyrics[k]
1402 if len (modes_found) > 1:
1403 error_message ('Too many modes found %s' % modes_found.keys ())
1405 return_value.ly_voice = seq_music
1406 for mode in modes_found.keys ():
1407 v = musicexp.ModeChangingMusicWrapper()
1408 v.element = seq_music
1410 return_value.ly_voice = v
1415 def musicxml_id_to_lily (id):
1416 digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five',
1417 'Six', 'Seven', 'Eight', 'Nine', 'Ten']
1419 for digit in digits:
1420 d = digits.index (digit)
1421 id = re.sub ('%d' % d, digit, id)
1423 id = re.sub ('[^a-zA-Z]', 'X', id)
1427 def musicxml_pitch_to_lily (mxl_pitch):
1428 p = musicexp.Pitch()
1429 p.alteration = mxl_pitch.get_alteration ()
1430 p.step = (ord (mxl_pitch.get_step ()) - ord ('A') + 7 - 2) % 7
1431 p.octave = mxl_pitch.get_octave () - 4
1434 def musicxml_restdisplay_to_lily (mxl_rest):
1436 step = mxl_rest.get_step ()
1438 p = musicexp.Pitch()
1439 p.step = (ord (step) - ord ('A') + 7 - 2) % 7
1440 octave = mxl_rest.get_octave ()
1442 p.octave = octave - 4
1445 def voices_in_part (part):
1446 """Return a Name -> Voice dictionary for PART"""
1448 part.extract_voices ()
1449 voices = part.get_voices ()
1450 part_info = part.get_staff_attributes ()
1452 return (voices, part_info)
1454 def voices_in_part_in_parts (parts):
1455 """return a Part -> Name -> Voice dictionary"""
1456 return dict([(p.id, voices_in_part (p)) for p in parts])
1459 def get_all_voices (parts):
1460 all_voices = voices_in_part_in_parts (parts)
1463 all_ly_staffinfo = {}
1464 for p, (name_voice, staff_info) in all_voices.items ():
1467 for n, v in name_voice.items ():
1468 progress ("Converting to LilyPond expressions...")
1469 # musicxml_voice_to_lily_voice returns (lily_voice, {nr->lyrics, nr->lyrics})
1470 part_ly_voices[n] = musicxml_voice_to_lily_voice (v)
1472 all_ly_voices[p] = part_ly_voices
1473 all_ly_staffinfo[p] = staff_info
1475 return (all_ly_voices, all_ly_staffinfo)
1478 def option_parser ():
1479 p = ly.get_option_parser(usage=_ ("musicxml2ly FILE.xml"),
1480 version=('''%prog (LilyPond) @TOPLEVEL_VERSION@\n\n'''
1482 _ ("""This program is free software. It is covered by the GNU General Public
1483 License and you are welcome to change it and/or distribute copies of it
1484 under certain conditions. Invoke as `%s --warranty' for more
1485 information.""") % 'lilypond'
1487 Copyright (c) 2005--2007 by
1488 Han-Wen Nienhuys <hanwen@xs4all.nl> and
1489 Jan Nieuwenhuizen <janneke@gnu.org>
1491 description=_ ("Convert %s to LilyPond input.") % 'MusicXML' + "\n")
1492 p.add_option ('-v', '--verbose',
1493 action="store_true",
1495 help=_ ("be verbose"))
1497 p.add_option ('', '--lxml',
1498 action="store_true",
1501 help=_ ("Use lxml.etree; uses less memory and cpu time."))
1503 p.add_option ('-o', '--output',
1509 help=_ ("set output filename to FILE"))
1510 p.add_option_group ('bugs',
1511 description=(_ ("Report bugs via")
1512 + ''' http://post.gmane.org/post.php'''
1513 '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
1516 def music_xml_voice_name_to_lily_name (part_id, name):
1517 str = "Part%sVoice%s" % (part_id, name)
1518 return musicxml_id_to_lily (str)
1520 def music_xml_lyrics_name_to_lily_name (part_id, name, lyricsnr):
1521 str = "Part%sVoice%sLyrics%s" % (part_id, name, lyricsnr)
1522 return musicxml_id_to_lily (str)
1524 def print_voice_definitions (printer, part_list, voices):
1525 for part in part_list:
1527 nv_dict = voices.get (part_id, {})
1528 for (name, voice) in nv_dict.items ():
1529 k = music_xml_voice_name_to_lily_name (part_id, name)
1530 printer.dump ('%s = ' % k)
1531 voice.ly_voice.print_ly (printer)
1533 for l in voice.lyrics_order:
1534 lname = music_xml_lyrics_name_to_lily_name (part_id, name, l)
1535 printer.dump ('%s = ' %lname )
1536 voice.lyrics_dict[l].print_ly (printer)
1541 return dict ([(elt,1) for elt in l]).keys ()
1543 # format the information about the staff in the form
1546 # [voiceid1, [lyricsid11, lyricsid12,...] ...],
1547 # [voiceid2, [lyricsid21, lyricsid22,...] ...],
1551 # raw_voices is of the form [(voicename, lyricsids)*]
1552 def format_staff_info (part_id, staff_id, raw_voices):
1554 for (v, lyricsids) in raw_voices:
1555 voice_name = music_xml_voice_name_to_lily_name (part_id, v)
1556 voice_lyrics = [music_xml_lyrics_name_to_lily_name (part_id, v, l)
1558 voices.append ([voice_name, voice_lyrics])
1559 return [staff_id, voices]
1561 def update_score_setup (score_structure, part_list, voices):
1563 for part_definition in part_list:
1564 part_id = part_definition.id
1565 nv_dict = voices.get (part_id)
1567 error_message ('unknown part in part-list: %s' % part_id)
1570 staves = reduce (lambda x,y: x+ y,
1571 [voice.voicedata._staves.keys ()
1572 for voice in nv_dict.values ()],
1575 if len (staves) > 1:
1577 staves = uniq_list (staves)
1580 thisstaff_raw_voices = [(voice_name, voice.lyrics_order)
1581 for (voice_name, voice) in nv_dict.items ()
1582 if voice.voicedata._start_staff == s]
1583 staves_info.append (format_staff_info (part_id, s, thisstaff_raw_voices))
1585 thisstaff_raw_voices = [(voice_name, voice.lyrics_order)
1586 for (voice_name, voice) in nv_dict.items ()]
1587 staves_info.append (format_staff_info (part_id, None, thisstaff_raw_voices))
1588 score_structure.set_part_information (part_id, staves_info)
1590 def print_ly_preamble (printer, filename):
1591 printer.dump_version ()
1592 printer.print_verbatim ('%% automatically converted from %s\n' % filename)
1594 def read_musicxml (filename, use_lxml):
1598 tree = lxml.etree.parse (filename)
1599 mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
1602 from xml.dom import minidom, Node
1604 doc = minidom.parse(filename)
1605 node = doc.documentElement
1606 return musicxml.minidom_demarshal_node (node)
1611 def convert (filename, options):
1612 progress ("Reading MusicXML from %s ..." % filename)
1614 tree = read_musicxml (filename, options.use_lxml)
1615 parts = tree.get_typed_children (musicxml.Part)
1616 (voices, staff_info) = get_all_voices (parts)
1618 score_structure = None
1619 mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
1621 score_structure = extract_score_layout (mxl_pl, staff_info)
1622 part_list = mxl_pl.get_named_children ("score-part")
1624 # score information is contained in the <work>, <identification> or <movement-title> tags
1625 score_information = extract_score_information (tree)
1626 update_score_setup (score_structure, part_list, voices)
1628 if not options.output_name:
1629 options.output_name = os.path.basename (filename)
1630 options.output_name = os.path.splitext (options.output_name)[0]
1631 elif re.match (".*\.ly", options.output_name):
1632 options.output_name = os.path.splitext (options.output_name)[0]
1635 defs_ly_name = options.output_name + '-defs.ly'
1636 driver_ly_name = options.output_name + '.ly'
1638 printer = musicexp.Output_printer()
1639 progress ("Output to `%s'" % defs_ly_name)
1640 printer.set_file (codecs.open (defs_ly_name, 'wb', encoding='utf-8'))
1642 print_ly_preamble (printer, filename)
1643 score_information.print_ly (printer)
1644 print_voice_definitions (printer, part_list, voices)
1649 progress ("Output to `%s'" % driver_ly_name)
1650 printer = musicexp.Output_printer()
1651 printer.set_file (codecs.open (driver_ly_name, 'wb', encoding='utf-8'))
1652 print_ly_preamble (printer, filename)
1653 printer.dump (r'\include "%s"' % os.path.basename (defs_ly_name))
1654 score_structure.print_ly (printer)
1659 def get_existing_filename_with_extension (filename, ext):
1660 if os.path.exists (filename):
1662 newfilename = filename + ".xml"
1663 if os.path.exists (newfilename):
1665 newfilename = filename + "xml"
1666 if os.path.exists (newfilename):
1671 opt_parser = option_parser()
1673 (options, args) = opt_parser.parse_args ()
1675 opt_parser.print_usage()
1678 # Allow the user to leave out the .xml or xml on the filename
1679 filename = get_existing_filename_with_extension (args[0], "xml")
1680 if filename and os.path.exists (filename):
1681 voices = convert (filename, options)
1683 progress ("Unable to find input file %s" % args[0])
1685 if __name__ == '__main__':