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)
29 # Enhancements (Laura Conrad)
31 # Barring now preserved between ABC and lilypond
32 # the default placement for text in abc is above the staff.
37 # Multiple tunes in single file not supported
38 # Blank T: header lines should write score and open a new score
39 # Not all header fields supported
40 # ABC line breaks are ignored
41 # Block comments generate error and are ignored
42 # Postscript commands are ignored
43 # lyrics not resynchronized by line breaks (lyrics must fully match notes)
53 program_name = 'abc2ly'
54 version = '@TOPLEVEL_VERSION@'
55 if version == '@' + 'TOPLEVEL_VERSION' + '@':
56 version = '(unknown version)' # uGUHGUHGHGUGH
74 current_voice_idx = -1
75 current_lyric_idx = -1
81 global_key = [0] * 7 # UGH
82 names = ["One", "Two", "Three"]
90 if re.match('^treble', s):
92 if re.match ('^-8', s):
94 state.base_octave = -2
95 voices_append("\\clef \"G_8\";\n")
98 voices_append("\\clef treble;\n")
99 elif re.match('^-8va', s):
101 state.base_octave = -1
102 voices_append("\\clef \"G_8\";\n")
103 elif re.match('^alto', s):
105 state.base_octave = -1
106 voices_append ("\\clef alto;\n" )
107 elif re.match('^bass',s ):
109 state.base_octave = -2
110 voices_append ("\\clef bass;\n" )
113 def select_voice (name, rol):
114 if not voice_idx_dict.has_key (name):
115 state_list.append(Parser_state())
118 voice_idx_dict[name] = len (voices) -1
119 __main__.current_voice_idx = voice_idx_dict[name]
120 __main__.state = state_list[current_voice_idx]
122 m = re.match ('^([^ \t=]*)=(.*)$', rol) # find keywork
126 a = re.match ('^("[^"]*"|[^ \t]*) *(.*)$', rol)
130 if keyword == 'clef':
132 elif keyword == "name":
133 value = re.sub ('\\\\','\\\\\\\\', value)
134 voices_append ("\\property Staff.instrument = %s\n" % value )
135 __main__.part_names = 1
136 elif keyword == "sname" or keyword == "snm":
137 voices_append ("\\property Staff.instr = %s\n" % value )
145 def dump_header (outf,hdr):
146 outf.write ('\\header {\n')
150 outf.write ('\t%s = "%s";\n'% (k,hdr[k]))
153 def dump_lyrics (outf):
155 outf.write("\n\\score\n{\n \\context Lyrics\n <\n")
156 for i in range (len (lyrics)):
157 outf.write ( lyrics [i])
159 outf.write(" >\n \\paper{}\n}\n")
161 def dump_default_bar (outf):
162 outf.write ("\n\\property Score.defaultBarType=\"empty\"\n")
165 def dump_slyrics (outf):
166 ks = voice_idx_dict.keys()
169 for i in range (len(slyrics[voice_idx_dict[k]])):
170 outf.write ("\nwords%sV%d = \\lyrics {" % (k, i))
171 outf.write ("\n" + slyrics [voice_idx_dict[k]][i])
174 def dump_voices (outf):
175 ks = voice_idx_dict.keys()
178 outf.write ("\nvoice%s = \\notes {" % k)
179 dump_default_bar(outf)
180 outf.write ("\n" + voices [voice_idx_dict[k]])
183 def dump_score (outf):
184 outf.write (r"""\score{
188 ks = voice_idx_dict.keys ();
191 if k == 'default' and len (voice_idx_dict) > 1:
193 if len ( slyrics [voice_idx_dict[k]] ):
194 outf.write ("\n \\addlyrics")
195 outf.write ("\n\t\\context Staff=\"%s\"\n\t{\n" %k )
197 outf.write ("\t \\$voicedefault\n")
198 outf.write ("\t \\$voice%s " % k)
199 outf.write ("\n\t}\n")
200 if len ( slyrics [voice_idx_dict[k]] ):
201 outf.write ("\n\t\\context Lyrics=\"%s\" \n\t<\t" % k)
202 for i in range (len(slyrics[voice_idx_dict[k]])):
203 outf.write("\n\t { \\$words%sV%d }" % ( k, i) )
204 outf.write ( "\n\t>\n" )
206 outf.write ("\n\t\\paper {\n")
208 outf.write ("\t \\translator \n\t {\n")
209 outf.write ("\t\t\\StaffContext\n")
210 outf.write ("\t\t\\consists Staff_margin_engraver;\n")
211 outf.write ("\t }\n")
212 outf.write ("\t}\n\t\\midi {}\n}\n")
216 def set_default_length (s):
217 global length_specified
218 m = re.search ('1/([0-9]+)', s)
220 __main__.default_len = string.atoi ( m.group (1))
223 def set_default_len_from_time_sig (s):
224 m = re.search ('([0-9]+)/([0-9]+)', s)
226 n = string.atoi (m.group (1))
227 d = string.atoi (m.group (2))
228 if (n * 1.0 )/(d * 1.0) < 0.75:
229 __main__.default_len = 16
231 __main__.default_len = 8
240 sys.stderr.write ("can't open file: %s\n" % f)
244 sys.stderr.write ("gulped empty file: %s\n" % f)
249 # pitch manipulation. Tuples are (name, alteration).
250 # 0 is (central) C. Alteration -1 is a flat, Alteration +1 is a sharp
251 # pitch in semitones.
252 def semitone_pitch (tup):
262 p = p + t* 2 + tup[1]
265 def fifth_above_pitch (tup):
266 (n, a) = (tup[0] + 4, tup[1])
268 difference = 7 - (semitone_pitch ((n,a)) - semitone_pitch (tup))
279 (t,a) = fifth_above_pitch (p)
280 if semitone_pitch((t,a)) % 12 == 0:
292 (t,a) = quart_above_pitch (p)
293 if semitone_pitch((t,a)) % 12 == 0:
299 def quart_above_pitch (tup):
300 (n, a) = (tup[0] + 3, tup[1])
302 difference = 5 - (semitone_pitch ((n,a)) - semitone_pitch (tup))
307 key_lookup = { # abc to lilypond key mode names
315 'mix' : 'mixolydian',
324 if k and k[0] == '#':
327 elif k and k[0] == 'b':
331 return '%s \\major' % key
334 if key_lookup.has_key(type):
335 return("%s \\%s" % ( key, key_lookup[type]))
336 sys.stderr.write("Unknown key type %s ignored\n" % type)
339 def shift_key (note, acc , shift):
340 s = semitone_pitch((note, acc))
341 s = (s + shift + 12) % 12
353 key_shift = { # semitone shifts for key mode names
367 intkey = (ord (k[0]) - ord('a') + 5) % 7
371 if k and k[0] == 'b':
374 elif k and k[0] == '#':
378 if k and key_shift.has_key(k):
379 (intkey, intkeyacc) = shift_key(intkey, intkeyacc, key_shift[k])
380 keytup = (intkey, intkeyacc)
382 sharp_key_seq = sharp_keys ()
383 flat_key_seq = flat_keys ()
387 if keytup in sharp_key_seq:
389 key_count = sharp_key_seq.index (keytup)
390 accseq = map (lambda x: (4*x -1 ) % 7, range (1, key_count + 1))
392 elif keytup in flat_key_seq:
394 key_count = flat_key_seq.index (keytup)
395 accseq = map (lambda x: (3*x + 3 ) % 7, range (1, key_count + 1))
401 key_table[a] = key_table[a] + accsign
416 def try_parse_tuplet_begin (str, state):
417 if re.match ('\([2-9]', str):
420 state.parsing_tuplet = string.atoi (dig[0])
422 voices_append ("\\times %s {" % tup_lookup[dig])
425 def try_parse_group_end (str, state):
426 if str and str[0] in HSPACE:
430 def header_append (key, a):
432 if header.has_key (key):
433 s = header[key] + "\n"
437 linelen = len (v) - string.rfind(v, '\n')
438 if linelen + len (a) > 80:
442 def stuff_append (stuff, idx, a):
446 stuff [idx] = wordwrap(a, stuff[idx])
450 def voices_append(a):
451 if current_voice_idx < 0:
452 select_voice ('default', '')
454 stuff_append (voices, current_voice_idx, a)
456 def lyrics_append(a):
457 a = re.sub ( '#', '\\#', a) # latex does not like naked #'s
458 a = re.sub ( '"', '\\"', a) # latex does not like naked "'s
459 a = '\t{ \\lyrics "' + a + '" }\n'
460 stuff_append (lyrics, current_lyric_idx, a)
462 # break lyrics to words and put "'s around words containing numbers and '"'s
467 m = re.match('[ \t]*([^ \t]*)[ \t]*(.*$)', str)
471 word = re.sub('"', '\\"', word) # escape "
472 if re.match('.*[0-9"]', word):
473 word = re.sub('_', ' ', word) # _ causes probs inside ""
474 ret = ret + '\"' + word + '\" '
476 ret = ret + word + ' '
481 def slyrics_append(a):
482 a = re.sub ( '_', ' _ ', a) # _ to ' _ '
483 a = re.sub ( '-', '- ', a) # split words with -
484 a = re.sub ( '\\\\- ', '-', a) # unless \-
485 a = re.sub ( '~', '_', a) # ~ to space('_')
486 a = re.sub ( '\*', '_ ', a) # * to to space
487 a = re.sub ( '#', '\\#', a) # latex does not like naked #'s
488 if re.match('.*[0-9"]', a): # put numbers and " into quoted string
490 a = re.sub ( '$', ' ', a) # insure space between lines
491 __main__.lyric_idx = lyric_idx + 1
492 if len(slyrics[current_voice_idx]) <= lyric_idx:
493 slyrics[current_voice_idx].append(a)
495 v = slyrics[current_voice_idx][lyric_idx]
496 slyrics[current_voice_idx][lyric_idx] = wordwrap(a, slyrics[current_voice_idx][lyric_idx])
499 def try_parse_header_line (ln, state):
500 global length_specified
501 m = re.match ('^([A-Za-z]): *(.*)$', ln)
507 a = re.sub('[ \t]*$','', a) #strip trailing blanks
508 if header.has_key('title'):
510 header['title'] = header['title'] + '\\\\\\\\' + a
515 if not state.common_time:
516 state.common_time = 1
517 voices_append ("\\property Staff.TimeSignature \push #\'style = #\"C\"\n")
520 if not state.common_time:
521 state.common_time = 1
522 voices_append ("\\property Staff.TimeSignature \push #\'style = #\"C\"\n")
524 if not length_specified:
525 set_default_len_from_time_sig (a)
528 voices_append ('\\time %s;' % a)
533 m = re.match ('^([^ \t]*) *(.*)$', a) # seperate clef info
535 # there may or may not be a space
536 # between the key letter and the mode
537 if key_lookup.has_key(m.group(2)[0:3]):
538 key_info = m.group(1) + m.group(2)[0:3]
539 clef_info = m.group(2)[4:]
541 key_info = m.group(1)
542 clef_info = m.group(2)
543 __main__.global_key = compute_key (key_info)# ugh.
544 voices_append ('\\key %s;' % lily_key(key_info))
545 check_clef(clef_info)
547 __main__.global_key = compute_key (a)# ugh.
548 voices_append ('\\key %s \\major;' % lily_key(a))
549 if g == 'O': # Origin
550 header ['origin'] = a
551 if g == 'X': # Reference Number
552 header ['crossRefNumber'] = a
555 if g == 'H': # History
556 header_append ('history', a)
559 if g == 'C': # Composer
560 if header.has_key('composer'):
562 header['composer'] = header['composer'] + '\\\\\\\\' + a
564 header['composer'] = a
566 header ['subtitle'] = a
567 if g == 'L': # Default note length
568 set_default_length (ln)
570 voice = re.sub (' .*$', '', a)
571 rest = re.sub ('^[^ \t]* *', '', a)
573 voices_append(state.next_bar)
575 select_voice (voice, rest)
578 if g == 'w': # vocals
584 # we use in this order specified accidental, active accidental for bar,
585 # active accidental for key
586 def pitch_to_mudela_name (name, acc, bar_acc, key):
600 return(chr (name + ord('c')) + s)
603 def octave_to_mudela_quotes (o):
616 while str and str[0] in DIGITS:
617 durstr = durstr + str[0]
622 n =string.atoi (durstr)
626 def duration_to_mudela_duration (multiply_tup, defaultlen, dots):
628 # (num / den) / defaultlen < 1/base
629 while base * multiply_tup[0] < multiply_tup[1]:
631 return '%d%s' % ( base, '.'* dots)
636 self.next_articulation = ''
640 self.parsing_tuplet = 0
647 # return (str, num,den,dots)
648 def parse_duration (str, parser_state):
650 den = parser_state.next_den
651 parser_state.next_den = 1
653 (str, num) = parse_num (str)
658 while str[:1] == '/':
662 (str, d) =parse_num (str)
666 den = den * default_len
668 current_dots = parser_state.next_dots
669 parser_state.next_dots = 0
670 if re.match ('[ \t]*[<>]', str):
671 while str[0] in HSPACE:
675 current_dots = current_dots + 1;
676 parser_state.next_den = parser_state.next_den * 2
681 parser_state.next_dots = parser_state.next_dots + 1
689 if num % multiplier == 0 and den % f == 0:
690 num = num / multiplier
692 current_dots = current_dots + d
694 return (str, num,den,current_dots)
697 def try_parse_rest (str, parser_state):
698 if not str or str[0] <> 'z' and str[0] <> 'x':
701 __main__.lyric_idx = -1
703 if parser_state.next_bar:
704 voices_append(parser_state.next_bar)
705 parser_state.next_bar = ''
713 (str, num,den,d) = parse_duration (str, parser_state)
714 voices_append ('%s%s' % (rest, duration_to_mudela_duration ((num,den), default_len, d)))
715 if parser_state.next_articulation:
716 voices_append (parser_state.next_articulation)
717 parser_state.next_articulation = ''
730 'J' : '', # ignore slide
731 'R' : '', # ignore roll
735 def try_parse_articulation (str, state):
737 while str and artic_tbl.has_key(str[:1]):
738 state.next_articulation = state.next_articulation + artic_tbl[str[:1]]
739 if not artic_tbl[str[:1]]:
740 sys.stderr.write("Warning: ignoring %s\n" % str[:1] )
746 # s7m2 input doesnt care about spaces
747 if re.match('[ \t]*\(', str):
748 str = string.lstrip (str)
751 while str[:1] =='(' and str[1] not in DIGITS:
752 slur_begin = slur_begin + 1
753 state.next_articulation = state.next_articulation + '('
759 # remember accidental for rest of bar
761 def set_bar_acc(note, octave, acc, state):
764 n_oct = note + octave * 7
765 state.in_acc[n_oct] = acc
767 # get accidental set in this bar or UNDEF if not set
768 def get_bar_acc(note, octave, state):
769 n_oct = note + octave * 7
770 if state.in_acc.has_key(n_oct):
771 return(state.in_acc[n_oct])
775 def clear_bar_acc(state):
776 for k in state.in_acc.keys():
781 # WAT IS ABC EEN ONTZETTENDE PROGRAMMEERPOEP !
782 def try_parse_note (str, parser_state):
801 octave = parser_state.base_octave
802 if str[0] in "ABCDEFG":
803 str = string.lower (str[0]) + str[1:]
808 if str[0] in "abcdefg":
809 notename = (ord(str[0]) - ord('a') + 5)%7
812 return str # failed; not a note!
815 __main__.lyric_idx = -1
817 if parser_state.next_bar:
818 voices_append(parser_state.next_bar)
819 parser_state.next_bar = ''
824 while str[0] == '\'':
828 (str, num,den,current_dots) = parse_duration (str, parser_state)
831 if re.match('[ \t]*\)', str):
832 str = string.lstrip (str)
836 slur_end = slur_end + 1
841 voices_append ('%s' % ')' *slur_end )
843 bar_acc = get_bar_acc(notename, octave, parser_state)
844 pit = pitch_to_mudela_name(notename, acc, bar_acc, global_key[notename])
845 oct = octave_to_mudela_quotes (octave)
846 if acc != UNDEF and (acc == global_key[notename] or acc == bar_acc):
850 voices_append ("%s%s%s%s" %
852 duration_to_mudela_duration ((num,den), default_len, current_dots)))
854 set_bar_acc(notename, octave, acc, parser_state)
855 if parser_state.next_articulation:
856 articulation = articulation + parser_state.next_articulation
857 parser_state.next_articulation = ''
859 voices_append (articulation)
861 if parser_state.parsing_tuplet:
862 parser_state.parsing_tuplet = parser_state.parsing_tuplet - 1
863 if not parser_state.parsing_tuplet:
866 voices_append ('%s' % '(' * slur_begin )
871 def junk_space (str):
872 while str and str[0] in '\t\n ':
878 def try_parse_guitar_chord (str, state):
882 while str and str[0] != '"':
888 gc = re.sub('#', '\\#', gc) # escape '#'s
889 state.next_articulation = ("^\"%s\"" % gc) + state.next_articulation
892 def try_parse_escape (str):
893 if not str or str [0] != '\\':
898 key_table = compute_key ()
902 # |] thin-thick double bar line
903 # || thin-thin double bar line
904 # [| thick-thin double bar line
907 # :: left-right repeat
924 warn_about = ['|:', '::', ':|', '|1', ':|2', '|2']
926 def try_parse_bar (str,state):
929 # first try the longer one
930 for trylen in [3,2,1]:
931 if str[:trylen] and bar_dict.has_key (str[:trylen]):
933 bs = "\\bar \"%s\";" % bar_dict[s]
935 sys.stderr.write('Warning kludging for barline `%s\'\n' % s)
940 state.next_bar = '|\n'
944 if bs <> None or state.next_bar != '':
945 if state.parsing_tuplet:
946 state.parsing_tuplet =0
955 def try_parse_tie (str):
958 voices_append (' ~ ')
961 def bracket_escape (str, state):
962 m = re.match ( '^([^\]]*)] *(.*)$', str)
966 try_parse_header_line (cmd, state)
969 def try_parse_chord_delims (str, state):
972 if re.match('[A-Z]:', str): # bracket escape
973 return bracket_escape(str, state)
975 voices_append(state.next_bar)
986 voices_append(state.next_bar)
1002 voices_append ("\\spanrequest \\stop \"slur\"" * end);
1006 def try_parse_grace_delims (str, state):
1009 voices_append(state.next_bar)
1012 voices_append ('\\grace { ')
1020 def try_parse_comment (str):
1023 if str[0:5] == '%MIDI':
1024 #the nobarlines option is necessary for an abc to mudela translator for
1025 #exactly the same reason abc2midi needs it: abc requires the user to enter
1026 #the note that will be printed, and MIDI and lilypond expect entry of the
1027 #pitch that will be played.
1029 #In standard 19th century musical notation, the algorithm for translating
1030 #between printed note and pitch involves using the barlines to determine
1031 #the scope of the accidentals.
1033 #Since ABC is frequently used for music in styles that do not use this
1034 #convention, such as most music written before 1700, or ethnic music in
1035 #non-western scales, it is necessary to be able to tell a translator that
1036 #the barlines should not affect its interpretation of the pitch.
1037 if (string.find(str,'nobarlines') > 0):
1040 elif str[0:3] == '%LY':
1041 p = string.find(str, 'voices')
1043 voices_append(str[p+7:])
1045 #write other kinds of appending if we ever need them.
1049 def parse_file (fn):
1053 select_voice('default', '')
1055 sys.stderr.write ("Line ... ")
1057 __main__.state = state_list[current_voice_idx]
1062 if not (lineno % happy_count):
1063 sys.stderr.write ('[%d]'% lineno)
1065 m = re.match ('^([^%]*)%(.*)$',ln) # add comments to current voice
1068 try_parse_comment(m.group(2))
1069 voices_append ('%% %s\n' % m.group(2))
1074 ln = try_parse_header_line (ln, state)
1076 # Try nibbling characters off until the line doesn't change.
1078 while ln != prev_ln:
1080 ln = try_parse_chord_delims (ln, state)
1081 ln = try_parse_rest (ln, state)
1082 ln = try_parse_articulation (ln,state)
1083 ln = try_parse_note (ln, state)
1084 ln = try_parse_bar (ln, state)
1085 ln = try_parse_tie (ln)
1086 ln = try_parse_escape (ln)
1087 ln = try_parse_guitar_chord (ln, state)
1088 ln = try_parse_tuplet_begin (ln, state)
1089 ln = try_parse_group_end (ln, state)
1090 ln = try_parse_grace_delims (ln, state)
1091 ln = junk_space (ln)
1094 msg = "%s: %d: Huh? Don't understand\n" % (fn, lineno)
1095 sys.stderr.write (msg)
1096 left = orig_ln[0:-len (ln)]
1097 sys.stderr.write (left + '\n')
1098 sys.stderr.write (' ' * len (left) + ln + '\n')
1102 sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
1106 Convert ABC to Mudela.
1108 Usage: abc2ly [OPTIONS]... ABC-FILE
1111 -h, --help this help
1112 -o, --output=FILE set output filename to FILE
1113 -v, --version version information
1115 This program converts ABC music files (see
1116 http://www.gre.ac.uk/~c.walshaw/abc2mtex/abc.txt) To LilyPond input.
1119 def print_version ():
1120 print r"""abc2ly (GNU lilypond) %s""" % version
1124 (options, files) = getopt.getopt (sys.argv[1:], 'vo:h', ['help','version', 'output='])
1130 if o== '--help' or o == '-h':
1133 if o == '--version' or o == '-v':
1137 if o == '--output' or o == '-o':
1145 header['tagline'] = 'Lily was here %s -- automatically converted from ABC' % version
1150 sys.stderr.write ('Parsing... [%s]\n' % f)
1153 if not out_filename:
1154 out_filename = os.path.basename (os.path.splitext (f)[0]) + ".ly"
1155 sys.stderr.write ('Ly output to: %s...' % out_filename)
1156 outf = open (out_filename, 'w')
1158 # dump_global (outf)
1159 dump_header (outf ,header)
1164 sys.stderr.write ('\n')