Easy heads: only access 'note-names vector if length > pitch-notename.
[lilypond/mpolesky.git] / scripts / musicxml2ly.py
bloba19c2fc8807eb516094d60a9c292947712cadf20
1 #!@TARGET_PYTHON@
2 # -*- coding: utf-8 -*-
3 import optparse
4 import sys
5 import re
6 import os
7 import string
8 import codecs
9 import zipfile
10 import StringIO
12 """
13 @relocate-preamble@
14 """
16 import lilylib as ly
17 _ = ly._
19 import musicxml
20 import musicexp
22 from rational import Rational
24 # Store command-line options in a global variable, so we can access them everythwere
25 options = None
27 class Conversion_Settings:
28 def __init__(self):
29 self.ignore_beaming = False
31 conversion_settings = Conversion_Settings ()
32 # Use a global variable to store the setting needed inside a \layout block.
33 # whenever we need to change a setting or add/remove an engraver, we can access
34 # this layout and add the corresponding settings
35 layout_information = musicexp.Layout ()
37 def progress (str):
38 ly.stderr_write (str + '\n')
39 sys.stderr.flush ()
41 def error_message (str):
42 ly.stderr_write (str + '\n')
43 sys.stderr.flush ()
45 needed_additional_definitions = []
46 additional_definitions = {
48 "tuplet-note-wrapper": """ % a formatter function, which is simply a wrapper around an existing
49 % tuplet formatter function. It takes the value returned by the given
50 % function and appends a note of given length.
51 #(define-public ((tuplet-number::append-note-wrapper function note) grob)
52 (let* ((txt (if function (function grob) #f)))
53 (if txt
54 (markup txt #:fontsize -5 #:note note UP)
55 (markup #:fontsize -5 #:note note UP)
58 )""",
60 "tuplet-non-default-denominator": """#(define ((tuplet-number::non-default-tuplet-denominator-text denominator) grob)
61 (number->string (if denominator
62 denominator
63 (ly:event-property (event-cause grob) 'denominator))))
64 """,
66 "tuplet-non-default-fraction": """#(define ((tuplet-number::non-default-tuplet-fraction-text denominator numerator) grob)
67 (let* ((ev (event-cause grob))
68 (den (if denominator denominator (ly:event-property ev 'denominator)))
69 (num (if numerator numerator (ly:event-property ev 'numerator))))
70 (format "~a:~a" den num)))
71 """,
73 "compound-time-signature": """%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
74 % Formatting of (possibly complex) compound time signatures
75 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
77 #(define-public (insert-markups l m)
78 (let* ((ll (reverse l)))
79 (let join-markups ((markups (list (car ll)))
80 (remaining (cdr ll)))
81 (if (pair? remaining)
82 (join-markups (cons (car remaining) (cons m markups)) (cdr remaining))
83 markups))))
85 % Use a centered-column inside a left-column, because the centered column
86 % moves its reference point to the center, which the left-column undoes.
87 % The center-column also aligns its contented centered, which is not undone...
88 #(define-public (format-time-fraction time-sig-fraction)
89 (let* ((revargs (reverse (map number->string time-sig-fraction)))
90 (den (car revargs))
91 (nums (reverse (cdr revargs))))
92 (make-override-markup '(baseline-skip . 0)
93 (make-number-markup
94 (make-left-column-markup (list
95 (make-center-column-markup (list
96 (make-line-markup (insert-markups nums "+"))
97 den))))))))
99 #(define-public (format-complex-compound-time time-sig)
100 (let* ((sigs (map format-time-fraction time-sig)))
101 (make-override-markup '(baseline-skip . 0)
102 (make-number-markup
103 (make-line-markup
104 (insert-markups sigs (make-vcenter-markup "+")))))))
106 #(define-public (format-compound-time time-sig)
107 (cond
108 ((not (pair? time-sig)) (null-markup))
109 ((pair? (car time-sig)) (format-complex-compound-time time-sig))
110 (else (format-time-fraction time-sig))))
113 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
114 % Measure length calculation of (possibly complex) compound time signatures
115 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
117 #(define-public (calculate-time-fraction time-sig-fraction)
118 (let* ((revargs (reverse time-sig-fraction))
119 (den (car revargs))
120 (nums (cdr revargs)))
121 (ly:make-moment (apply + nums) den)))
123 #(define-public (calculate-complex-compound-time time-sig)
124 (let* ((sigs (map calculate-time-fraction time-sig)))
125 (let add-moment ((moment ZERO-MOMENT)
126 (remaining sigs))
127 (if (pair? remaining)
128 (add-moment (ly:moment-add moment (car remaining)) (cdr remaining))
129 moment))))
131 #(define-public (calculate-compound-measure-length time-sig)
132 (cond
133 ((not (pair? time-sig)) (ly:make-moment 4 4))
134 ((pair? (car time-sig)) (calculate-complex-compound-time time-sig))
135 (else (calculate-time-fraction time-sig))))
138 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
139 % Base beat lenth
140 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
142 #(define-public (calculate-compound-base-beat-full time-sig)
143 (let* ((den (map last time-sig)))
144 (apply max den)))
146 #(define-public (calculate-compound-base-beat time-sig)
147 (ly:make-moment 1 (cond
148 ((not (pair? time-sig)) 4)
149 ((pair? (car time-sig)) (calculate-compound-base-beat-full time-sig))
150 (else (calculate-compound-base-beat-full (list time-sig))))))
153 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
154 % The music function to set the complex time signature
155 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
157 compoundMeter =
158 #(define-music-function (parser location args) (pair?)
159 (let ((mlen (calculate-compound-measure-length args))
160 (beat (calculate-compound-base-beat args)))
162 \once \override Staff.TimeSignature #'stencil = #ly:text-interface::print
163 \once \override Staff.TimeSignature #'text = #(format-compound-time $args)
164 % \set Staff.beatGrouping = #(reverse (cdr (reverse $args)))
165 \set Timing.measureLength = $mlen
166 \set Timing.timeSignatureFraction = #(cons (ly:moment-main-numerator $mlen)
167 (ly:moment-main-denominator $mlen))
168 \set Timing.beatLength = $beat
170 % TODO: Implement beatGrouping and auto-beam-settings!!!
171 #} ))
175 def round_to_two_digits (val):
176 return round (val * 100) / 100
178 def extract_paper_information (tree):
179 paper = musicexp.Paper ()
180 defaults = tree.get_maybe_exist_named_child ('defaults')
181 if not defaults:
182 return None
183 tenths = -1
184 scaling = defaults.get_maybe_exist_named_child ('scaling')
185 if scaling:
186 mm = scaling.get_named_child ('millimeters')
187 mm = string.atof (mm.get_text ())
188 tn = scaling.get_maybe_exist_named_child ('tenths')
189 tn = string.atof (tn.get_text ())
190 tenths = mm / tn
191 paper.global_staff_size = mm * 72.27 / 25.4
192 # We need the scaling (i.e. the size of staff tenths for everything!
193 if tenths < 0:
194 return None
196 def from_tenths (txt):
197 return round_to_two_digits (string.atof (txt) * tenths / 10)
198 def set_paper_variable (varname, parent, element_name):
199 el = parent.get_maybe_exist_named_child (element_name)
200 if el: # Convert to cm from tenths
201 setattr (paper, varname, from_tenths (el.get_text ()))
203 pagelayout = defaults.get_maybe_exist_named_child ('page-layout')
204 if pagelayout:
205 # TODO: How can one have different margins for even and odd pages???
206 set_paper_variable ("page_height", pagelayout, 'page-height')
207 set_paper_variable ("page_width", pagelayout, 'page-width')
209 pmargins = pagelayout.get_named_children ('page-margins')
210 for pm in pmargins:
211 set_paper_variable ("left_margin", pm, 'left-margin')
212 set_paper_variable ("right_margin", pm, 'right-margin')
213 set_paper_variable ("bottom_margin", pm, 'bottom-margin')
214 set_paper_variable ("top_margin", pm, 'top-margin')
216 systemlayout = defaults.get_maybe_exist_named_child ('system-layout')
217 if systemlayout:
218 sl = systemlayout.get_maybe_exist_named_child ('system-margins')
219 if sl:
220 set_paper_variable ("system_left_margin", sl, 'left-margin')
221 set_paper_variable ("system_right_margin", sl, 'right-margin')
222 set_paper_variable ("system_distance", systemlayout, 'system-distance')
223 set_paper_variable ("top_system_distance", systemlayout, 'top-system-distance')
225 stafflayout = defaults.get_named_children ('staff-layout')
226 for sl in stafflayout:
227 nr = getattr (sl, 'number', 1)
228 dist = sl.get_named_child ('staff-distance')
229 #TODO: the staff distance needs to be set in the Staff context!!!
231 # TODO: Finish appearance?, music-font?, word-font?, lyric-font*, lyric-language*
232 appearance = defaults.get_named_child ('appearance')
233 if appearance:
234 lws = appearance.get_named_children ('line-width')
235 for lw in lws:
236 # Possible types are: beam, bracket, dashes,
237 # enclosure, ending, extend, heavy barline, leger,
238 # light barline, octave shift, pedal, slur middle, slur tip,
239 # staff, stem, tie middle, tie tip, tuplet bracket, and wedge
240 tp = lw.type
241 w = from_tenths (lw.get_text ())
242 # TODO: Do something with these values!
243 nss = appearance.get_named_children ('note-size')
244 for ns in nss:
245 # Possible types are: cue, grace and large
246 tp = ns.type
247 sz = from_tenths (ns.get_text ())
248 # TODO: Do something with these values!
249 # <other-appearance> elements have no specified meaning
251 rawmusicfont = defaults.get_named_child ('music-font')
252 if rawmusicfont:
253 # TODO: Convert the font
254 pass
255 rawwordfont = defaults.get_named_child ('word-font')
256 if rawwordfont:
257 # TODO: Convert the font
258 pass
259 rawlyricsfonts = defaults.get_named_children ('lyric-font')
260 for lyricsfont in rawlyricsfonts:
261 # TODO: Convert the font
262 pass
264 return paper
268 # score information is contained in the <work>, <identification> or <movement-title> tags
269 # extract those into a hash, indexed by proper lilypond header attributes
270 def extract_score_information (tree):
271 header = musicexp.Header ()
272 def set_if_exists (field, value):
273 if value:
274 header.set_field (field, musicxml.escape_ly_output_string (value))
276 movement_title = tree.get_maybe_exist_named_child ('movement-title')
277 if movement_title:
278 set_if_exists ('title', movement_title.get_text ())
279 work = tree.get_maybe_exist_named_child ('work')
280 if work:
281 # Overwrite the title from movement-title with work->title
282 set_if_exists ('title', work.get_work_title ())
283 set_if_exists ('worknumber', work.get_work_number ())
284 set_if_exists ('opus', work.get_opus ())
286 identifications = tree.get_named_children ('identification')
287 for ids in identifications:
288 set_if_exists ('copyright', ids.get_rights ())
289 set_if_exists ('composer', ids.get_composer ())
290 set_if_exists ('arranger', ids.get_arranger ())
291 set_if_exists ('editor', ids.get_editor ())
292 set_if_exists ('poet', ids.get_poet ())
294 set_if_exists ('tagline', ids.get_encoding_software ())
295 set_if_exists ('encodingsoftware', ids.get_encoding_software ())
296 set_if_exists ('encodingdate', ids.get_encoding_date ())
297 set_if_exists ('encoder', ids.get_encoding_person ())
298 set_if_exists ('encodingdescription', ids.get_encoding_description ())
300 set_if_exists ('texidoc', ids.get_file_description ());
302 # Finally, apply the required compatibility modes
303 # Some applications created wrong MusicXML files, so we need to
304 # apply some compatibility mode, e.g. ignoring some features/tags
305 # in those files
306 software = ids.get_encoding_software_list ()
308 # Case 1: "Sibelius 5.1" with the "Dolet 3.4 for Sibelius" plugin
309 # is missing all beam ends => ignore all beaming information
310 ignore_beaming_software = {
311 "Dolet 4 for Sibelius, Beta 2": "Dolet 4 for Sibelius, Beta 2",
312 "Dolet 3.5 for Sibelius": "Dolet 3.5 for Sibelius",
313 "Dolet 3.4 for Sibelius": "Dolet 3.4 for Sibelius",
314 "Dolet 3.3 for Sibelius": "Dolet 3.3 for Sibelius",
315 "Dolet 3.2 for Sibelius": "Dolet 3.2 for Sibelius",
316 "Dolet 3.1 for Sibelius": "Dolet 3.1 for Sibelius",
317 "Dolet for Sibelius 1.3": "Dolet for Sibelius 1.3",
318 "Noteworthy Composer": "Noteworthy Composer's nwc2xm[",
320 for s in software:
321 app_description = ignore_beaming_software.get (s, False);
322 if app_description:
323 conversion_settings.ignore_beaming = True
324 progress (_ ("Encountered file created by %s, containing wrong beaming information. All beaming information in the MusicXML file will be ignored") % app_description)
326 # TODO: Check for other unsupported features
327 return header
329 class PartGroupInfo:
330 def __init__ (self):
331 self.start = {}
332 self.end = {}
333 def is_empty (self):
334 return len (self.start) + len (self.end) == 0
335 def add_start (self, g):
336 self.start[getattr (g, 'number', "1")] = g
337 def add_end (self, g):
338 self.end[getattr (g, 'number', "1")] = g
339 def print_ly (self, printer):
340 error_message (_ ("Unprocessed PartGroupInfo %s encountered") % self)
341 def ly_expression (self):
342 error_message (_ ("Unprocessed PartGroupInfo %s encountered") % self)
343 return ''
345 def staff_attributes_to_string_tunings (mxl_attr):
346 details = mxl_attr.get_maybe_exist_named_child ('staff-details')
347 if not details:
348 return []
349 lines = 6
350 staff_lines = details.get_maybe_exist_named_child ('staff-lines')
351 if staff_lines:
352 lines = string.atoi (staff_lines.get_text ())
354 tunings = [0]*lines
355 staff_tunings = details.get_named_children ('staff-tuning')
356 for i in staff_tunings:
357 p = musicexp.Pitch()
358 line = 0
359 try:
360 line = string.atoi (i.line) - 1
361 except ValueError:
362 pass
363 tunings[line] = p
365 step = i.get_named_child (u'tuning-step')
366 step = step.get_text ().strip ()
367 p.step = musicxml_step_to_lily (step)
369 octave = i.get_named_child (u'tuning-octave')
370 octave = octave.get_text ().strip ()
371 p.octave = int (octave) - 4
373 alter = i.get_named_child (u'tuning-alter')
374 if alter:
375 p.alteration = int (alter.get_text ().strip ())
376 # lilypond seems to use the opposite ordering than MusicXML...
377 tunings.reverse ()
379 return tunings
382 def staff_attributes_to_lily_staff (mxl_attr):
383 if not mxl_attr:
384 return musicexp.Staff ()
386 (staff_id, attributes) = mxl_attr.items ()[0]
388 # distinguish by clef:
389 # percussion (percussion and rhythmic), tab, and everything else
390 clef_sign = None
391 clef = attributes.get_maybe_exist_named_child ('clef')
392 if clef:
393 sign = clef.get_maybe_exist_named_child ('sign')
394 if sign:
395 clef_sign = {"percussion": "percussion", "TAB": "tab"}.get (sign.get_text (), None)
397 lines = 5
398 details = attributes.get_named_children ('staff-details')
399 for d in details:
400 staff_lines = d.get_maybe_exist_named_child ('staff-lines')
401 if staff_lines:
402 lines = string.atoi (staff_lines.get_text ())
404 staff = None
405 if clef_sign == "percussion" and lines == 1:
406 staff = musicexp.RhythmicStaff ()
407 elif clef_sign == "percussion":
408 staff = musicexp.DrumStaff ()
409 # staff.drum_style_table = ???
410 elif clef_sign == "tab":
411 staff = musicexp.TabStaff ()
412 staff.string_tunings = staff_attributes_to_string_tunings (attributes)
413 # staff.tablature_format = ???
414 else:
415 # TODO: Handle case with lines <> 5!
416 staff = musicexp.Staff ()
418 return staff
421 def extract_score_structure (part_list, staffinfo):
422 score = musicexp.Score ()
423 structure = musicexp.StaffGroup (None)
424 score.set_contents (structure)
426 if not part_list:
427 return structure
429 def read_score_part (el):
430 if not isinstance (el, musicxml.Score_part):
431 return
432 # Depending on the attributes of the first measure, we create different
433 # types of staves (Staff, RhythmicStaff, DrumStaff, TabStaff, etc.)
434 staff = staff_attributes_to_lily_staff (staffinfo.get (el.id, None))
435 if not staff:
436 return None
437 staff.id = el.id
438 partname = el.get_maybe_exist_named_child ('part-name')
439 # Finale gives unnamed parts the name "MusicXML Part" automatically!
440 if partname and partname.get_text() != "MusicXML Part":
441 staff.instrument_name = partname.get_text ()
442 if el.get_maybe_exist_named_child ('part-abbreviation'):
443 staff.short_instrument_name = el.get_maybe_exist_named_child ('part-abbreviation').get_text ()
444 # TODO: Read in the MIDI device / instrument
445 return staff
447 def read_score_group (el):
448 if not isinstance (el, musicxml.Part_group):
449 return
450 group = musicexp.StaffGroup ()
451 if hasattr (el, 'number'):
452 id = el.number
453 group.id = id
454 #currentgroups_dict[id] = group
455 #currentgroups.append (id)
456 if el.get_maybe_exist_named_child ('group-name'):
457 group.instrument_name = el.get_maybe_exist_named_child ('group-name').get_text ()
458 if el.get_maybe_exist_named_child ('group-abbreviation'):
459 group.short_instrument_name = el.get_maybe_exist_named_child ('group-abbreviation').get_text ()
460 if el.get_maybe_exist_named_child ('group-symbol'):
461 group.symbol = el.get_maybe_exist_named_child ('group-symbol').get_text ()
462 if el.get_maybe_exist_named_child ('group-barline'):
463 group.spanbar = el.get_maybe_exist_named_child ('group-barline').get_text ()
464 return group
467 parts_groups = part_list.get_all_children ()
469 # the start/end group tags are not necessarily ordered correctly and groups
470 # might even overlap, so we can't go through the children sequentially!
472 # 1) Replace all Score_part objects by their corresponding Staff objects,
473 # also collect all group start/stop points into one PartGroupInfo object
474 staves = []
475 group_info = PartGroupInfo ()
476 for el in parts_groups:
477 if isinstance (el, musicxml.Score_part):
478 if not group_info.is_empty ():
479 staves.append (group_info)
480 group_info = PartGroupInfo ()
481 staff = read_score_part (el)
482 if staff:
483 staves.append (staff)
484 elif isinstance (el, musicxml.Part_group):
485 if el.type == "start":
486 group_info.add_start (el)
487 elif el.type == "stop":
488 group_info.add_end (el)
489 if not group_info.is_empty ():
490 staves.append (group_info)
492 # 2) Now, detect the groups:
493 group_starts = []
494 pos = 0
495 while pos < len (staves):
496 el = staves[pos]
497 if isinstance (el, PartGroupInfo):
498 prev_start = 0
499 if len (group_starts) > 0:
500 prev_start = group_starts[-1]
501 elif len (el.end) > 0: # no group to end here
502 el.end = {}
503 if len (el.end) > 0: # closes an existing group
504 ends = el.end.keys ()
505 prev_started = staves[prev_start].start.keys ()
506 grpid = None
507 intersection = filter(lambda x:x in ends, prev_started)
508 if len (intersection) > 0:
509 grpid = intersection[0]
510 else:
511 # Close the last started group
512 grpid = staves[prev_start].start.keys () [0]
513 # Find the corresponding closing tag and remove it!
514 j = pos + 1
515 foundclosing = False
516 while j < len (staves) and not foundclosing:
517 if isinstance (staves[j], PartGroupInfo) and staves[j].end.has_key (grpid):
518 foundclosing = True
519 del staves[j].end[grpid]
520 if staves[j].is_empty ():
521 del staves[j]
522 j += 1
523 grpobj = staves[prev_start].start[grpid]
524 group = read_score_group (grpobj)
525 # remove the id from both the start and end
526 if el.end.has_key (grpid):
527 del el.end[grpid]
528 del staves[prev_start].start[grpid]
529 if el.is_empty ():
530 del staves[pos]
531 # replace the staves with the whole group
532 for j in staves[(prev_start + 1):pos]:
533 group.append_staff (j)
534 del staves[(prev_start + 1):pos]
535 staves.insert (prev_start + 1, group)
536 # reset pos so that we continue at the correct position
537 pos = prev_start
538 # remove an empty start group
539 if staves[prev_start].is_empty ():
540 del staves[prev_start]
541 group_starts.remove (prev_start)
542 pos -= 1
543 elif len (el.start) > 0: # starts new part groups
544 group_starts.append (pos)
545 pos += 1
547 if len (staves) == 1:
548 return staves[0]
549 for i in staves:
550 structure.append_staff (i)
551 return score
554 def musicxml_duration_to_lily (mxl_note):
555 # if the note has no Type child, then that method returns None. In that case,
556 # use the <duration> tag instead. If that doesn't exist, either -> Error
557 dur = mxl_note.get_duration_info ()
558 if dur:
559 d = musicexp.Duration ()
560 d.duration_log = dur[0]
561 d.dots = dur[1]
562 # Grace notes by specification have duration 0, so no time modification
563 # factor is possible. It even messes up the output with *0/1
564 if not mxl_note.get_maybe_exist_typed_child (musicxml.Grace):
565 d.factor = mxl_note._duration / d.get_length ()
566 return d
568 else:
569 if mxl_note._duration > 0:
570 return rational_to_lily_duration (mxl_note._duration)
571 else:
572 mxl_note.message (_ ("Encountered note at %s without type and duration (=%s)") % (mxl_note.start, mxl_note._duration) )
573 return None
576 def rational_to_lily_duration (rational_len):
577 d = musicexp.Duration ()
579 rational_len.normalize_self ()
580 d_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)
582 # Duration of the form 1/2^n or 3/2^n can be converted to a simple lilypond duration
583 dots = {1: 0, 3: 1, 7: 2, 15: 3, 31: 4, 63: 5, 127: 6}.get (rational_len.numerator(), -1)
584 if ( d_log >= dots >= 0 ):
585 # account for the dots!
586 d.duration_log = d_log - dots
587 d.dots = dots
588 elif (d_log >= 0):
589 d.duration_log = d_log
590 d.factor = Rational (rational_len.numerator ())
591 else:
592 error_message (_ ("Encountered rational duration with denominator %s, "
593 "unable to convert to lilypond duration") %
594 rational_len.denominator ())
595 # TODO: Test the above error message
596 return None
598 return d
600 def musicxml_partial_to_lily (partial_len):
601 if partial_len > 0:
602 p = musicexp.Partial ()
603 p.partial = rational_to_lily_duration (partial_len)
604 return p
605 else:
606 return Null
608 # Detect repeats and alternative endings in the chord event list (music_list)
609 # and convert them to the corresponding musicexp objects, containing nested
610 # music
611 def group_repeats (music_list):
612 repeat_replaced = True
613 music_start = 0
614 i = 0
615 # Walk through the list of expressions, looking for repeat structure
616 # (repeat start/end, corresponding endings). If we find one, try to find the
617 # last event of the repeat, replace the whole structure and start over again.
618 # For nested repeats, as soon as we encounter another starting repeat bar,
619 # treat that one first, and start over for the outer repeat.
620 while repeat_replaced and i < 100:
621 i += 1
622 repeat_start = -1 # position of repeat start / end
623 repeat_end = -1 # position of repeat start / end
624 repeat_times = 0
625 ending_start = -1 # position of current ending start
626 endings = [] # list of already finished endings
627 pos = 0
628 last = len (music_list) - 1
629 repeat_replaced = False
630 final_marker = 0
631 while pos < len (music_list) and not repeat_replaced:
632 e = music_list[pos]
633 repeat_finished = False
634 if isinstance (e, RepeatMarker):
635 if not repeat_times and e.times:
636 repeat_times = e.times
637 if e.direction == -1:
638 if repeat_end >= 0:
639 repeat_finished = True
640 else:
641 repeat_start = pos
642 repeat_end = -1
643 ending_start = -1
644 endings = []
645 elif e.direction == 1:
646 if repeat_start < 0:
647 repeat_start = 0
648 if repeat_end < 0:
649 repeat_end = pos
650 final_marker = pos
651 elif isinstance (e, EndingMarker):
652 if e.direction == -1:
653 if repeat_start < 0:
654 repeat_start = 0
655 if repeat_end < 0:
656 repeat_end = pos
657 ending_start = pos
658 elif e.direction == 1:
659 if ending_start < 0:
660 ending_start = 0
661 endings.append ([ending_start, pos])
662 ending_start = -1
663 final_marker = pos
664 elif not isinstance (e, musicexp.BarLine):
665 # As soon as we encounter an element when repeat start and end
666 # is set and we are not inside an alternative ending,
667 # this whole repeat structure is finished => replace it
668 if repeat_start >= 0 and repeat_end > 0 and ending_start < 0:
669 repeat_finished = True
671 # Finish off all repeats without explicit ending bar (e.g. when
672 # we convert only one page of a multi-page score with repeats)
673 if pos == last and repeat_start >= 0:
674 repeat_finished = True
675 final_marker = pos
676 if repeat_end < 0:
677 repeat_end = pos
678 if ending_start >= 0:
679 endings.append ([ending_start, pos])
680 ending_start = -1
682 if repeat_finished:
683 # We found the whole structure replace it!
684 r = musicexp.RepeatedMusic ()
685 if repeat_times <= 0:
686 repeat_times = 2
687 r.repeat_count = repeat_times
688 # don't erase the first element for "implicit" repeats (i.e. no
689 # starting repeat bars at the very beginning)
690 start = repeat_start+1
691 if repeat_start == music_start:
692 start = music_start
693 r.set_music (music_list[start:repeat_end])
694 for (start, end) in endings:
695 s = musicexp.SequentialMusic ()
696 s.elements = music_list[start+1:end]
697 r.add_ending (s)
698 del music_list[repeat_start:final_marker+1]
699 music_list.insert (repeat_start, r)
700 repeat_replaced = True
701 pos += 1
702 # TODO: Implement repeats until the end without explicit ending bar
703 return music_list
706 # Extract the settings for tuplets from the <notations><tuplet> and the
707 # <time-modification> elements of the note:
708 def musicxml_tuplet_to_lily (tuplet_elt, time_modification):
709 tsm = musicexp.TimeScaledMusic ()
710 fraction = (1,1)
711 if time_modification:
712 fraction = time_modification.get_fraction ()
713 tsm.numerator = fraction[0]
714 tsm.denominator = fraction[1]
717 normal_type = tuplet_elt.get_normal_type ()
718 if not normal_type and time_modification:
719 normal_type = time_modification.get_normal_type ()
720 if not normal_type and time_modification:
721 note = time_modification.get_parent ()
722 if note:
723 normal_type = note.get_duration_info ()
724 if normal_type:
725 normal_note = musicexp.Duration ()
726 (normal_note.duration_log, normal_note.dots) = normal_type
727 tsm.normal_type = normal_note
729 actual_type = tuplet_elt.get_actual_type ()
730 if actual_type:
731 actual_note = musicexp.Duration ()
732 (actual_note.duration_log, actual_note.dots) = actual_type
733 tsm.actual_type = actual_note
735 # Obtain non-default nrs of notes from the tuplet object!
736 tsm.display_numerator = tuplet_elt.get_normal_nr ()
737 tsm.display_denominator = tuplet_elt.get_actual_nr ()
740 if hasattr (tuplet_elt, 'bracket') and tuplet_elt.bracket == "no":
741 tsm.display_bracket = None
742 elif hasattr (tuplet_elt, 'line-shape') and getattr (tuplet_elt, 'line-shape') == "curved":
743 tsm.display_bracket = "curved"
744 else:
745 tsm.display_bracket = "bracket"
747 display_values = {"none": None, "actual": "actual", "both": "both"}
748 if hasattr (tuplet_elt, "show-number"):
749 tsm.display_number = display_values.get (getattr (tuplet_elt, "show-number"), "actual")
751 if hasattr (tuplet_elt, "show-type"):
752 tsm.display_type = display_values.get (getattr (tuplet_elt, "show-type"), None)
754 return tsm
757 def group_tuplets (music_list, events):
760 """Collect Musics from
761 MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
765 indices = []
766 brackets = {}
768 j = 0
769 for (ev_chord, tuplet_elt, time_modification) in events:
770 while (j < len (music_list)):
771 if music_list[j] == ev_chord:
772 break
773 j += 1
774 nr = 0
775 if hasattr (tuplet_elt, 'number'):
776 nr = getattr (tuplet_elt, 'number')
777 if tuplet_elt.type == 'start':
778 tuplet_object = musicxml_tuplet_to_lily (tuplet_elt, time_modification)
779 tuplet_info = [j, None, tuplet_object]
780 indices.append (tuplet_info)
781 brackets[nr] = tuplet_info
782 elif tuplet_elt.type == 'stop':
783 bracket_info = brackets.get (nr, None)
784 if bracket_info:
785 bracket_info[1] = j # Set the ending position to j
786 del brackets[nr]
788 new_list = []
789 last = 0
790 for (i1, i2, tsm) in indices:
791 if i1 > i2:
792 continue
794 new_list.extend (music_list[last:i1])
795 seq = musicexp.SequentialMusic ()
796 last = i2 + 1
797 seq.elements = music_list[i1:last]
799 tsm.element = seq
801 new_list.append (tsm)
802 #TODO: Handle nested tuplets!!!!
804 new_list.extend (music_list[last:])
805 return new_list
808 def musicxml_clef_to_lily (attributes):
809 change = musicexp.ClefChange ()
810 (change.type, change.position, change.octave) = attributes.get_clef_information ()
811 return change
813 def musicxml_time_to_lily (attributes):
814 sig = attributes.get_time_signature ()
815 if not sig:
816 return None
817 change = musicexp.TimeSignatureChange()
818 change.fractions = sig
819 if (len(sig) != 2) or isinstance (sig[0], list):
820 needed_additional_definitions.append ("compound-time-signature")
822 time_elm = attributes.get_maybe_exist_named_child ('time')
823 if time_elm and hasattr (time_elm, 'symbol'):
824 change.style = { 'single-number': "'single-digit",
825 'cut': None,
826 'common': None,
827 'normal': "'()"}.get (time_elm.symbol, "'()")
828 else:
829 change.style = "'()"
831 # TODO: Handle senza-misura measures
832 # TODO: Handle hidden time signatures (print-object="no")
833 # TODO: What shall we do if the symbol clashes with the sig? e.g. "cut"
834 # with 3/8 or "single-number" with (2+3)/8 or 3/8+2/4?
836 return change
838 def musicxml_key_to_lily (attributes):
839 key_sig = attributes.get_key_signature ()
840 if not key_sig or not (isinstance (key_sig, list) or isinstance (key_sig, tuple)):
841 error_message (_ ("Unable to extract key signature!"))
842 return None
844 change = musicexp.KeySignatureChange()
846 if len (key_sig) == 2 and not isinstance (key_sig[0], list):
847 # standard key signature, (fifths, mode)
848 (fifths, mode) = key_sig
849 change.mode = mode
851 start_pitch = musicexp.Pitch ()
852 start_pitch.octave = 0
853 try:
854 (n,a) = {
855 'major' : (0,0),
856 'minor' : (5,0),
857 'ionian' : (0,0),
858 'dorian' : (1,0),
859 'phrygian' : (2,0),
860 'lydian' : (3,0),
861 'mixolydian': (4,0),
862 'aeolian' : (5,0),
863 'locrian' : (6,0),
864 }[mode]
865 start_pitch.step = n
866 start_pitch.alteration = a
867 except KeyError:
868 error_message (_ ("unknown mode %s, expecting 'major' or 'minor' "
869 "or a church mode!") % mode)
871 fifth = musicexp.Pitch()
872 fifth.step = 4
873 if fifths < 0:
874 fifths *= -1
875 fifth.step *= -1
876 fifth.normalize ()
877 for x in range (fifths):
878 start_pitch = start_pitch.transposed (fifth)
879 change.tonic = start_pitch
881 else:
882 # Non-standard key signature of the form [[step,alter<,octave>],...]
883 change.non_standard_alterations = key_sig
884 return change
886 def musicxml_transpose_to_lily (attributes):
887 transpose = attributes.get_transposition ()
888 if not transpose:
889 return None
891 shift = musicexp.Pitch ()
892 octave_change = transpose.get_maybe_exist_named_child ('octave-change')
893 if octave_change:
894 shift.octave = string.atoi (octave_change.get_text ())
895 chromatic_shift = string.atoi (transpose.get_named_child ('chromatic').get_text ())
896 chromatic_shift_normalized = chromatic_shift % 12;
897 (shift.step, shift.alteration) = [
898 (0,0), (0,1), (1,0), (2,-1), (2,0),
899 (3,0), (3,1), (4,0), (5,-1), (5,0),
900 (6,-1), (6,0)][chromatic_shift_normalized];
902 shift.octave += (chromatic_shift - chromatic_shift_normalized) / 12
904 diatonic = transpose.get_maybe_exist_named_child ('diatonic')
905 if diatonic:
906 diatonic_step = string.atoi (diatonic.get_text ()) % 7
907 if diatonic_step != shift.step:
908 # We got the alter incorrect!
909 old_semitones = shift.semitones ()
910 shift.step = diatonic_step
911 new_semitones = shift.semitones ()
912 shift.alteration += old_semitones - new_semitones
914 transposition = musicexp.Transposition ()
915 transposition.pitch = musicexp.Pitch ().transposed (shift)
916 return transposition
919 def musicxml_attributes_to_lily (attrs):
920 elts = []
921 attr_dispatch = {
922 'clef': musicxml_clef_to_lily,
923 'time': musicxml_time_to_lily,
924 'key': musicxml_key_to_lily,
925 'transpose': musicxml_transpose_to_lily,
927 for (k, func) in attr_dispatch.items ():
928 children = attrs.get_named_children (k)
929 if children:
930 ev = func (attrs)
931 if ev:
932 elts.append (ev)
934 return elts
936 def musicxml_print_to_lily (el):
937 # TODO: Implement other print attributes
938 # <!ELEMENT print (page-layout?, system-layout?, staff-layout*,
939 # measure-layout?, measure-numbering?, part-name-display?,
940 # part-abbreviation-display?)>
941 # <!ATTLIST print
942 # staff-spacing %tenths; #IMPLIED
943 # new-system %yes-no; #IMPLIED
944 # new-page %yes-no-number; #IMPLIED
945 # blank-page NMTOKEN #IMPLIED
946 # page-number CDATA #IMPLIED
948 elts = []
949 if (hasattr (el, "new-system") and conversion_settings.convert_page_layout):
950 val = getattr (el, "new-system")
951 if (val == "yes"):
952 elts.append (musicexp.Break ("break"))
953 if (hasattr (el, "new-page") and conversion_settings.convert_page_layout):
954 val = getattr (el, "new-page")
955 if (val == "yes"):
956 elts.append (musicexp.Break ("pageBreak"))
957 return elts
960 class Marker (musicexp.Music):
961 def __init__ (self):
962 self.direction = 0
963 self.event = None
964 def print_ly (self, printer):
965 ly.stderr_write (_ ("Encountered unprocessed marker %s\n") % self)
966 pass
967 def ly_expression (self):
968 return ""
969 class RepeatMarker (Marker):
970 def __init__ (self):
971 Marker.__init__ (self)
972 self.times = 0
973 class EndingMarker (Marker):
974 pass
976 # Convert the <barline> element to musicxml.BarLine (for non-standard barlines)
977 # and to RepeatMarker and EndingMarker objects for repeat and
978 # alternatives start/stops
979 def musicxml_barline_to_lily (barline):
980 # retval contains all possible markers in the order:
981 # 0..bw_ending, 1..bw_repeat, 2..barline, 3..fw_repeat, 4..fw_ending
982 retval = {}
983 bartype_element = barline.get_maybe_exist_named_child ("bar-style")
984 repeat_element = barline.get_maybe_exist_named_child ("repeat")
985 ending_element = barline.get_maybe_exist_named_child ("ending")
987 bartype = None
988 if bartype_element:
989 bartype = bartype_element.get_text ()
991 if repeat_element and hasattr (repeat_element, 'direction'):
992 repeat = RepeatMarker ()
993 repeat.direction = {"forward": -1, "backward": 1}.get (repeat_element.direction, 0)
995 if ( (repeat_element.direction == "forward" and bartype == "heavy-light") or
996 (repeat_element.direction == "backward" and bartype == "light-heavy") ):
997 bartype = None
998 if hasattr (repeat_element, 'times'):
999 try:
1000 repeat.times = int (repeat_element.times)
1001 except ValueError:
1002 repeat.times = 2
1003 repeat.event = barline
1004 if repeat.direction == -1:
1005 retval[3] = repeat
1006 else:
1007 retval[1] = repeat
1009 if ending_element and hasattr (ending_element, 'type'):
1010 ending = EndingMarker ()
1011 ending.direction = {"start": -1, "stop": 1, "discontinue": 1}.get (ending_element.type, 0)
1012 ending.event = barline
1013 if ending.direction == -1:
1014 retval[4] = ending
1015 else:
1016 retval[0] = ending
1018 if bartype:
1019 b = musicexp.BarLine ()
1020 b.type = bartype
1021 retval[2] = b
1023 return retval.values ()
1025 spanner_event_dict = {
1026 'beam' : musicexp.BeamEvent,
1027 'dashes' : musicexp.TextSpannerEvent,
1028 'bracket' : musicexp.BracketSpannerEvent,
1029 'glissando' : musicexp.GlissandoEvent,
1030 'octave-shift' : musicexp.OctaveShiftEvent,
1031 'pedal' : musicexp.PedalEvent,
1032 'slide' : musicexp.GlissandoEvent,
1033 'slur' : musicexp.SlurEvent,
1034 'wavy-line' : musicexp.TrillSpanEvent,
1035 'wedge' : musicexp.HairpinEvent
1037 spanner_type_dict = {
1038 'start': -1,
1039 'begin': -1,
1040 'crescendo': -1,
1041 'decreschendo': -1,
1042 'diminuendo': -1,
1043 'continue': 0,
1044 'change': 0,
1045 'up': -1,
1046 'down': -1,
1047 'stop': 1,
1048 'end' : 1
1051 def musicxml_spanner_to_lily_event (mxl_event):
1052 ev = None
1054 name = mxl_event.get_name()
1055 func = spanner_event_dict.get (name)
1056 if func:
1057 ev = func()
1058 else:
1059 error_message (_ ('unknown span event %s') % mxl_event)
1062 type = mxl_event.get_type ()
1063 span_direction = spanner_type_dict.get (type)
1064 # really check for None, because some types will be translated to 0, which
1065 # would otherwise also lead to the unknown span warning
1066 if span_direction != None:
1067 ev.span_direction = span_direction
1068 else:
1069 error_message (_ ('unknown span type %s for %s') % (type, name))
1071 ev.set_span_type (type)
1072 ev.line_type = getattr (mxl_event, 'line-type', 'solid')
1074 # assign the size, which is used for octave-shift, etc.
1075 ev.size = mxl_event.get_size ()
1077 return ev
1079 def musicxml_direction_to_indicator (direction):
1080 return { "above": 1, "upright": 1, "up": 1, "below": -1, "downright": -1, "down": -1, "inverted": -1 }.get (direction, 0)
1082 def musicxml_fermata_to_lily_event (mxl_event):
1083 ev = musicexp.ArticulationEvent ()
1084 txt = mxl_event.get_text ()
1085 # The contents of the element defined the shape, possible are normal, angled and square
1086 ev.type = { "angled": "shortfermata", "square": "longfermata" }.get (txt, "fermata")
1087 if hasattr (mxl_event, 'type'):
1088 dir = musicxml_direction_to_indicator (mxl_event.type)
1089 if dir and options.convert_directions:
1090 ev.force_direction = dir
1091 return ev
1093 def musicxml_arpeggiate_to_lily_event (mxl_event):
1094 ev = musicexp.ArpeggioEvent ()
1095 ev.direction = musicxml_direction_to_indicator (getattr (mxl_event, 'direction', None))
1096 return ev
1098 def musicxml_nonarpeggiate_to_lily_event (mxl_event):
1099 ev = musicexp.ArpeggioEvent ()
1100 ev.non_arpeggiate = True
1101 ev.direction = musicxml_direction_to_indicator (getattr (mxl_event, 'direction', None))
1102 return ev
1104 def musicxml_tremolo_to_lily_event (mxl_event):
1105 ev = musicexp.TremoloEvent ()
1106 txt = mxl_event.get_text ()
1107 if txt:
1108 ev.bars = txt
1109 else:
1110 ev.bars = "3"
1111 return ev
1113 def musicxml_falloff_to_lily_event (mxl_event):
1114 ev = musicexp.BendEvent ()
1115 ev.alter = -4
1116 return ev
1118 def musicxml_doit_to_lily_event (mxl_event):
1119 ev = musicexp.BendEvent ()
1120 ev.alter = 4
1121 return ev
1123 def musicxml_bend_to_lily_event (mxl_event):
1124 ev = musicexp.BendEvent ()
1125 ev.alter = mxl_event.bend_alter ()
1126 return ev
1128 def musicxml_caesura_to_lily_event (mxl_event):
1129 ev = musicexp.MarkupEvent ()
1130 # FIXME: default to straight or curved caesura?
1131 ev.contents = "\\musicglyph #\"scripts.caesura.straight\""
1132 ev.force_direction = 1
1133 return ev
1135 def musicxml_fingering_event (mxl_event):
1136 ev = musicexp.ShortArticulationEvent ()
1137 ev.type = mxl_event.get_text ()
1138 return ev
1140 def musicxml_string_event (mxl_event):
1141 ev = musicexp.NoDirectionArticulationEvent ()
1142 ev.type = mxl_event.get_text ()
1143 return ev
1145 def musicxml_accidental_mark (mxl_event):
1146 ev = musicexp.MarkupEvent ()
1147 contents = { "sharp": "\\sharp",
1148 "natural": "\\natural",
1149 "flat": "\\flat",
1150 "double-sharp": "\\doublesharp",
1151 "sharp-sharp": "\\sharp\\sharp",
1152 "flat-flat": "\\flat\\flat",
1153 "flat-flat": "\\doubleflat",
1154 "natural-sharp": "\\natural\\sharp",
1155 "natural-flat": "\\natural\\flat",
1156 "quarter-flat": "\\semiflat",
1157 "quarter-sharp": "\\semisharp",
1158 "three-quarters-flat": "\\sesquiflat",
1159 "three-quarters-sharp": "\\sesquisharp",
1160 }.get (mxl_event.get_text ())
1161 if contents:
1162 ev.contents = contents
1163 return ev
1164 else:
1165 return None
1167 # translate articulations, ornaments and other notations into ArticulationEvents
1168 # possible values:
1169 # -) string (ArticulationEvent with that name)
1170 # -) function (function(mxl_event) needs to return a full ArticulationEvent-derived object
1171 # -) (class, name) (like string, only that a different class than ArticulationEvent is used)
1172 # TODO: Some translations are missing!
1173 articulations_dict = {
1174 "accent": (musicexp.ShortArticulationEvent, ">"), # or "accent"
1175 "accidental-mark": musicxml_accidental_mark,
1176 "bend": musicxml_bend_to_lily_event,
1177 "breath-mark": (musicexp.NoDirectionArticulationEvent, "breathe"),
1178 "caesura": musicxml_caesura_to_lily_event,
1179 #"delayed-turn": "?",
1180 "detached-legato": (musicexp.ShortArticulationEvent, "_"), # or "portato"
1181 "doit": musicxml_doit_to_lily_event,
1182 #"double-tongue": "?",
1183 "down-bow": "downbow",
1184 "falloff": musicxml_falloff_to_lily_event,
1185 "fingering": musicxml_fingering_event,
1186 #"fingernails": "?",
1187 #"fret": "?",
1188 #"hammer-on": "?",
1189 "harmonic": "flageolet",
1190 #"heel": "?",
1191 "inverted-mordent": "prall",
1192 "inverted-turn": "reverseturn",
1193 "mordent": "mordent",
1194 "open-string": "open",
1195 #"plop": "?",
1196 #"pluck": "?",
1197 #"pull-off": "?",
1198 #"schleifer": "?",
1199 #"scoop": "?",
1200 #"shake": "?",
1201 "snap-pizzicato": "snappizzicato",
1202 #"spiccato": "?",
1203 "staccatissimo": (musicexp.ShortArticulationEvent, "|"), # or "staccatissimo"
1204 "staccato": (musicexp.ShortArticulationEvent, "."), # or "staccato"
1205 "stopped": (musicexp.ShortArticulationEvent, "+"), # or "stopped"
1206 #"stress": "?",
1207 "string": musicxml_string_event,
1208 "strong-accent": (musicexp.ShortArticulationEvent, "^"), # or "marcato"
1209 #"tap": "?",
1210 "tenuto": (musicexp.ShortArticulationEvent, "-"), # or "tenuto"
1211 "thumb-position": "thumb",
1212 #"toe": "?",
1213 "turn": "turn",
1214 "tremolo": musicxml_tremolo_to_lily_event,
1215 "trill-mark": "trill",
1216 #"triple-tongue": "?",
1217 #"unstress": "?"
1218 "up-bow": "upbow",
1219 #"wavy-line": "?",
1221 articulation_spanners = [ "wavy-line" ]
1223 def musicxml_articulation_to_lily_event (mxl_event):
1224 # wavy-line elements are treated as trill spanners, not as articulation ornaments
1225 if mxl_event.get_name () in articulation_spanners:
1226 return musicxml_spanner_to_lily_event (mxl_event)
1228 tmp_tp = articulations_dict.get (mxl_event.get_name ())
1229 if not tmp_tp:
1230 return
1232 if isinstance (tmp_tp, str):
1233 ev = musicexp.ArticulationEvent ()
1234 ev.type = tmp_tp
1235 elif isinstance (tmp_tp, tuple):
1236 ev = tmp_tp[0] ()
1237 ev.type = tmp_tp[1]
1238 else:
1239 ev = tmp_tp (mxl_event)
1241 # Some articulations use the type attribute, other the placement...
1242 dir = None
1243 if hasattr (mxl_event, 'type') and options.convert_directions:
1244 dir = musicxml_direction_to_indicator (mxl_event.type)
1245 if hasattr (mxl_event, 'placement') and options.convert_directions:
1246 dir = musicxml_direction_to_indicator (mxl_event.placement)
1247 if dir:
1248 ev.force_direction = dir
1249 return ev
1253 def musicxml_dynamics_to_lily_event (dynentry):
1254 dynamics_available = (
1255 "ppppp", "pppp", "ppp", "pp", "p", "mp", "mf",
1256 "f", "ff", "fff", "ffff", "fp", "sf", "sff", "sp", "spp", "sfz", "rfz" )
1257 dynamicsname = dynentry.get_name ()
1258 if dynamicsname == "other-dynamics":
1259 dynamicsname = dynentry.get_text ()
1260 if not dynamicsname or dynamicsname=="#text":
1261 return
1263 if not dynamicsname in dynamics_available:
1264 # Get rid of - in tag names (illegal in ly tags!)
1265 dynamicstext = dynamicsname
1266 dynamicsname = string.replace (dynamicsname, "-", "")
1267 additional_definitions[dynamicsname] = dynamicsname + \
1268 " = #(make-dynamic-script \"" + dynamicstext + "\")"
1269 needed_additional_definitions.append (dynamicsname)
1270 event = musicexp.DynamicsEvent ()
1271 event.type = dynamicsname
1272 return event
1274 # Convert single-color two-byte strings to numbers 0.0 - 1.0
1275 def hexcolorval_to_nr (hex_val):
1276 try:
1277 v = int (hex_val, 16)
1278 if v == 255:
1279 v = 256
1280 return v / 256.
1281 except ValueError:
1282 return 0.
1284 def hex_to_color (hex_val):
1285 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)
1286 if res:
1287 return map (lambda x: hexcolorval_to_nr (x), res.group (2,3,4))
1288 else:
1289 return None
1291 def musicxml_words_to_lily_event (words):
1292 event = musicexp.TextEvent ()
1293 text = words.get_text ()
1294 text = re.sub ('^ *\n? *', '', text)
1295 text = re.sub (' *\n? *$', '', text)
1296 event.text = text
1298 if hasattr (words, 'default-y') and options.convert_directions:
1299 offset = getattr (words, 'default-y')
1300 try:
1301 off = string.atoi (offset)
1302 if off > 0:
1303 event.force_direction = 1
1304 else:
1305 event.force_direction = -1
1306 except ValueError:
1307 event.force_direction = 0
1309 if hasattr (words, 'font-weight'):
1310 font_weight = { "normal": '', "bold": '\\bold' }.get (getattr (words, 'font-weight'), '')
1311 if font_weight:
1312 event.markup += font_weight
1314 if hasattr (words, 'font-size'):
1315 size = getattr (words, 'font-size')
1316 font_size = {
1317 "xx-small": '\\teeny',
1318 "x-small": '\\tiny',
1319 "small": '\\small',
1320 "medium": '',
1321 "large": '\\large',
1322 "x-large": '\\huge',
1323 "xx-large": '\\larger\\huge'
1324 }.get (size, '')
1325 if font_size:
1326 event.markup += font_size
1328 if hasattr (words, 'color'):
1329 color = getattr (words, 'color')
1330 rgb = hex_to_color (color)
1331 if rgb:
1332 event.markup += "\\with-color #(rgb-color %s %s %s)" % (rgb[0], rgb[1], rgb[2])
1334 if hasattr (words, 'font-style'):
1335 font_style = { "italic": '\\italic' }.get (getattr (words, 'font-style'), '')
1336 if font_style:
1337 event.markup += font_style
1339 # TODO: How should I best convert the font-family attribute?
1341 # TODO: How can I represent the underline, overline and line-through
1342 # attributes in LilyPond? Values of these attributes indicate
1343 # the number of lines
1345 return event
1348 # convert accordion-registration to lilypond.
1349 # Since lilypond does not have any built-in commands, we need to create
1350 # the markup commands manually and define our own variables.
1351 # Idea was taken from: http://lsr.dsi.unimi.it/LSR/Item?id=194
1352 def musicxml_accordion_to_markup (mxl_event):
1353 commandname = "accReg"
1354 command = ""
1356 high = mxl_event.get_maybe_exist_named_child ('accordion-high')
1357 if high:
1358 commandname += "H"
1359 command += """\\combine
1360 \\raise #2.5 \\musicglyph #\"accordion.accDot\"
1362 middle = mxl_event.get_maybe_exist_named_child ('accordion-middle')
1363 if middle:
1364 # By default, use one dot (when no or invalid content is given). The
1365 # MusicXML spec is quiet about this case...
1366 txt = 1
1367 try:
1368 txt = string.atoi (middle.get_text ())
1369 except ValueError:
1370 pass
1371 if txt == 3:
1372 commandname += "MMM"
1373 command += """\\combine
1374 \\raise #1.5 \\musicglyph #\"accordion.accDot\"
1375 \\combine
1376 \\raise #1.5 \\translate #(cons 1 0) \\musicglyph #\"accordion.accDot\"
1377 \\combine
1378 \\raise #1.5 \\translate #(cons -1 0) \\musicglyph #\"accordion.accDot\"
1380 elif txt == 2:
1381 commandname += "MM"
1382 command += """\\combine
1383 \\raise #1.5 \\translate #(cons 0.5 0) \\musicglyph #\"accordion.accDot\"
1384 \\combine
1385 \\raise #1.5 \\translate #(cons -0.5 0) \\musicglyph #\"accordion.accDot\"
1387 elif not txt <= 0:
1388 commandname += "M"
1389 command += """\\combine
1390 \\raise #1.5 \\musicglyph #\"accordion.accDot\"
1392 low = mxl_event.get_maybe_exist_named_child ('accordion-low')
1393 if low:
1394 commandname += "L"
1395 command += """\\combine
1396 \\raise #0.5 \musicglyph #\"accordion.accDot\"
1399 command += "\musicglyph #\"accordion.accDiscant\""
1400 command = "\\markup { \\normalsize %s }" % command
1401 # Define the newly built command \accReg[H][MMM][L]
1402 additional_definitions[commandname] = "%s = %s" % (commandname, command)
1403 needed_additional_definitions.append (commandname)
1404 return "\\%s" % commandname
1406 def musicxml_accordion_to_ly (mxl_event):
1407 txt = musicxml_accordion_to_markup (mxl_event)
1408 if txt:
1409 ev = musicexp.MarkEvent (txt)
1410 return ev
1411 return
1414 def musicxml_rehearsal_to_ly_mark (mxl_event):
1415 text = mxl_event.get_text ()
1416 if not text:
1417 return
1418 # default is boxed rehearsal marks!
1419 encl = "box"
1420 if hasattr (mxl_event, 'enclosure'):
1421 encl = {"none": None, "square": "box", "circle": "circle" }.get (mxl_event.enclosure, None)
1422 if encl:
1423 text = "\\%s { %s }" % (encl, text)
1424 ev = musicexp.MarkEvent ("\\markup { %s }" % text)
1425 return ev
1427 def musicxml_harp_pedals_to_ly (mxl_event):
1428 count = 0
1429 result = "\\harp-pedal #\""
1430 for t in mxl_event.get_named_children ('pedal-tuning'):
1431 alter = t.get_named_child ('pedal-alter')
1432 if alter:
1433 val = int (alter.get_text ().strip ())
1434 result += {1: "v", 0: "-", -1: "^"}.get (val, "")
1435 count += 1
1436 if count == 3:
1437 result += "|"
1438 ev = musicexp.MarkupEvent ()
1439 ev.contents = result + "\""
1440 return ev
1442 def musicxml_eyeglasses_to_ly (mxl_event):
1443 needed_additional_definitions.append ("eyeglasses")
1444 return musicexp.MarkEvent ("\\markup { \\eyeglasses }")
1446 def next_non_hash_index (lst, pos):
1447 pos += 1
1448 while pos < len (lst) and isinstance (lst[pos], musicxml.Hash_text):
1449 pos += 1
1450 return pos
1452 def musicxml_metronome_to_ly (mxl_event):
1453 children = mxl_event.get_all_children ()
1454 if not children:
1455 return
1457 index = -1
1458 index = next_non_hash_index (children, index)
1459 if isinstance (children[index], musicxml.BeatUnit):
1460 # first form of metronome-mark, using unit and beats/min or other unit
1461 ev = musicexp.TempoMark ()
1462 if hasattr (mxl_event, 'parentheses'):
1463 ev.set_parentheses (mxl_event.parentheses == "yes")
1465 d = musicexp.Duration ()
1466 d.duration_log = musicxml.musicxml_duration_to_log (children[index].get_text ())
1467 index = next_non_hash_index (children, index)
1468 if isinstance (children[index], musicxml.BeatUnitDot):
1469 d.dots = 1
1470 index = next_non_hash_index (children, index)
1471 ev.set_base_duration (d)
1472 if isinstance (children[index], musicxml.BeatUnit):
1473 # Form "note = newnote"
1474 newd = musicexp.Duration ()
1475 newd.duration_log = musicxml.musicxml_duration_to_log (children[index].get_text ())
1476 index = next_non_hash_index (children, index)
1477 if isinstance (children[index], musicxml.BeatUnitDot):
1478 newd.dots = 1
1479 index = next_non_hash_index (children, index)
1480 ev.set_new_duration (newd)
1481 elif isinstance (children[index], musicxml.PerMinute):
1482 # Form "note = bpm"
1483 try:
1484 beats = int (children[index].get_text ())
1485 ev.set_beats_per_minute (beats)
1486 except ValueError:
1487 pass
1488 else:
1489 error_message (_ ("Unknown metronome mark, ignoring"))
1490 return
1491 return ev
1492 else:
1493 #TODO: Implement the other (more complex) way for tempo marks!
1494 error_message (_ ("Metronome marks with complex relations (<metronome-note> in MusicXML) are not yet implemented."))
1495 return
1497 # translate directions into Events, possible values:
1498 # -) string (MarkEvent with that command)
1499 # -) function (function(mxl_event) needs to return a full Event-derived object
1500 # -) (class, name) (like string, only that a different class than MarkEvent is used)
1501 directions_dict = {
1502 'accordion-registration' : musicxml_accordion_to_ly,
1503 'coda' : (musicexp.MusicGlyphMarkEvent, "coda"),
1504 # 'damp' : ???
1505 # 'damp-all' : ???
1506 'eyeglasses': musicxml_eyeglasses_to_ly,
1507 'harp-pedals' : musicxml_harp_pedals_to_ly,
1508 # 'image' : ???
1509 'metronome' : musicxml_metronome_to_ly,
1510 'rehearsal' : musicxml_rehearsal_to_ly_mark,
1511 # 'scordatura' : ???
1512 'segno' : (musicexp.MusicGlyphMarkEvent, "segno"),
1513 'words' : musicxml_words_to_lily_event,
1515 directions_spanners = [ 'octave-shift', 'pedal', 'wedge', 'dashes', 'bracket' ]
1517 def musicxml_direction_to_lily (n):
1518 # TODO: Handle the <staff> element!
1519 res = []
1520 # placement applies to all children!
1521 dir = None
1522 if hasattr (n, 'placement') and options.convert_directions:
1523 dir = musicxml_direction_to_indicator (n.placement)
1524 dirtype_children = []
1525 # TODO: The direction-type is used for grouping (e.g. dynamics with text),
1526 # so we can't simply flatten them out!
1527 for dt in n.get_typed_children (musicxml.DirType):
1528 dirtype_children += dt.get_all_children ()
1530 for entry in dirtype_children:
1531 # backets, dashes, octave shifts. pedal marks, hairpins etc. are spanners:
1532 if entry.get_name() in directions_spanners:
1533 event = musicxml_spanner_to_lily_event (entry)
1534 if event:
1535 res.append (event)
1536 continue
1538 # now treat all the "simple" ones, that can be translated using the dict
1539 ev = None
1540 tmp_tp = directions_dict.get (entry.get_name (), None)
1541 if isinstance (tmp_tp, str): # string means MarkEvent
1542 ev = musicexp.MarkEvent (tmp_tp)
1543 elif isinstance (tmp_tp, tuple): # tuple means (EventClass, "text")
1544 ev = tmp_tp[0] (tmp_tp[1])
1545 elif tmp_tp:
1546 ev = tmp_tp (entry)
1547 if ev:
1548 # TODO: set the correct direction! Unfortunately, \mark in ly does
1549 # not seem to support directions!
1550 res.append (ev)
1551 continue
1553 if entry.get_name () == "dynamics":
1554 for dynentry in entry.get_all_children ():
1555 ev = musicxml_dynamics_to_lily_event (dynentry)
1556 if ev:
1557 res.append (ev)
1559 return res
1561 def musicxml_frame_to_lily_event (frame):
1562 ev = musicexp.FretEvent ()
1563 ev.strings = frame.get_strings ()
1564 ev.frets = frame.get_frets ()
1565 #offset = frame.get_first_fret () - 1
1566 barre = []
1567 for fn in frame.get_named_children ('frame-note'):
1568 fret = fn.get_fret ()
1569 if fret <= 0:
1570 fret = "o"
1571 el = [ fn.get_string (), fret ]
1572 fingering = fn.get_fingering ()
1573 if fingering >= 0:
1574 el.append (fingering)
1575 ev.elements.append (el)
1576 b = fn.get_barre ()
1577 if b == 'start':
1578 barre[0] = el[0] # start string
1579 barre[2] = el[1] # fret
1580 elif b == 'stop':
1581 barre[1] = el[0] # end string
1582 if barre:
1583 ev.barre = barre
1584 return ev
1586 def musicxml_harmony_to_lily (n):
1587 res = []
1588 for f in n.get_named_children ('frame'):
1589 ev = musicxml_frame_to_lily_event (f)
1590 if ev:
1591 res.append (ev)
1592 return res
1595 notehead_styles_dict = {
1596 'slash': '\'slash',
1597 'triangle': '\'triangle',
1598 'diamond': '\'diamond',
1599 'square': '\'la', # TODO: Proper squared note head
1600 'cross': None, # TODO: + shaped note head
1601 'x': '\'cross',
1602 'circle-x': '\'xcircle',
1603 'inverted triangle': None, # TODO: Implement
1604 'arrow down': None, # TODO: Implement
1605 'arrow up': None, # TODO: Implement
1606 'slashed': None, # TODO: Implement
1607 'back slashed': None, # TODO: Implement
1608 'normal': None,
1609 'cluster': None, # TODO: Implement
1610 'none': '#f',
1611 'do': '\'do',
1612 're': '\'re',
1613 'mi': '\'mi',
1614 'fa': '\'fa',
1615 'so': None,
1616 'la': '\'la',
1617 'ti': '\'ti',
1620 def musicxml_notehead_to_lily (nh):
1621 styles = []
1623 # Notehead style
1624 style = notehead_styles_dict.get (nh.get_text ().strip (), None)
1625 style_elm = musicexp.NotestyleEvent ()
1626 if style:
1627 style_elm.style = style
1628 if hasattr (nh, 'filled'):
1629 style_elm.filled = (getattr (nh, 'filled') == "yes")
1630 if style_elm.style or (style_elm.filled != None):
1631 styles.append (style_elm)
1633 # parentheses
1634 if hasattr (nh, 'parentheses') and (nh.parentheses == "yes"):
1635 styles.append (musicexp.ParenthesizeEvent ())
1637 return styles
1639 def musicxml_chordpitch_to_lily (mxl_cpitch):
1640 r = musicexp.ChordPitch ()
1641 r.alteration = mxl_cpitch.get_alteration ()
1642 r.step = musicxml_step_to_lily (mxl_cpitch.get_step ())
1643 return r
1645 chordkind_dict = {
1646 'major': '5',
1647 'minor': 'm5',
1648 'augmented': 'aug5',
1649 'diminished': 'dim5',
1650 # Sevenths:
1651 'dominant': '7',
1652 'dominant-seventh': '7',
1653 'major-seventh': 'maj7',
1654 'minor-seventh': 'm7',
1655 'diminished-seventh': 'dim7',
1656 'augmented-seventh': 'aug7',
1657 'half-diminished': 'dim5m7',
1658 'major-minor': 'maj7m5',
1659 # Sixths:
1660 'major-sixth': '6',
1661 'minor-sixth': 'm6',
1662 # Ninths:
1663 'dominant-ninth': '9',
1664 'major-ninth': 'maj9',
1665 'minor-ninth': 'm9',
1666 # 11ths (usually as the basis for alteration):
1667 'dominant-11th': '11',
1668 'major-11th': 'maj11',
1669 'minor-11th': 'm11',
1670 # 13ths (usually as the basis for alteration):
1671 'dominant-13th': '13.11',
1672 'major-13th': 'maj13.11',
1673 'minor-13th': 'm13',
1674 # Suspended:
1675 'suspended-second': 'sus2',
1676 'suspended-fourth': 'sus4',
1677 # Functional sixths:
1678 # TODO
1679 #'Neapolitan': '???',
1680 #'Italian': '???',
1681 #'French': '???',
1682 #'German': '???',
1683 # Other:
1684 #'pedal': '???',(pedal-point bass)
1685 'power': '5^3',
1686 #'Tristan': '???',
1687 'other': '1',
1688 'none': None,
1691 def musicxml_chordkind_to_lily (kind):
1692 res = chordkind_dict.get (kind, None)
1693 # Check for None, since a major chord is converted to ''
1694 if res == None:
1695 error_message (_ ("Unable to convert chord type %s to lilypond.") % kind)
1696 return res
1698 def musicxml_harmony_to_lily_chordname (n):
1699 res = []
1700 root = n.get_maybe_exist_named_child ('root')
1701 if root:
1702 ev = musicexp.ChordNameEvent ()
1703 ev.root = musicxml_chordpitch_to_lily (root)
1704 kind = n.get_maybe_exist_named_child ('kind')
1705 if kind:
1706 ev.kind = musicxml_chordkind_to_lily (kind.get_text ())
1707 if not ev.kind:
1708 return res
1709 bass = n.get_maybe_exist_named_child ('bass')
1710 if bass:
1711 ev.bass = musicxml_chordpitch_to_lily (bass)
1712 inversion = n.get_maybe_exist_named_child ('inversion')
1713 if inversion:
1714 # TODO: LilyPond does not support inversions, does it?
1716 # Mail from Carl Sorensen on lilypond-devel, June 11, 2008:
1717 # 4. LilyPond supports the first inversion in the form of added
1718 # bass notes. So the first inversion of C major would be c:/g.
1719 # To get the second inversion of C major, you would need to do
1720 # e:6-3-^5 or e:m6-^5. However, both of these techniques
1721 # require you to know the chord and calculate either the fifth
1722 # pitch (for the first inversion) or the third pitch (for the
1723 # second inversion) so they may not be helpful for musicxml2ly.
1724 inversion_count = string.atoi (inversion.get_text ())
1725 if inversion_count == 1:
1726 # TODO: Calculate the bass note for the inversion...
1727 pass
1728 pass
1729 for deg in n.get_named_children ('degree'):
1730 d = musicexp.ChordModification ()
1731 d.type = deg.get_type ()
1732 d.step = deg.get_value ()
1733 d.alteration = deg.get_alter ()
1734 ev.add_modification (d)
1735 #TODO: convert the user-symbols attribute:
1736 #major: a triangle, like Unicode 25B3
1737 #minor: -, like Unicode 002D
1738 #augmented: +, like Unicode 002B
1739 #diminished: (degree), like Unicode 00B0
1740 #half-diminished: (o with slash), like Unicode 00F8
1741 if ev and ev.root:
1742 res.append (ev)
1744 return res
1746 def musicxml_figured_bass_note_to_lily (n):
1747 res = musicexp.FiguredBassNote ()
1748 suffix_dict = { 'sharp' : "+",
1749 'flat' : "-",
1750 'natural' : "!",
1751 'double-sharp' : "++",
1752 'flat-flat' : "--",
1753 'sharp-sharp' : "++",
1754 'slash' : "/" }
1755 prefix = n.get_maybe_exist_named_child ('prefix')
1756 if prefix:
1757 res.set_prefix (suffix_dict.get (prefix.get_text (), ""))
1758 fnumber = n.get_maybe_exist_named_child ('figure-number')
1759 if fnumber:
1760 res.set_number (fnumber.get_text ())
1761 suffix = n.get_maybe_exist_named_child ('suffix')
1762 if suffix:
1763 res.set_suffix (suffix_dict.get (suffix.get_text (), ""))
1764 if n.get_maybe_exist_named_child ('extend'):
1765 # TODO: Implement extender lines (unfortunately, in lilypond you have
1766 # to use \set useBassFigureExtenders = ##t, which turns them on
1767 # globally, while MusicXML has a property for each note...
1768 # I'm not sure there is a proper way to implement this cleanly
1769 #n.extend
1770 pass
1771 return res
1775 def musicxml_figured_bass_to_lily (n):
1776 if not isinstance (n, musicxml.FiguredBass):
1777 return
1778 res = musicexp.FiguredBassEvent ()
1779 for i in n.get_named_children ('figure'):
1780 note = musicxml_figured_bass_note_to_lily (i)
1781 if note:
1782 res.append (note)
1783 dur = n.get_maybe_exist_named_child ('duration')
1784 if dur:
1785 # apply the duration to res
1786 length = Rational(int(dur.get_text()), n._divisions)*Rational(1,4)
1787 res.set_real_duration (length)
1788 duration = rational_to_lily_duration (length)
1789 if duration:
1790 res.set_duration (duration)
1791 if hasattr (n, 'parentheses') and n.parentheses == "yes":
1792 res.set_parentheses (True)
1793 return res
1795 instrument_drumtype_dict = {
1796 'Acoustic Snare Drum': 'acousticsnare',
1797 'Side Stick': 'sidestick',
1798 'Open Triangle': 'opentriangle',
1799 'Mute Triangle': 'mutetriangle',
1800 'Tambourine': 'tambourine',
1801 'Bass Drum': 'bassdrum',
1804 def musicxml_note_to_lily_main_event (n):
1805 pitch = None
1806 duration = None
1807 event = None
1809 mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
1810 if mxl_pitch:
1811 pitch = musicxml_pitch_to_lily (mxl_pitch)
1812 event = musicexp.NoteEvent ()
1813 event.pitch = pitch
1815 acc = n.get_maybe_exist_named_child ('accidental')
1816 if acc:
1817 # let's not force accs everywhere.
1818 event.cautionary = acc.editorial
1820 elif n.get_maybe_exist_typed_child (musicxml.Unpitched):
1821 # Unpitched elements have display-step and can also have
1822 # display-octave.
1823 unpitched = n.get_maybe_exist_typed_child (musicxml.Unpitched)
1824 event = musicexp.NoteEvent ()
1825 event.pitch = musicxml_unpitched_to_lily (unpitched)
1827 elif n.get_maybe_exist_typed_child (musicxml.Rest):
1828 # rests can have display-octave and display-step, which are
1829 # treated like an ordinary note pitch
1830 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
1831 event = musicexp.RestEvent ()
1832 if options.convert_rest_positions:
1833 pitch = musicxml_restdisplay_to_lily (rest)
1834 event.pitch = pitch
1836 elif n.instrument_name:
1837 event = musicexp.NoteEvent ()
1838 drum_type = instrument_drumtype_dict.get (n.instrument_name)
1839 if drum_type:
1840 event.drum_type = drum_type
1841 else:
1842 n.message (_ ("drum %s type unknown, please add to instrument_drumtype_dict") % n.instrument_name)
1843 event.drum_type = 'acousticsnare'
1845 else:
1846 n.message (_ ("cannot find suitable event"))
1848 if event:
1849 event.duration = musicxml_duration_to_lily (n)
1851 noteheads = n.get_named_children ('notehead')
1852 for nh in noteheads:
1853 styles = musicxml_notehead_to_lily (nh)
1854 for s in styles:
1855 event.add_associated_event (s)
1857 return event
1859 def musicxml_lyrics_to_text (lyrics):
1860 # TODO: Implement text styles for lyrics syllables
1861 continued = False
1862 extended = False
1863 text = ''
1864 for e in lyrics.get_all_children ():
1865 if isinstance (e, musicxml.Syllabic):
1866 continued = e.continued ()
1867 elif isinstance (e, musicxml.Text):
1868 # We need to convert soft hyphens to -, otherwise the ascii codec as well
1869 # as lilypond will barf on that character
1870 text += string.replace( e.get_text(), u'\xad', '-' )
1871 elif isinstance (e, musicxml.Elision):
1872 if text:
1873 text += " "
1874 continued = False
1875 extended = False
1876 elif isinstance (e, musicxml.Extend):
1877 if text:
1878 text += " "
1879 extended = True
1881 if text == "-" and continued:
1882 return "--"
1883 elif text == "_" and extended:
1884 return "__"
1885 elif continued and text:
1886 return musicxml.escape_ly_output_string (text) + " --"
1887 elif continued:
1888 return "--"
1889 elif extended and text:
1890 return musicxml.escape_ly_output_string (text) + " __"
1891 elif extended:
1892 return "__"
1893 elif text:
1894 return musicxml.escape_ly_output_string (text)
1895 else:
1896 return ""
1898 ## TODO
1899 class NegativeSkip:
1900 def __init__ (self, here, dest):
1901 self.here = here
1902 self.dest = dest
1904 class LilyPondVoiceBuilder:
1905 def __init__ (self):
1906 self.elements = []
1907 self.pending_dynamics = []
1908 self.end_moment = Rational (0)
1909 self.begin_moment = Rational (0)
1910 self.pending_multibar = Rational (0)
1911 self.ignore_skips = False
1912 self.has_relevant_elements = False
1913 self.measure_length = Rational (4, 4)
1915 def _insert_multibar (self):
1916 layout_information.set_context_item ('Score', 'skipBars = ##t')
1917 r = musicexp.MultiMeasureRest ()
1918 lenfrac = self.measure_length
1919 r.duration = rational_to_lily_duration (lenfrac)
1920 r.duration.factor *= self.pending_multibar / lenfrac
1921 self.elements.append (r)
1922 self.begin_moment = self.end_moment
1923 self.end_moment = self.begin_moment + self.pending_multibar
1924 self.pending_multibar = Rational (0)
1926 def set_measure_length (self, mlen):
1927 if (mlen != self.measure_length) and self.pending_multibar:
1928 self._insert_multibar ()
1929 self.measure_length = mlen
1931 def add_multibar_rest (self, duration):
1932 self.pending_multibar += duration
1934 def set_duration (self, duration):
1935 self.end_moment = self.begin_moment + duration
1936 def current_duration (self):
1937 return self.end_moment - self.begin_moment
1939 def add_music (self, music, duration, relevant = True):
1940 assert isinstance (music, musicexp.Music)
1941 if self.pending_multibar > Rational (0):
1942 self._insert_multibar ()
1944 self.has_relevant_elements = self.has_relevant_elements or relevant
1945 self.elements.append (music)
1946 self.begin_moment = self.end_moment
1947 self.set_duration (duration)
1949 # Insert all pending dynamics right after the note/rest:
1950 if isinstance (music, musicexp.ChordEvent) and self.pending_dynamics:
1951 for d in self.pending_dynamics:
1952 music.append (d)
1953 self.pending_dynamics = []
1955 # Insert some music command that does not affect the position in the measure
1956 def add_command (self, command, relevant = True):
1957 assert isinstance (command, musicexp.Music)
1958 if self.pending_multibar > Rational (0):
1959 self._insert_multibar ()
1960 self.has_relevant_elements = self.has_relevant_elements or relevant
1961 self.elements.append (command)
1962 def add_barline (self, barline, relevant = False):
1963 # Insert only if we don't have a barline already
1964 # TODO: Implement proper merging of default barline and custom bar line
1965 has_relevant = self.has_relevant_elements
1966 if (not (self.elements) or
1967 not (isinstance (self.elements[-1], musicexp.BarLine)) or
1968 (self.pending_multibar > Rational (0))):
1969 self.add_music (barline, Rational (0))
1970 self.has_relevant_elements = has_relevant or relevant
1971 def add_partial (self, command):
1972 self.ignore_skips = True
1973 # insert the partial, but restore relevant_elements (partial is not relevant)
1974 relevant = self.has_relevant_elements
1975 self.add_command (command)
1976 self.has_relevant_elements = relevant
1978 def add_dynamics (self, dynamic):
1979 # store the dynamic item(s) until we encounter the next note/rest:
1980 self.pending_dynamics.append (dynamic)
1982 def add_bar_check (self, number):
1983 # re/store has_relevant_elements, so that a barline alone does not
1984 # trigger output for figured bass, chord names
1985 b = musicexp.BarLine ()
1986 b.bar_number = number
1987 self.add_barline (b)
1989 def jumpto (self, moment):
1990 current_end = self.end_moment + self.pending_multibar
1991 diff = moment - current_end
1993 if diff < Rational (0):
1994 error_message (_ ('Negative skip %s (from position %s to %s)') %
1995 (diff, current_end, moment))
1996 diff = Rational (0)
1998 if diff > Rational (0) and not (self.ignore_skips and moment == 0):
1999 skip = musicexp.SkipEvent()
2000 duration_factor = 1
2001 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)
2002 duration_dots = 0
2003 # TODO: Use the time signature for skips, too. Problem: The skip
2004 # might not start at a measure boundary!
2005 if duration_log > 0: # denominator is a power of 2...
2006 if diff.numerator () == 3:
2007 duration_log -= 1
2008 duration_dots = 1
2009 else:
2010 duration_factor = Rational (diff.numerator ())
2011 else:
2012 # for skips of a whole or more, simply use s1*factor
2013 duration_log = 0
2014 duration_factor = diff
2015 skip.duration.duration_log = duration_log
2016 skip.duration.factor = duration_factor
2017 skip.duration.dots = duration_dots
2019 evc = musicexp.ChordEvent ()
2020 evc.elements.append (skip)
2021 self.add_music (evc, diff, False)
2023 if diff > Rational (0) and moment == 0:
2024 self.ignore_skips = False
2026 def last_event_chord (self, starting_at):
2028 value = None
2030 # if the position matches, find the last ChordEvent, do not cross a bar line!
2031 at = len( self.elements ) - 1
2032 while (at >= 0 and
2033 not isinstance (self.elements[at], musicexp.ChordEvent) and
2034 not isinstance (self.elements[at], musicexp.BarLine)):
2035 at -= 1
2037 if (self.elements
2038 and at >= 0
2039 and isinstance (self.elements[at], musicexp.ChordEvent)
2040 and self.begin_moment == starting_at):
2041 value = self.elements[at]
2042 else:
2043 self.jumpto (starting_at)
2044 value = None
2045 return value
2047 def correct_negative_skip (self, goto):
2048 self.end_moment = goto
2049 self.begin_moment = goto
2050 evc = musicexp.ChordEvent ()
2051 self.elements.append (evc)
2054 class VoiceData:
2055 def __init__ (self):
2056 self.voicename = None
2057 self.voicedata = None
2058 self.ly_voice = None
2059 self.figured_bass = None
2060 self.chordnames = None
2061 self.lyrics_dict = {}
2062 self.lyrics_order = []
2064 def musicxml_step_to_lily (step):
2065 if step:
2066 return (ord (step) - ord ('A') + 7 - 2) % 7
2067 else:
2068 return None
2070 def measure_length_from_attributes (attr, current_measure_length):
2071 len = attr.get_measure_length ()
2072 if not len:
2073 len = current_measure_length
2074 return len
2076 def musicxml_voice_to_lily_voice (voice):
2077 tuplet_events = []
2078 modes_found = {}
2079 lyrics = {}
2080 return_value = VoiceData ()
2081 return_value.voicedata = voice
2083 # First pitch needed for relative mode (if selected in command-line options)
2084 first_pitch = None
2086 # Needed for melismata detection (ignore lyrics on those notes!):
2087 inside_slur = False
2088 is_tied = False
2089 is_chord = False
2090 is_beamed = False
2091 ignore_lyrics = False
2093 current_staff = None
2095 pending_figured_bass = []
2096 pending_chordnames = []
2098 # Make sure that the keys in the dict don't get reordered, since
2099 # we need the correct ordering of the lyrics stanzas! By default,
2100 # a dict will reorder its keys
2101 return_value.lyrics_order = voice.get_lyrics_numbers ()
2102 for k in return_value.lyrics_order:
2103 lyrics[k] = []
2105 voice_builder = LilyPondVoiceBuilder ()
2106 figured_bass_builder = LilyPondVoiceBuilder ()
2107 chordnames_builder = LilyPondVoiceBuilder ()
2108 current_measure_length = Rational (4, 4)
2109 voice_builder.set_measure_length (current_measure_length)
2111 for n in voice._elements:
2112 tie_started = False
2113 if n.get_name () == 'forward':
2114 continue
2115 staff = n.get_maybe_exist_named_child ('staff')
2116 if staff:
2117 staff = staff.get_text ()
2118 if current_staff and staff <> current_staff and not n.get_maybe_exist_named_child ('chord'):
2119 voice_builder.add_command (musicexp.StaffChange (staff))
2120 current_staff = staff
2122 if isinstance (n, musicxml.Partial) and n.partial > 0:
2123 a = musicxml_partial_to_lily (n.partial)
2124 if a:
2125 voice_builder.add_partial (a)
2126 figured_bass_builder.add_partial (a)
2127 chordnames_builder.add_partial (a)
2128 continue
2130 is_chord = n.get_maybe_exist_named_child ('chord')
2131 is_after_grace = (isinstance (n, musicxml.Note) and n.is_after_grace ());
2132 if not is_chord and not is_after_grace:
2133 try:
2134 voice_builder.jumpto (n._when)
2135 figured_bass_builder.jumpto (n._when)
2136 chordnames_builder.jumpto (n._when)
2137 except NegativeSkip, neg:
2138 voice_builder.correct_negative_skip (n._when)
2139 figured_bass_builder.correct_negative_skip (n._when)
2140 chordnames_builder.correct_negative_skip (n._when)
2141 n.message (_ ("Negative skip found: from %s to %s, difference is %s") % (neg.here, neg.dest, neg.dest - neg.here))
2143 if isinstance (n, musicxml.Barline):
2144 barlines = musicxml_barline_to_lily (n)
2145 for a in barlines:
2146 if isinstance (a, musicexp.BarLine):
2147 voice_builder.add_barline (a)
2148 figured_bass_builder.add_barline (a, False)
2149 chordnames_builder.add_barline (a, False)
2150 elif isinstance (a, RepeatMarker) or isinstance (a, EndingMarker):
2151 voice_builder.add_command (a)
2152 figured_bass_builder.add_barline (a, False)
2153 chordnames_builder.add_barline (a, False)
2154 continue
2157 if isinstance (n, musicxml.Print):
2158 for a in musicxml_print_to_lily (n):
2159 voice_builder.add_command (a, False)
2160 continue
2162 # Continue any multimeasure-rests before trying to add bar checks!
2163 # Don't handle new MM rests yet, because for them we want bar checks!
2164 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
2165 if (rest and rest.is_whole_measure ()
2166 and voice_builder.pending_multibar > Rational (0)):
2167 voice_builder.add_multibar_rest (n._duration)
2168 continue
2171 # print a bar check at the beginning of each measure!
2172 if n.is_first () and n._measure_position == Rational (0) and n != voice._elements[0]:
2173 try:
2174 num = int (n.get_parent ().number)
2175 except ValueError:
2176 num = 0
2177 if num > 0:
2178 voice_builder.add_bar_check (num)
2179 figured_bass_builder.add_bar_check (num)
2180 chordnames_builder.add_bar_check (num)
2182 # Start any new multimeasure rests
2183 if (rest and rest.is_whole_measure ()):
2184 voice_builder.add_multibar_rest (n._duration)
2185 continue
2188 if isinstance (n, musicxml.Direction):
2189 for a in musicxml_direction_to_lily (n):
2190 if a.wait_for_note ():
2191 voice_builder.add_dynamics (a)
2192 else:
2193 voice_builder.add_command (a)
2194 continue
2196 if isinstance (n, musicxml.Harmony):
2197 for a in musicxml_harmony_to_lily (n):
2198 if a.wait_for_note ():
2199 voice_builder.add_dynamics (a)
2200 else:
2201 voice_builder.add_command (a)
2202 for a in musicxml_harmony_to_lily_chordname (n):
2203 pending_chordnames.append (a)
2204 continue
2206 if isinstance (n, musicxml.FiguredBass):
2207 a = musicxml_figured_bass_to_lily (n)
2208 if a:
2209 pending_figured_bass.append (a)
2210 continue
2212 if isinstance (n, musicxml.Attributes):
2213 for a in musicxml_attributes_to_lily (n):
2214 voice_builder.add_command (a)
2215 measure_length = measure_length_from_attributes (n, current_measure_length)
2216 if current_measure_length != measure_length:
2217 current_measure_length = measure_length
2218 voice_builder.set_measure_length (current_measure_length)
2219 continue
2221 if not n.__class__.__name__ == 'Note':
2222 n.message (_ ('unexpected %s; expected %s or %s or %s') % (n, 'Note', 'Attributes', 'Barline'))
2223 continue
2225 main_event = musicxml_note_to_lily_main_event (n)
2226 if main_event and not first_pitch:
2227 first_pitch = main_event.pitch
2228 # ignore lyrics for notes inside a slur, tie, chord or beam
2229 ignore_lyrics = inside_slur or is_tied or is_chord or is_beamed
2231 if main_event and hasattr (main_event, 'drum_type') and main_event.drum_type:
2232 modes_found['drummode'] = True
2234 ev_chord = voice_builder.last_event_chord (n._when)
2235 if not ev_chord:
2236 ev_chord = musicexp.ChordEvent()
2237 voice_builder.add_music (ev_chord, n._duration)
2239 # For grace notes:
2240 grace = n.get_maybe_exist_typed_child (musicxml.Grace)
2241 if n.is_grace ():
2242 is_after_grace = ev_chord.has_elements () or n.is_after_grace ();
2243 is_chord = n.get_maybe_exist_typed_child (musicxml.Chord)
2245 grace_chord = None
2247 # after-graces and other graces use different lists; Depending on
2248 # whether we have a chord or not, obtain either a new ChordEvent or
2249 # the previous one to create a chord
2250 if is_after_grace:
2251 if ev_chord.after_grace_elements and n.get_maybe_exist_typed_child (musicxml.Chord):
2252 grace_chord = ev_chord.after_grace_elements.get_last_event_chord ()
2253 if not grace_chord:
2254 grace_chord = musicexp.ChordEvent ()
2255 ev_chord.append_after_grace (grace_chord)
2256 elif n.is_grace ():
2257 if ev_chord.grace_elements and n.get_maybe_exist_typed_child (musicxml.Chord):
2258 grace_chord = ev_chord.grace_elements.get_last_event_chord ()
2259 if not grace_chord:
2260 grace_chord = musicexp.ChordEvent ()
2261 ev_chord.append_grace (grace_chord)
2263 if hasattr (grace, 'slash') and not is_after_grace:
2264 # TODO: use grace_type = "appoggiatura" for slurred grace notes
2265 if grace.slash == "yes":
2266 ev_chord.grace_type = "acciaccatura"
2267 # now that we have inserted the chord into the grace music, insert
2268 # everything into that chord instead of the ev_chord
2269 ev_chord = grace_chord
2270 ev_chord.append (main_event)
2271 ignore_lyrics = True
2272 else:
2273 ev_chord.append (main_event)
2274 # When a note/chord has grace notes (duration==0), the duration of the
2275 # event chord is not yet known, but the event chord was already added
2276 # with duration 0. The following correct this when we hit the real note!
2277 if voice_builder.current_duration () == 0 and n._duration > 0:
2278 voice_builder.set_duration (n._duration)
2280 # if we have a figured bass, set its voice builder to the correct position
2281 # and insert the pending figures
2282 if pending_figured_bass:
2283 try:
2284 figured_bass_builder.jumpto (n._when)
2285 except NegativeSkip, neg:
2286 pass
2287 for fb in pending_figured_bass:
2288 # if a duration is given, use that, otherwise the one of the note
2289 dur = fb.real_duration
2290 if not dur:
2291 dur = ev_chord.get_length ()
2292 if not fb.duration:
2293 fb.duration = ev_chord.get_duration ()
2294 figured_bass_builder.add_music (fb, dur)
2295 pending_figured_bass = []
2297 if pending_chordnames:
2298 try:
2299 chordnames_builder.jumpto (n._when)
2300 except NegativeSkip, neg:
2301 pass
2302 for cn in pending_chordnames:
2303 # Assign the duration of the EventChord
2304 cn.duration = ev_chord.get_duration ()
2305 chordnames_builder.add_music (cn, ev_chord.get_length ())
2306 pending_chordnames = []
2308 notations_children = n.get_typed_children (musicxml.Notations)
2309 tuplet_event = None
2310 span_events = []
2312 # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
2313 # +tied | +slur | +tuplet | glissando | slide |
2314 # ornaments | technical | articulations | dynamics |
2315 # +fermata | arpeggiate | non-arpeggiate |
2316 # accidental-mark | other-notation
2317 for notations in notations_children:
2318 for tuplet_event in notations.get_tuplets():
2319 time_mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
2320 tuplet_events.append ((ev_chord, tuplet_event, time_mod))
2322 # First, close all open slurs, only then start any new slur
2323 # TODO: Record the number of the open slur to dtermine the correct
2324 # closing slur!
2325 endslurs = [s for s in notations.get_named_children ('slur')
2326 if s.get_type () in ('stop')]
2327 if endslurs and not inside_slur:
2328 endslurs[0].message (_ ('Encountered closing slur, but no slur is open'))
2329 elif endslurs:
2330 if len (endslurs) > 1:
2331 endslurs[0].message (_ ('Cannot have two simultaneous (closing) slurs'))
2332 # record the slur status for the next note in the loop
2333 inside_slur = False
2334 lily_ev = musicxml_spanner_to_lily_event (endslurs[0])
2335 ev_chord.append (lily_ev)
2337 startslurs = [s for s in notations.get_named_children ('slur')
2338 if s.get_type () in ('start')]
2339 if startslurs and inside_slur:
2340 startslurs[0].message (_ ('Cannot have a slur inside another slur'))
2341 elif startslurs:
2342 if len (startslurs) > 1:
2343 startslurs[0].message (_ ('Cannot have two simultaneous slurs'))
2344 # record the slur status for the next note in the loop
2345 inside_slur = True
2346 lily_ev = musicxml_spanner_to_lily_event (startslurs[0])
2347 ev_chord.append (lily_ev)
2350 if not grace:
2351 mxl_tie = notations.get_tie ()
2352 if mxl_tie and mxl_tie.type == 'start':
2353 ev_chord.append (musicexp.TieEvent ())
2354 is_tied = True
2355 tie_started = True
2356 else:
2357 is_tied = False
2359 fermatas = notations.get_named_children ('fermata')
2360 for a in fermatas:
2361 ev = musicxml_fermata_to_lily_event (a)
2362 if ev:
2363 ev_chord.append (ev)
2365 arpeggiate = notations.get_named_children ('arpeggiate')
2366 for a in arpeggiate:
2367 ev = musicxml_arpeggiate_to_lily_event (a)
2368 if ev:
2369 ev_chord.append (ev)
2371 arpeggiate = notations.get_named_children ('non-arpeggiate')
2372 for a in arpeggiate:
2373 ev = musicxml_nonarpeggiate_to_lily_event (a)
2374 if ev:
2375 ev_chord.append (ev)
2377 glissandos = notations.get_named_children ('glissando')
2378 glissandos += notations.get_named_children ('slide')
2379 for a in glissandos:
2380 ev = musicxml_spanner_to_lily_event (a)
2381 if ev:
2382 ev_chord.append (ev)
2384 # accidental-marks are direct children of <notation>!
2385 for a in notations.get_named_children ('accidental-mark'):
2386 ev = musicxml_articulation_to_lily_event (a)
2387 if ev:
2388 ev_chord.append (ev)
2390 # Articulations can contain the following child elements:
2391 # accent | strong-accent | staccato | tenuto |
2392 # detached-legato | staccatissimo | spiccato |
2393 # scoop | plop | doit | falloff | breath-mark |
2394 # caesura | stress | unstress
2395 # Technical can contain the following child elements:
2396 # up-bow | down-bow | harmonic | open-string |
2397 # thumb-position | fingering | pluck | double-tongue |
2398 # triple-tongue | stopped | snap-pizzicato | fret |
2399 # string | hammer-on | pull-off | bend | tap | heel |
2400 # toe | fingernails | other-technical
2401 # Ornaments can contain the following child elements:
2402 # trill-mark | turn | delayed-turn | inverted-turn |
2403 # shake | wavy-line | mordent | inverted-mordent |
2404 # schleifer | tremolo | other-ornament, accidental-mark
2405 ornaments = notations.get_named_children ('ornaments')
2406 ornaments += notations.get_named_children ('articulations')
2407 ornaments += notations.get_named_children ('technical')
2409 for a in ornaments:
2410 for ch in a.get_all_children ():
2411 ev = musicxml_articulation_to_lily_event (ch)
2412 if ev:
2413 ev_chord.append (ev)
2415 dynamics = notations.get_named_children ('dynamics')
2416 for a in dynamics:
2417 for ch in a.get_all_children ():
2418 ev = musicxml_dynamics_to_lily_event (ch)
2419 if ev:
2420 ev_chord.append (ev)
2423 mxl_beams = [b for b in n.get_named_children ('beam')
2424 if (b.get_type () in ('begin', 'end')
2425 and b.is_primary ())]
2426 if mxl_beams and not conversion_settings.ignore_beaming:
2427 beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
2428 if beam_ev:
2429 ev_chord.append (beam_ev)
2430 if beam_ev.span_direction == -1: # beam and thus melisma starts here
2431 is_beamed = True
2432 elif beam_ev.span_direction == 1: # beam and thus melisma ends here
2433 is_beamed = False
2435 # Extract the lyrics
2436 if not rest and not ignore_lyrics:
2437 note_lyrics_processed = []
2438 note_lyrics_elements = n.get_typed_children (musicxml.Lyric)
2439 for l in note_lyrics_elements:
2440 if l.get_number () < 0:
2441 for k in lyrics.keys ():
2442 lyrics[k].append (musicxml_lyrics_to_text (l))
2443 note_lyrics_processed.append (k)
2444 else:
2445 lyrics[l.number].append(musicxml_lyrics_to_text (l))
2446 note_lyrics_processed.append (l.number)
2447 for lnr in lyrics.keys ():
2448 if not lnr in note_lyrics_processed:
2449 lyrics[lnr].append ("\skip4")
2451 # Assume that a <tie> element only lasts for one note.
2452 # This might not be correct MusicXML interpretation, but works for
2453 # most cases and fixes broken files, which have the end tag missing
2454 if is_tied and not tie_started:
2455 is_tied = False
2457 ## force trailing mm rests to be written out.
2458 voice_builder.add_music (musicexp.ChordEvent (), Rational (0))
2460 ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
2461 ly_voice = group_repeats (ly_voice)
2463 seq_music = musicexp.SequentialMusic ()
2465 if 'drummode' in modes_found.keys ():
2466 ## \key <pitch> barfs in drummode.
2467 ly_voice = [e for e in ly_voice
2468 if not isinstance(e, musicexp.KeySignatureChange)]
2470 seq_music.elements = ly_voice
2471 for k in lyrics.keys ():
2472 return_value.lyrics_dict[k] = musicexp.Lyrics ()
2473 return_value.lyrics_dict[k].lyrics_syllables = lyrics[k]
2476 if len (modes_found) > 1:
2477 error_message (_ ('cannot simultaneously have more than one mode: %s') % modes_found.keys ())
2479 if options.relative:
2480 v = musicexp.RelativeMusic ()
2481 v.element = seq_music
2482 v.basepitch = first_pitch
2483 seq_music = v
2485 return_value.ly_voice = seq_music
2486 for mode in modes_found.keys ():
2487 v = musicexp.ModeChangingMusicWrapper()
2488 v.element = seq_music
2489 v.mode = mode
2490 return_value.ly_voice = v
2492 # create \figuremode { figured bass elements }
2493 if figured_bass_builder.has_relevant_elements:
2494 fbass_music = musicexp.SequentialMusic ()
2495 fbass_music.elements = group_repeats (figured_bass_builder.elements)
2496 v = musicexp.ModeChangingMusicWrapper()
2497 v.mode = 'figuremode'
2498 v.element = fbass_music
2499 return_value.figured_bass = v
2501 # create \chordmode { chords }
2502 if chordnames_builder.has_relevant_elements:
2503 cname_music = musicexp.SequentialMusic ()
2504 cname_music.elements = group_repeats (chordnames_builder.elements)
2505 v = musicexp.ModeChangingMusicWrapper()
2506 v.mode = 'chordmode'
2507 v.element = cname_music
2508 return_value.chordnames = v
2510 return return_value
2512 def musicxml_id_to_lily (id):
2513 digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five',
2514 'Six', 'Seven', 'Eight', 'Nine', 'Ten']
2516 for digit in digits:
2517 d = digits.index (digit)
2518 id = re.sub ('%d' % d, digit, id)
2520 id = re.sub ('[^a-zA-Z]', 'X', id)
2521 return id
2523 def musicxml_pitch_to_lily (mxl_pitch):
2524 p = musicexp.Pitch ()
2525 p.alteration = mxl_pitch.get_alteration ()
2526 p.step = musicxml_step_to_lily (mxl_pitch.get_step ())
2527 p.octave = mxl_pitch.get_octave () - 4
2528 return p
2530 def musicxml_unpitched_to_lily (mxl_unpitched):
2531 p = None
2532 step = mxl_unpitched.get_step ()
2533 if step:
2534 p = musicexp.Pitch ()
2535 p.step = musicxml_step_to_lily (step)
2536 octave = mxl_unpitched.get_octave ()
2537 if octave and p:
2538 p.octave = octave - 4
2539 return p
2541 def musicxml_restdisplay_to_lily (mxl_rest):
2542 p = None
2543 step = mxl_rest.get_step ()
2544 if step:
2545 p = musicexp.Pitch ()
2546 p.step = musicxml_step_to_lily (step)
2547 octave = mxl_rest.get_octave ()
2548 if octave and p:
2549 p.octave = octave - 4
2550 return p
2552 def voices_in_part (part):
2553 """Return a Name -> Voice dictionary for PART"""
2554 part.interpret ()
2555 part.extract_voices ()
2556 voices = part.get_voices ()
2557 part_info = part.get_staff_attributes ()
2559 return (voices, part_info)
2561 def voices_in_part_in_parts (parts):
2562 """return a Part -> Name -> Voice dictionary"""
2563 # don't crash if p doesn't have an id (that's invalid MusicXML,
2564 # but such files are out in the wild!
2565 dictionary = {}
2566 for p in parts:
2567 voices = voices_in_part (p)
2568 if (hasattr (p, "id")):
2569 dictionary[p.id] = voices
2570 else:
2571 # TODO: extract correct part id from other sources
2572 dictionary[None] = voices
2573 return dictionary;
2576 def get_all_voices (parts):
2577 all_voices = voices_in_part_in_parts (parts)
2579 all_ly_voices = {}
2580 all_ly_staffinfo = {}
2581 for p, (name_voice, staff_info) in all_voices.items ():
2583 part_ly_voices = {}
2584 for n, v in name_voice.items ():
2585 progress (_ ("Converting to LilyPond expressions..."))
2586 # musicxml_voice_to_lily_voice returns (lily_voice, {nr->lyrics, nr->lyrics})
2587 part_ly_voices[n] = musicxml_voice_to_lily_voice (v)
2589 all_ly_voices[p] = part_ly_voices
2590 all_ly_staffinfo[p] = staff_info
2592 return (all_ly_voices, all_ly_staffinfo)
2595 def option_parser ():
2596 p = ly.get_option_parser (usage = _ ("musicxml2ly [OPTION]... FILE.xml"),
2597 description =
2598 _ ("""Convert MusicXML from FILE.xml to LilyPond input.
2599 If the given filename is -, musicxml2ly reads from the command line.
2600 """), add_help_option=False)
2602 p.add_option("-h", "--help",
2603 action="help",
2604 help=_ ("show this help and exit"))
2606 p.version = ('''%prog (LilyPond) @TOPLEVEL_VERSION@\n\n'''
2608 _ ("""Copyright (c) 2005--2009 by
2609 Han-Wen Nienhuys <hanwen@xs4all.nl>,
2610 Jan Nieuwenhuizen <janneke@gnu.org> and
2611 Reinhold Kainhofer <reinhold@kainhofer.com>
2615 This program is free software. It is covered by the GNU General Public
2616 License and you are welcome to change it and/or distribute copies of it
2617 under certain conditions. Invoke as `%s --warranty' for more
2618 information.""") % 'lilypond')
2620 p.add_option("--version",
2621 action="version",
2622 help=_ ("show version number and exit"))
2624 p.add_option ('-v', '--verbose',
2625 action = "store_true",
2626 dest = 'verbose',
2627 help = _ ("be verbose"))
2629 p.add_option ('', '--lxml',
2630 action = "store_true",
2631 default = False,
2632 dest = "use_lxml",
2633 help = _ ("use lxml.etree; uses less memory and cpu time"))
2635 p.add_option ('-z', '--compressed',
2636 action = "store_true",
2637 dest = 'compressed',
2638 default = False,
2639 help = _ ("input file is a zip-compressed MusicXML file"))
2641 p.add_option ('-r', '--relative',
2642 action = "store_true",
2643 default = True,
2644 dest = "relative",
2645 help = _ ("convert pitches in relative mode (default)"))
2647 p.add_option ('-a', '--absolute',
2648 action = "store_false",
2649 dest = "relative",
2650 help = _ ("convert pitches in absolute mode"))
2652 p.add_option ('-l', '--language',
2653 metavar = _ ("LANG"),
2654 action = "store",
2655 help = _ ("use a different language file 'LANG.ly' and corresponding pitch names, e.g. 'deutsch' for deutsch.ly"))
2657 p.add_option ('--nd', '--no-articulation-directions',
2658 action = "store_false",
2659 default = True,
2660 dest = "convert_directions",
2661 help = _ ("do not convert directions (^, _ or -) for articulations, dynamics, etc."))
2663 p.add_option ('--nrp', '--no-rest-positions',
2664 action = "store_false",
2665 default = True,
2666 dest = "convert_rest_positions",
2667 help = _ ("do not convert exact vertical positions of rests"))
2669 p.add_option ('--npl', '--no-page-layout',
2670 action = "store_false",
2671 default = True,
2672 dest = "convert_page_layout",
2673 help = _ ("do not convert the exact page layout and breaks"))
2675 p.add_option ('--no-beaming',
2676 action = "store_false",
2677 default = True,
2678 dest = "convert_beaming",
2679 help = _ ("do not convert beaming information, use lilypond's automatic beaming instead"))
2681 p.add_option ('-o', '--output',
2682 metavar = _ ("FILE"),
2683 action = "store",
2684 default = None,
2685 type = 'string',
2686 dest = 'output_name',
2687 help = _ ("set output filename to FILE, stdout if -"))
2688 p.add_option_group ('',
2689 description = (
2690 _ ("Report bugs via %s")
2691 % 'http://post.gmane.org/post.php'
2692 '?group=gmane.comp.gnu.lilypond.bugs') + '\n')
2693 return p
2695 def music_xml_voice_name_to_lily_name (part_id, name):
2696 str = "Part%sVoice%s" % (part_id, name)
2697 return musicxml_id_to_lily (str)
2699 def music_xml_lyrics_name_to_lily_name (part_id, name, lyricsnr):
2700 str = "Part%sVoice%sLyrics%s" % (part_id, name, lyricsnr)
2701 return musicxml_id_to_lily (str)
2703 def music_xml_figuredbass_name_to_lily_name (part_id, voicename):
2704 str = "Part%sVoice%sFiguredBass" % (part_id, voicename)
2705 return musicxml_id_to_lily (str)
2707 def music_xml_chordnames_name_to_lily_name (part_id, voicename):
2708 str = "Part%sVoice%sChords" % (part_id, voicename)
2709 return musicxml_id_to_lily (str)
2711 def print_voice_definitions (printer, part_list, voices):
2712 for part in part_list:
2713 part_id = part.id
2714 nv_dict = voices.get (part_id, {})
2715 for (name, voice) in nv_dict.items ():
2716 k = music_xml_voice_name_to_lily_name (part_id, name)
2717 printer.dump ('%s = ' % k)
2718 voice.ly_voice.print_ly (printer)
2719 printer.newline()
2720 if voice.chordnames:
2721 cnname = music_xml_chordnames_name_to_lily_name (part_id, name)
2722 printer.dump ('%s = ' % cnname )
2723 voice.chordnames.print_ly (printer)
2724 printer.newline()
2725 for l in voice.lyrics_order:
2726 lname = music_xml_lyrics_name_to_lily_name (part_id, name, l)
2727 printer.dump ('%s = ' % lname )
2728 voice.lyrics_dict[l].print_ly (printer)
2729 printer.newline()
2730 if voice.figured_bass:
2731 fbname = music_xml_figuredbass_name_to_lily_name (part_id, name)
2732 printer.dump ('%s = ' % fbname )
2733 voice.figured_bass.print_ly (printer)
2734 printer.newline()
2737 def uniq_list (l):
2738 return dict ([(elt,1) for elt in l]).keys ()
2740 # format the information about the staff in the form
2741 # [staffid,
2743 # [voiceid1, [lyricsid11, lyricsid12,...], figuredbassid1],
2744 # [voiceid2, [lyricsid21, lyricsid22,...], figuredbassid2],
2745 # ...
2748 # raw_voices is of the form [(voicename, lyricsids, havefiguredbass)*]
2749 def format_staff_info (part_id, staff_id, raw_voices):
2750 voices = []
2751 for (v, lyricsids, figured_bass, chordnames) in raw_voices:
2752 voice_name = music_xml_voice_name_to_lily_name (part_id, v)
2753 voice_lyrics = [music_xml_lyrics_name_to_lily_name (part_id, v, l)
2754 for l in lyricsids]
2755 figured_bass_name = ''
2756 if figured_bass:
2757 figured_bass_name = music_xml_figuredbass_name_to_lily_name (part_id, v)
2758 chordnames_name = ''
2759 if chordnames:
2760 chordnames_name = music_xml_chordnames_name_to_lily_name (part_id, v)
2761 voices.append ([voice_name, voice_lyrics, figured_bass_name, chordnames_name])
2762 return [staff_id, voices]
2764 def update_score_setup (score_structure, part_list, voices):
2766 for part_definition in part_list:
2767 part_id = part_definition.id
2768 nv_dict = voices.get (part_id)
2769 if not nv_dict:
2770 error_message (_ ('unknown part in part-list: %s') % part_id)
2771 continue
2773 staves = reduce (lambda x,y: x+ y,
2774 [voice.voicedata._staves.keys ()
2775 for voice in nv_dict.values ()],
2777 staves_info = []
2778 if len (staves) > 1:
2779 staves_info = []
2780 staves = uniq_list (staves)
2781 staves.sort ()
2782 for s in staves:
2783 thisstaff_raw_voices = [(voice_name, voice.lyrics_order, voice.figured_bass, voice.chordnames)
2784 for (voice_name, voice) in nv_dict.items ()
2785 if voice.voicedata._start_staff == s]
2786 staves_info.append (format_staff_info (part_id, s, thisstaff_raw_voices))
2787 else:
2788 thisstaff_raw_voices = [(voice_name, voice.lyrics_order, voice.figured_bass, voice.chordnames)
2789 for (voice_name, voice) in nv_dict.items ()]
2790 staves_info.append (format_staff_info (part_id, None, thisstaff_raw_voices))
2791 score_structure.set_part_information (part_id, staves_info)
2793 # Set global values in the \layout block, like auto-beaming etc.
2794 def update_layout_information ():
2795 if not conversion_settings.ignore_beaming and layout_information:
2796 layout_information.set_context_item ('Score', 'autoBeaming = ##f')
2798 def print_ly_preamble (printer, filename):
2799 printer.dump_version ()
2800 printer.print_verbatim ('%% automatically converted from %s\n' % filename)
2802 def print_ly_additional_definitions (printer, filename):
2803 if needed_additional_definitions:
2804 printer.newline ()
2805 printer.print_verbatim ('%% additional definitions required by the score:')
2806 printer.newline ()
2807 for a in set(needed_additional_definitions):
2808 printer.print_verbatim (additional_definitions.get (a, ''))
2809 printer.newline ()
2810 printer.newline ()
2812 # Read in the tree from the given I/O object (either file or string) and
2813 # demarshall it using the classes from the musicxml.py file
2814 def read_xml (io_object, use_lxml):
2815 if use_lxml:
2816 import lxml.etree
2817 tree = lxml.etree.parse (io_object)
2818 mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
2819 return mxl_tree
2820 else:
2821 from xml.dom import minidom, Node
2822 doc = minidom.parse(io_object)
2823 node = doc.documentElement
2824 return musicxml.minidom_demarshal_node (node)
2825 return None
2828 def read_musicxml (filename, compressed, use_lxml):
2829 raw_string = None
2830 if compressed:
2831 if filename == "-":
2832 progress (_ ("Input is compressed, extracting raw MusicXML data from stdin") )
2833 z = zipfile.ZipFile (sys.stdin)
2834 else:
2835 progress (_ ("Input file %s is compressed, extracting raw MusicXML data") % filename)
2836 z = zipfile.ZipFile (filename, "r")
2837 container_xml = z.read ("META-INF/container.xml")
2838 if not container_xml:
2839 return None
2840 container = read_xml (StringIO.StringIO (container_xml), use_lxml)
2841 if not container:
2842 return None
2843 rootfiles = container.get_maybe_exist_named_child ('rootfiles')
2844 if not rootfiles:
2845 return None
2846 rootfile_list = rootfiles.get_named_children ('rootfile')
2847 mxml_file = None
2848 if len (rootfile_list) > 0:
2849 mxml_file = getattr (rootfile_list[0], 'full-path', None)
2850 if mxml_file:
2851 raw_string = z.read (mxml_file)
2853 if raw_string:
2854 io_object = StringIO.StringIO (raw_string)
2855 elif filename == "-":
2856 io_object = sys.stdin
2857 else:
2858 io_object = filename
2860 return read_xml (io_object, use_lxml)
2863 def convert (filename, options):
2864 if filename == "-":
2865 progress (_ ("Reading MusicXML from Standard input ...") )
2866 else:
2867 progress (_ ("Reading MusicXML from %s ...") % filename)
2869 tree = read_musicxml (filename, options.compressed, options.use_lxml)
2870 score_information = extract_score_information (tree)
2871 paper_information = extract_paper_information (tree)
2873 parts = tree.get_typed_children (musicxml.Part)
2874 (voices, staff_info) = get_all_voices (parts)
2876 score = None
2877 mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
2878 if mxl_pl:
2879 score = extract_score_structure (mxl_pl, staff_info)
2880 part_list = mxl_pl.get_named_children ("score-part")
2882 # score information is contained in the <work>, <identification> or <movement-title> tags
2883 update_score_setup (score, part_list, voices)
2884 # After the conversion, update the list of settings for the \layout block
2885 update_layout_information ()
2887 if not options.output_name:
2888 options.output_name = os.path.basename (filename)
2889 options.output_name = os.path.splitext (options.output_name)[0]
2890 elif re.match (".*\.ly", options.output_name):
2891 options.output_name = os.path.splitext (options.output_name)[0]
2894 #defs_ly_name = options.output_name + '-defs.ly'
2895 if (options.output_name == "-"):
2896 output_ly_name = 'Standard output'
2897 else:
2898 output_ly_name = options.output_name + '.ly'
2900 progress (_ ("Output to `%s'") % output_ly_name)
2901 printer = musicexp.Output_printer()
2902 #progress (_ ("Output to `%s'") % defs_ly_name)
2903 if (options.output_name == "-"):
2904 printer.set_file (codecs.getwriter ("utf-8")(sys.stdout))
2905 else:
2906 printer.set_file (codecs.open (output_ly_name, 'wb', encoding='utf-8'))
2907 print_ly_preamble (printer, filename)
2908 print_ly_additional_definitions (printer, filename)
2909 if score_information:
2910 score_information.print_ly (printer)
2911 if paper_information and conversion_settings.convert_page_layout:
2912 paper_information.print_ly (printer)
2913 if layout_information:
2914 layout_information.print_ly (printer)
2915 print_voice_definitions (printer, part_list, voices)
2917 printer.newline ()
2918 printer.dump ("% The score definition")
2919 printer.newline ()
2920 score.print_ly (printer)
2921 printer.newline ()
2923 return voices
2925 def get_existing_filename_with_extension (filename, ext):
2926 if os.path.exists (filename):
2927 return filename
2928 newfilename = filename + "." + ext
2929 if os.path.exists (newfilename):
2930 return newfilename;
2931 newfilename = filename + ext
2932 if os.path.exists (newfilename):
2933 return newfilename;
2934 return ''
2936 def main ():
2937 opt_parser = option_parser()
2939 global options
2940 (options, args) = opt_parser.parse_args ()
2941 if not args:
2942 opt_parser.print_usage()
2943 sys.exit (2)
2945 if options.language:
2946 musicexp.set_pitch_language (options.language)
2947 needed_additional_definitions.append (options.language)
2948 additional_definitions[options.language] = "\\include \"%s.ly\"\n" % options.language
2949 conversion_settings.ignore_beaming = not options.convert_beaming
2950 conversion_settings.convert_page_layout = options.convert_page_layout
2952 # Allow the user to leave out the .xml or xml on the filename
2953 basefilename = args[0].decode('utf-8')
2954 if basefilename == "-": # Read from stdin
2955 basefilename = "-"
2956 else:
2957 filename = get_existing_filename_with_extension (basefilename, "xml")
2958 if not filename:
2959 filename = get_existing_filename_with_extension (basefilename, "mxl")
2960 options.compressed = True
2961 if filename and filename.endswith ("mxl"):
2962 options.compressed = True
2964 if filename and (filename == "-" or os.path.exists (filename)):
2965 voices = convert (filename, options)
2966 else:
2967 progress (_ ("Unable to find input file %s") % basefilename)
2969 if __name__ == '__main__':
2970 main()