3 # once upon a rainy monday afternoon.
8 # ABC standard v1.6: http://www.gre.ac.uk/~c.walshaw/abc2mtex/abc.txt
10 # Enhancements (Roy R. Rankin)
12 # Header section moved to top of lilypond file
13 # handle treble, treble-8, alto, and bass clef
14 # Handle voices (V: headers) with clef and part names, multiple voices
15 # Handle w: lyrics with multiple verses
16 # Handle key mode names for minor, major, phrygian, ionian, locrian, aeolian,
17 # mixolydian, lydian, dorian
18 # Handle part names from V: header
19 # Tuplets handling fixed up
20 # Lines starting with |: not discarded as header lines
21 # Multiple T: and C: header entries handled
22 # Accidental maintained until next bar check
23 # Silent rests supported
24 # articulations fermata, upbow, downbow, ltoe, accent, tenuto supported
25 # Chord strings([-^]"string") can contain a '#'
26 # Header fields enclosed by [] in notes string processed
27 # W: words output after tune as abc2ps does it (they failed before)
31 # Multiple tunes in single file not supported
32 # Blank T: header lines should write score and open a new score
33 # Not all header fields supported
34 # Beaming not preserved between ABC and lilypond
35 # ABC line breaks are ignored
36 # Block comments generate error and are ignored
37 # Postscript commands are ignored
38 # lyrics not resynchronized by line breaks (lyrics must fully match notes)
48 program_name = 'abc2ly'
49 version = '@TOPLEVEL_VERSION@'
50 if version == '@' + 'TOPLEVEL_VERSION' + '@':
51 version = '(unknown version)' # uGUHGUHGHGUGH
69 current_voice_idx = -1
70 current_lyric_idx = -1
74 global_key = [0] * 7 # UGH
75 names = ["One", "Two", "Three"]
83 if re.match('^treble', s):
85 if re.match ('^-8', s):
87 state.base_octave = -2
88 voices_append("\\clef \"G_8\";\n")
91 voices_append("\\clef treble;\n")
92 elif re.match('^alto', s):
94 state.base_octave = -1
95 voices_append ("\\clef alto;\n" )
96 elif re.match('^bass',s ):
98 state.base_octave = -2
99 voices_append ("\\clef bass;\n" )
102 def select_voice (name, rol):
103 if not voice_idx_dict.has_key (name):
104 state_list.append(Parser_state())
107 voice_idx_dict[name] = len (voices) -1
108 __main__.current_voice_idx = voice_idx_dict[name]
109 __main__.state = state_list[current_voice_idx]
111 m = re.match ('^([^ \t=]*)=(.*)$', rol) # find keywork
115 a = re.match ('^("[^"]*"|[^ \t]*) *(.*)$', rol)
119 if keyword == 'clef':
121 elif keyword == "name":
122 value = re.sub ('\\\\','\\\\\\\\', value)
123 voices_append ("\\property Staff.instrument = %s\n" % value )
124 __main__.part_names = 1
125 elif keyword == "sname" or keyword == "snm":
126 voices_append ("\\property Staff.instr = %s\n" % value )
134 def dump_header (outf,hdr):
135 outf.write ('\\header {\n')
139 outf.write ('\t%s = "%s";\n'% (k,hdr[k]))
142 def dump_lyrics (outf):
144 outf.write("\n\\score\n{\n \\context Lyrics\n <\n")
145 for i in range (len (lyrics)):
146 outf.write ( lyrics [i])
148 outf.write(" >\n \\paper{}\n}\n")
150 def dump_slyrics (outf):
151 ks = voice_idx_dict.keys()
154 for i in range (len(slyrics[voice_idx_dict[k]])):
155 outf.write ("\nwords%sV%d = \\lyrics {" % (k, i))
156 outf.write ("\n" + slyrics [voice_idx_dict[k]][i])
159 def dump_voices (outf):
160 ks = voice_idx_dict.keys()
163 outf.write ("\nvoice%s = \\notes {" % k)
164 outf.write ("\n" + voices [voice_idx_dict[k]])
167 def dump_score (outf):
168 outf.write (r"""\score{
172 ks = voice_idx_dict.keys ();
175 if k == 'default' and len (voice_idx_dict) > 1:
177 if len ( slyrics [voice_idx_dict[k]] ):
178 outf.write ("\n \\addlyrics")
179 outf.write ("\n\t\\context Staff=\"%s\"\n\t{\n" %k )
181 outf.write ("\t \\$voicedefault\n")
182 outf.write ("\t \\$voice%s " % k)
183 outf.write ("\n\t}\n")
184 if len ( slyrics [voice_idx_dict[k]] ):
185 outf.write ("\n\t\\context Lyrics=\"%s\" \n\t<\t" % k)
186 for i in range (len(slyrics[voice_idx_dict[k]])):
187 outf.write("\n\t { \\$words%sV%d }" % ( k, i) )
188 outf.write ( "\n\t>\n" )
190 outf.write ("\n\t\\paper {\n")
192 outf.write ("\t \\translator \n\t {\n")
193 outf.write ("\t\t\\StaffContext\n")
194 outf.write ("\t\t\\consists Staff_margin_engraver;\n")
195 outf.write ("\t }\n")
196 outf.write ("\t}\n\t\\midi {}\n}\n")
200 def set_default_length (s):
201 m = re.search ('1/([0-9]+)', s)
203 __main__.default_len = string.atoi ( m.group (1))
205 def set_default_len_from_time_sig (s):
206 m = re.search ('([0-9]+)/([0-9]+)', s)
208 n = string.atoi (m.group (1))
209 d = string.atoi (m.group (2))
210 if (n * 1.0 )/(d * 1.0) < 0.75:
211 __main__.default_len = 16
213 __main__.default_len = 8
222 sys.stderr.write ("can't open file: %s\n" % f)
226 sys.stderr.write ("gulped emty file: %s\n" % f)
231 # pitch manipulation. Tuples are (name, alteration).
232 # 0 is (central) C. Alteration -1 is a flat, Alteration +1 is a sharp
233 # pitch in semitones.
234 def semitone_pitch (tup):
244 p = p + t* 2 + tup[1]
247 def fifth_above_pitch (tup):
248 (n, a) = (tup[0] + 4, tup[1])
250 difference = 7 - (semitone_pitch ((n,a)) - semitone_pitch (tup))
261 (t,a) = fifth_above_pitch (p)
262 if semitone_pitch((t,a)) % 12 == 0:
274 (t,a) = quart_above_pitch (p)
275 if semitone_pitch((t,a)) % 12 == 0:
281 def quart_above_pitch (tup):
282 (n, a) = (tup[0] + 3, tup[1])
284 difference = 5 - (semitone_pitch ((n,a)) - semitone_pitch (tup))
289 key_lookup = { # abc to lilypond key mode names
297 'mix' : 'mixolydian',
306 if k and k[0] == '#':
309 elif k and k[0] == 'b':
316 if key_lookup.has_key(type):
317 return("%s \\%s" % ( key, key_lookup[type]))
318 sys.stderr.write("Unknown key type %s ignored\n" % type)
321 def shift_key (note, acc , shift):
322 s = semitone_pitch((note, acc))
323 s = (s + shift + 12) % 12
335 key_shift = { # semitone shifts for key mode names
349 intkey = (ord (k[0]) - ord('a') + 5) % 7
353 if k and k[0] == 'b':
356 elif k and k[0] == '#':
360 if k and key_shift.has_key(k):
361 (intkey, intkeyacc) = shift_key(intkey, intkeyacc, key_shift[k])
362 keytup = (intkey, intkeyacc)
364 sharp_key_seq = sharp_keys ()
365 flat_key_seq = flat_keys ()
369 if keytup in sharp_key_seq:
371 key_count = sharp_key_seq.index (keytup)
372 accseq = map (lambda x: (4*x -1 ) % 7, range (1, key_count + 1))
374 elif keytup in flat_key_seq:
376 key_count = flat_key_seq.index (keytup)
377 accseq = map (lambda x: (3*x + 3 ) % 7, range (1, key_count + 1))
383 key_table[a] = key_table[a] + accsign
398 def try_parse_tuplet_begin (str, state):
399 if re.match ('\([2-9]', str):
402 state.parsing_tuplet = string.atoi (dig[0])
404 voices_append ("\\times %s {" % tup_lookup[dig])
407 def try_parse_group_end (str, state):
408 if str and str[0] in HSPACE:
412 def header_append (key, a):
414 if header.has_key (key):
415 s = header[key] + "\n"
419 linelen = len (v) - string.rfind(v, '\n')
420 if linelen + len (a) > 80:
424 def stuff_append (stuff, idx, a):
428 stuff [idx] = wordwrap(a, stuff[idx])
432 def voices_append(a):
433 if current_voice_idx < 0:
434 select_voice ('default', '')
436 stuff_append (voices, current_voice_idx, a)
438 def lyrics_append(a):
439 a = re.sub ( '#', '\\#', a) # latex does not like naked #'s
440 a = re.sub ( '"', '\\"', a) # latex does not like naked "'s
441 a = '\t{ \\lyrics "' + a + '" }\n'
442 stuff_append (lyrics, current_lyric_idx, a)
444 # break lyrics to words and put "'s around words containing numbers and '"'s
449 m = re.match('[ \t]*([^ \t]*)[ \t]*(.*$)', str)
453 word = re.sub('"', '\\"', word) # escape "
454 if re.match('.*[0-9"]', word):
455 word = re.sub('_', ' ', word) # _ causes probs inside ""
456 ret = ret + '\"' + word + '\" '
458 ret = ret + word + ' '
463 def slyrics_append(a):
464 a = re.sub ( '_', ' _ ', a) # _ to ' _ '
465 a = re.sub ( '-', '- ', a) # split words with -
466 a = re.sub ( '\\\\- ', '-', a) # unless \-
467 a = re.sub ( '~', '_', a) # ~ to space('_')
468 a = re.sub ( '\*', '_ ', a) # * to to space
469 a = re.sub ( '#', '\\#', a) # latex does not like naked #'s
470 if re.match('.*[0-9"]', a): # put numbers and " into quoted string
472 a = re.sub ( '$', ' ', a) # insure space between lines
473 __main__.lyric_idx = lyric_idx + 1
474 if len(slyrics[current_voice_idx]) <= lyric_idx:
475 slyrics[current_voice_idx].append(a)
477 v = slyrics[current_voice_idx][lyric_idx]
478 slyrics[current_voice_idx][lyric_idx] = wordwrap(a, slyrics[current_voice_idx][lyric_idx])
481 def try_parse_header_line (ln, state):
482 m = re.match ('^([A-Za-z]): *(.*)$', ln)
488 a = re.sub('[ \t]*$','', a) #strip trailing blanks
489 if header.has_key('title'):
491 header['title'] = header['title'] + '\\\\\\\\' + a
496 if not state.common_time:
497 state.common_time = 1
498 voices_append ("\\property Staff.timeSignatureStyle=\"C\"\n")
501 if not state.common_time:
502 state.common_time = 1
503 voices_append ("\\property Staff.timeSignatureStyle=\"C\"\n")
505 # global_voice_stuff.append ('\\time %s;' % a)
506 set_default_len_from_time_sig (a)
507 voices_append ('\\time %s;' % a)
512 m = re.match ('^([^ \t]*) *(.*)$', a) # seperate clef info
514 __main__.global_key =compute_key (m.group(1))# ugh.
515 voices_append ('\\key %s;' % lily_key(m.group(1)))
516 check_clef(m.group(2))
518 __main__.global_key =compute_key (a)# ugh.
519 voices_append ('\\key %s;' % lily_key(a))
520 if g == 'O': # Origin
521 header ['origin'] = a
522 if g == 'X': # Reference Number
523 header ['crossRefNumber'] = a
526 if g == 'H': # History
527 header_append ('history', a)
530 if g == 'C': # Composer
531 if header.has_key('composer'):
533 header['composer'] = header['composer'] + '\\\\\\\\' + a
535 header['composer'] = a
537 header ['subtitle'] = a
538 if g == 'L': # Default note length
539 set_default_length (ln)
541 voice = re.sub (' .*$', '', a)
542 rest = re.sub ('^[^ \t]* *', '', a)
544 voices_append(state.next_bar)
546 select_voice (voice, rest)
549 if g == 'w': # vocals
555 # we use in this order specified accidental, active accidental for bar,
556 # active accidental for key
557 def pitch_to_mudela_name (name, acc, bar_acc, key):
570 return(chr (name + ord('c')) + s)
573 def octave_to_mudela_quotes (o):
586 while str and str[0] in DIGITS:
587 durstr = durstr + str[0]
592 n =string.atoi (durstr)
596 def duration_to_mudela_duration (multiply_tup, defaultlen, dots):
599 # (num / den) / defaultlen < 1/base
600 while base * multiply_tup[0] < multiply_tup[1]:
604 return '%d%s' % ( base, '.'* dots)
609 self.next_articulation = ''
613 self.parsing_tuplet = 0
620 # return (str, num,den,dots)
621 def parse_duration (str, parser_state):
623 den = parser_state.next_den
624 parser_state.next_den = 1
626 (str, num) = parse_num (str)
631 while str[:1] == '/':
635 (str, d) =parse_num (str)
639 den = den * default_len
641 current_dots = parser_state.next_dots
642 parser_state.next_dots = 0
643 if re.match ('[ \t]*[<>]', str):
644 while str[0] in HSPACE:
648 current_dots = current_dots + 1;
649 parser_state.next_den = parser_state.next_den * 2
654 parser_state.next_dots = parser_state.next_dots + 1
662 if num % multiplier == 0 and den % f == 0:
663 num = num / multiplier
665 current_dots = current_dots + d
667 return (str, num,den,current_dots)
670 def try_parse_rest (str, parser_state):
671 if not str or str[0] <> 'z' and str[0] <> 'x':
674 __main__.lyric_idx = -1
676 if parser_state.next_bar:
677 voices_append(parser_state.next_bar)
678 parser_state.next_bar = ''
686 (str, num,den,d) = parse_duration (str, parser_state)
687 voices_append ('%s%s' % (rest, duration_to_mudela_duration ((num,den), default_len, d)))
688 if parser_state.next_articulation:
689 voices_append (parser_state.next_articulation)
690 parser_state.next_articulation = ''
703 'J' : '', # ignore slide
704 'R' : '', # ignore roll
708 def try_parse_articulation (str, state):
710 while str and artic_tbl.has_key(str[:1]):
711 state.next_articulation = state.next_articulation + artic_tbl[str[:1]]
712 if not artic_tbl[str[:1]]:
713 sys.stderr.write("Warning: ignoring %s\n" % str[:1] )
719 # s7m2 input doesnt care about spaces
720 if re.match('[ \t]*\(', str):
721 str = string.lstrip (str)
724 while str[:1] =='(' and str[1] not in DIGITS:
725 slur_begin = slur_begin + 1
726 state.next_articulation = state.next_articulation + '('
732 # remember accidental for rest of bar
734 def set_bar_acc(note, octave, acc, state):
737 n_oct = note + octave * 7
738 state.in_acc[n_oct] = acc
740 # get accidental set in this bar or UNDEF if not set
741 def get_bar_acc(note, octave, state):
742 n_oct = note + octave * 7
743 if state.in_acc.has_key(n_oct):
744 return(state.in_acc[n_oct])
748 def clear_bar_acc(state):
749 for k in state.in_acc.keys():
754 # WAT IS ABC EEN ONTZETTENDE PROGRAMMEERPOEP !
755 def try_parse_note (str, parser_state):
774 octave = parser_state.base_octave
775 if str[0] in "ABCDEFG":
776 str = string.lower (str[0]) + str[1:]
781 if str[0] in "abcdefg":
782 notename = (ord(str[0]) - ord('a') + 5)%7
785 return str # failed; not a note!
788 __main__.lyric_idx = -1
790 if parser_state.next_bar:
791 voices_append(parser_state.next_bar)
792 parser_state.next_bar = ''
797 while str[0] == '\'':
801 (str, num,den,current_dots) = parse_duration (str, parser_state)
804 if re.match('[ \t]*\)', str):
805 str = string.lstrip (str)
809 slur_end = slur_end + 1
814 voices_append ('%s' % ')' *slur_end )
816 bar_acc = get_bar_acc(notename, octave, parser_state)
817 pit = pitch_to_mudela_name(notename, acc, bar_acc, global_key[notename])
818 oct = octave_to_mudela_quotes (octave)
819 if acc != UNDEF and (acc == global_key[notename] or acc == bar_acc):
823 voices_append ("%s%s%s%s" %
825 duration_to_mudela_duration ((num,den), default_len, current_dots)))
827 set_bar_acc(notename, octave, acc, parser_state)
828 if parser_state.next_articulation:
829 articulation = articulation + parser_state.next_articulation
830 parser_state.next_articulation = ''
832 voices_append (articulation)
834 if parser_state.parsing_tuplet:
835 parser_state.parsing_tuplet = parser_state.parsing_tuplet - 1
836 if not parser_state.parsing_tuplet:
839 voices_append ('%s' % '(' * slur_begin )
844 def junk_space (str):
845 while str and str[0] in '\t\n ':
851 def try_parse_guitar_chord (str, state):
855 while str and str[0] != '"':
861 gc = re.sub('#', '\\#', gc) # escape '#'s
862 state.next_articulation = ("-\"%s\"" % gc) + state.next_articulation
865 def try_parse_escape (str):
866 if not str or str [0] != '\\':
871 key_table = compute_key ()
875 # |] thin-thick double bar line
876 # || thin-thin double bar line
877 # [| thick-thin double bar line
880 # :: left-right repeat
896 warn_about = ['|:', '::', ':|', '|1', ':|2', '|2']
898 def try_parse_bar (str,state):
901 # first try the longer one
903 if str[:trylen] and bar_dict.has_key (str[:trylen]):
905 bs = "\\bar \"%s\";" % bar_dict[s]
907 sys.stderr.write('Warning kludging for barline `%s\'\n' % s)
912 state.next_bar = '|\n'
916 if bs <> None or state.next_bar != '':
917 if state.parsing_tuplet:
918 state.parsing_tuplet =0
927 def try_parse_tie (str):
930 voices_append (' ~ ')
933 def bracket_escape (str, state):
934 m = re.match ( '^([^\]]*)] *(.*)$', str)
938 try_parse_header_line (cmd, state)
941 def try_parse_chord_delims (str, state):
944 if re.match('[A-Z]:', str): # bracket escape
945 return bracket_escape(str, state)
947 voices_append(state.next_bar)
958 voices_append(state.next_bar)
974 voices_append ("\\spanrequest \\stop \"slur\"" * end);
978 def try_parse_grace_delims (str, state):
981 voices_append(state.next_bar)
984 voices_append ('\\grace { ')
998 select_voice('default', '')
1000 sys.stderr.write ("Line ... ")
1002 __main__.state = state_list[current_voice_idx]
1007 if not (lineno % happy_count):
1008 sys.stderr.write ('[%d]'% lineno)
1010 m = re.match ('^([^%]*)%(.*)$',ln) # add comments to current voice
1013 voices_append ('%% %s\n' % m.group(2))
1018 ln = try_parse_header_line (ln, state)
1020 # Try nibbling characters off until the line doesn't change.
1022 while ln != prev_ln:
1024 ln = try_parse_chord_delims (ln, state)
1025 ln = try_parse_rest (ln, state)
1026 ln = try_parse_articulation (ln,state)
1027 ln = try_parse_note (ln, state)
1028 ln = try_parse_bar (ln, state)
1029 ln = try_parse_tie (ln)
1030 ln = try_parse_escape (ln)
1031 ln = try_parse_guitar_chord (ln, state)
1032 ln = try_parse_tuplet_begin (ln, state)
1033 ln = try_parse_group_end (ln, state)
1034 ln = try_parse_grace_delims (ln, state)
1035 ln = junk_space (ln)
1038 msg = "%s: %d: Huh? Don't understand\n" % (fn, lineno)
1039 sys.stderr.write (msg)
1040 left = orig_ln[0:-len (ln)]
1041 sys.stderr.write (left + '\n')
1042 sys.stderr.write (' ' * len (left) + ln + '\n')
1046 sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
1050 Convert ABC to Mudela.
1052 Usage: abc2ly [OPTION]... ABC-FILE
1055 -h, --help this help
1056 -o, --output=FILE set output filename to FILE
1057 -v, --version version information
1060 def print_version ():
1061 print r"""abc2ly (GNU lilypond) %s""" % version
1065 (options, files) = getopt.getopt (sys.argv[1:], 'vo:h', ['help','version', 'output='])
1071 if o== '--help' or o == '-h':
1074 if o == '--version' or o == '-v':
1078 if o == '--output' or o == '-o':
1086 header['tagline'] = 'Lily was here %s -- automatically converted from ABC' % version
1091 sys.stderr.write ('Parsing... [%s]\n' % f)
1094 if not out_filename:
1095 out_filename = os.path.basename (os.path.splitext (f)[0]) + ".ly"
1096 sys.stderr.write ('Ly output to: %s...' % out_filename)
1097 outf = open (out_filename, 'w')
1099 # dump_global (outf)
1100 dump_header (outf ,header)
1105 sys.stderr.write ('\n')