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)
44 program_name = 'abc2ly'
45 version = '@TOPLEVEL_VERSION@'
46 if version == '@' + 'TOPLEVEL_VERSION' + '@':
47 version = '1.2.9' # uGUHGUHGHGUGH
65 current_voice_idx = -1
66 current_lyric_idx = -1
70 global_key = [0] * 7 # UGH
71 names = ["One", "Two", "Three"]
79 if re.match('^treble', s):
81 if re.match ('^-8', s):
83 state.base_octave = -2
84 voices_append("\\clef \"G_8\";\n")
87 voices_append("\\clef treble;\n")
88 elif re.match('^alto', s):
90 state.base_octave = -1
91 voices_append ("\\clef alto;\n" )
92 elif re.match('^bass',s ):
94 state.base_octave = -2
95 voices_append ("\\clef bass;\n" )
98 def select_voice (name, rol):
99 if not voice_idx_dict.has_key (name):
100 state_list.append(Parser_state())
103 voice_idx_dict[name] = len (voices) -1
104 __main__.current_voice_idx = voice_idx_dict[name]
105 __main__.state = state_list[current_voice_idx]
107 m = re.match ('^([^ \t=]*)=(.*)$', rol) # find keywork
111 a = re.match ('^("[^"]*"|[^ \t]*) *(.*)$', rol)
115 if keyword == 'clef':
117 elif keyword == "name":
118 value = re.sub ('\\\\','\\\\\\\\', value)
119 voices_append ("\\property Staff.instrument = %s\n" % value )
120 __main__.part_names = 1
121 elif keyword == "sname" or keyword == "snm":
122 voices_append ("\\property Staff.instr = %s\n" % value )
130 def dump_header (outf,hdr):
131 outf.write ('\\header {\n')
135 outf.write ('\t%s = "%s";\n'% (k,hdr[k]))
138 def dump_lyrics (outf):
140 outf.write("\n\\score\n{\n \\context Lyrics\n <\n")
141 for i in range (len (lyrics)):
142 outf.write ( lyrics [i])
144 outf.write(" >\n \\paper{}\n}\n")
146 def dump_slyrics (outf):
147 ks = voice_idx_dict.keys()
150 for i in range (len(slyrics[voice_idx_dict[k]])):
151 outf.write ("\nwords%sV%d = \\lyrics {" % (k, i))
152 outf.write ("\n" + slyrics [voice_idx_dict[k]][i])
155 def dump_voices (outf):
156 ks = voice_idx_dict.keys()
159 outf.write ("\nvoice%s = \\notes {" % k)
160 outf.write ("\n" + voices [voice_idx_dict[k]])
163 def dump_score (outf):
164 outf.write (r"""\score{
168 ks = voice_idx_dict.keys ();
171 if k == 'default' and len (voice_idx_dict) > 1:
173 if len ( slyrics [voice_idx_dict[k]] ):
174 outf.write ("\n \\addlyrics")
175 outf.write ("\n\t\\context Staff=\"%s\"\n\t{\n" %k )
177 outf.write ("\t \\$voicedefault\n")
178 outf.write ("\t \\$voice%s " % k)
179 outf.write ("\n\t}\n")
180 if len ( slyrics [voice_idx_dict[k]] ):
181 outf.write ("\n\t\\context Lyrics=\"%s\" \n\t<\t" % k)
182 for i in range (len(slyrics[voice_idx_dict[k]])):
183 outf.write("\n\t { \\$words%sV%d }" % ( k, i) )
184 outf.write ( "\n\t>\n" )
186 outf.write ("\n\t\\paper {\n")
188 outf.write ("\t \\translator \n\t {\n")
189 outf.write ("\t\t\\StaffContext\n")
190 outf.write ("\t\t\\consists Staff_margin_engraver;\n")
191 outf.write ("\t }\n")
192 outf.write ("\t}\n\t\\midi {}\n}\n")
196 def set_default_length (s):
197 m = re.search ('1/([0-9]+)', s)
199 __main__.default_len = string.atoi ( m.group (1))
201 def set_default_len_from_time_sig (s):
202 m = re.search ('([0-9]+)/([0-9]+)', s)
204 n = string.atoi (m.group (1))
205 d = string.atoi (m.group (2))
206 if (n * 1.0 )/(d * 1.0) < 0.75:
207 __main__.default_len = 16
209 __main__.default_len = 8
218 sys.stderr.write ("can't open file: %s\n" % f)
222 sys.stderr.write ("gulped emty file: %s\n" % f)
227 # pitch manipulation. Tuples are (name, alteration).
228 # 0 is (central) C. Alteration -1 is a flat, Alteration +1 is a sharp
229 # pitch in semitones.
230 def semitone_pitch (tup):
240 p = p + t* 2 + tup[1]
243 def fifth_above_pitch (tup):
244 (n, a) = (tup[0] + 4, tup[1])
246 difference = 7 - (semitone_pitch ((n,a)) - semitone_pitch (tup))
257 (t,a) = fifth_above_pitch (p)
258 if semitone_pitch((t,a)) % 12 == 0:
270 (t,a) = quart_above_pitch (p)
271 if semitone_pitch((t,a)) % 12 == 0:
277 def quart_above_pitch (tup):
278 (n, a) = (tup[0] + 3, tup[1])
280 difference = 5 - (semitone_pitch ((n,a)) - semitone_pitch (tup))
285 key_lookup = { # abc to lilypond key mode names
293 'mix' : 'mixolydian',
302 if k and k[0] == '#':
305 elif k and k[0] == 'b':
312 if key_lookup.has_key(type):
313 return("%s \\%s" % ( key, key_lookup[type]))
314 sys.stderr.write("Unknown key type %s ignored\n" % type)
317 def shift_key (note, acc , shift):
318 s = semitone_pitch((note, acc))
319 s = (s + shift + 12) % 12
331 key_shift = { # semitone shifts for key mode names
345 intkey = (ord (k[0]) - ord('a') + 5) % 7
349 if k and k[0] == 'b':
352 elif k and k[0] == '#':
356 if k and key_shift.has_key(k):
357 (intkey, intkeyacc) = shift_key(intkey, intkeyacc, key_shift[k])
358 keytup = (intkey, intkeyacc)
360 sharp_key_seq = sharp_keys ()
361 flat_key_seq = flat_keys ()
365 if keytup in sharp_key_seq:
367 key_count = sharp_key_seq.index (keytup)
368 accseq = map (lambda x: (4*x -1 ) % 7, range (1, key_count + 1))
370 elif keytup in flat_key_seq:
372 key_count = flat_key_seq.index (keytup)
373 accseq = map (lambda x: (3*x + 3 ) % 7, range (1, key_count + 1))
379 key_table[a] = key_table[a] + accsign
394 def try_parse_tuplet_begin (str, state):
395 if re.match ('\([2-9]', str):
398 state.parsing_tuplet = string.atoi (dig[0])
400 voices_append ("\\times %s {" % tup_lookup[dig])
403 def try_parse_group_end (str, state):
404 if str and str[0] in HSPACE:
408 def header_append (key, a):
410 if header.has_key (key):
411 s = header[key] + "\n"
415 linelen = len (v) - string.rfind(v, '\n')
416 if linelen + len (a) > 80:
420 def stuff_append (stuff, idx, a):
424 stuff [idx] = wordwrap(a, stuff[idx])
428 def voices_append(a):
429 if current_voice_idx < 0:
430 select_voice ('default', '')
432 stuff_append (voices, current_voice_idx, a)
434 def lyrics_append(a):
435 a = re.sub ( '#', '\\#', a) # latex does not like naked #'s
436 a = re.sub ( '"', '\\"', a) # latex does not like naked "'s
437 a = '\t{ \\lyrics "' + a + '" }\n'
438 stuff_append (lyrics, current_lyric_idx, a)
440 # break lyrics to words and put "'s around words containing numbers and '"'s
445 m = re.match('[ \t]*([^ \t]*)[ \t]*(.*$)', str)
449 word = re.sub('"', '\\"', word) # escape "
450 if re.match('.*[0-9"]', word):
451 word = re.sub('_', ' ', word) # _ causes probs inside ""
452 ret = ret + '\"' + word + '\" '
454 ret = ret + word + ' '
459 def slyrics_append(a):
460 a = re.sub ( '_', ' _ ', a) # _ to ' _ '
461 a = re.sub ( '-', '- ', a) # split words with -
462 a = re.sub ( '\\\\- ', '-', a) # unless \-
463 a = re.sub ( '~', '_', a) # ~ to space('_')
464 a = re.sub ( '\*', '_ ', a) # * to to space
465 a = re.sub ( '#', '\\#', a) # latex does not like naked #'s
466 if re.match('.*[0-9"]', a): # put numbers and " into quoted string
468 a = re.sub ( '$', ' ', a) # insure space between lines
469 __main__.lyric_idx = lyric_idx + 1
470 if len(slyrics[current_voice_idx]) <= lyric_idx:
471 slyrics[current_voice_idx].append(a)
473 v = slyrics[current_voice_idx][lyric_idx]
474 slyrics[current_voice_idx][lyric_idx] = wordwrap(a, slyrics[current_voice_idx][lyric_idx])
477 def try_parse_header_line (ln, state):
478 m = re.match ('^([A-Za-z]): *(.*)$', ln)
484 a = re.sub('[ \t]*$','', a) #strip trailing blanks
485 if header.has_key('title'):
487 header['title'] = header['title'] + '\\\\\\\\' + a
492 if not state.common_time:
493 state.common_time = 1
494 voices_append ("\\property Staff.timeSignatureStyle=\"C\"\n")
497 if not state.common_time:
498 state.common_time = 1
499 voices_append ("\\property Staff.timeSignatureStyle=\"C\"\n")
501 # global_voice_stuff.append ('\\time %s;' % a)
502 set_default_len_from_time_sig (a)
503 voices_append ('\\time %s;' % a)
508 m = re.match ('^([^ \t]*) *(.*)$', a) # seperate clef info
510 __main__.global_key =compute_key (m.group(1))# ugh.
511 voices_append ('\\key %s;' % lily_key(m.group(1)))
512 check_clef(m.group(2))
514 __main__.global_key =compute_key (a)# ugh.
515 voices_append ('\\key %s;' % lily_key(a))
516 if g == 'O': # Origin
517 header ['origin'] = a
518 if g == 'X': # Reference Number
519 header ['crossRefNumber'] = a
522 if g == 'H': # History
523 header_append ('history', a)
526 if g == 'C': # Composer
527 if header.has_key('composer'):
529 header['composer'] = header['composer'] + '\\\\\\\\' + a
531 header['composer'] = a
533 header ['subtitle'] = a
534 if g == 'L': # Default note length
535 set_default_length (ln)
537 voice = re.sub (' .*$', '', a)
538 rest = re.sub ('^[^ \t]* *', '', a)
540 voices_append(state.next_bar)
542 select_voice (voice, rest)
545 if g == 'w': # vocals
551 # we use in this order specified accidental, active accidental for bar,
552 # active accidental for key
553 def pitch_to_mudela_name (name, acc, bar_acc, key):
566 return(chr (name + ord('c')) + s)
569 def octave_to_mudela_quotes (o):
582 while str and str[0] in DIGITS:
583 durstr = durstr + str[0]
588 n =string.atoi (durstr)
592 def duration_to_mudela_duration (multiply_tup, defaultlen, dots):
595 # (num / den) / defaultlen < 1/base
596 while base * multiply_tup[0] < multiply_tup[1]:
600 return '%d%s' % ( base, '.'* dots)
605 self.next_articulation = ''
609 self.parsing_tuplet = 0
616 # return (str, num,den,dots)
617 def parse_duration (str, parser_state):
619 den = parser_state.next_den
620 parser_state.next_den = 1
622 (str, num) = parse_num (str)
627 while str[:1] == '/':
631 (str, d) =parse_num (str)
635 den = den * default_len
637 current_dots = parser_state.next_dots
638 parser_state.next_dots = 0
639 if re.match ('[ \t]*[<>]', str):
640 while str[0] in HSPACE:
644 current_dots = current_dots + 1;
645 parser_state.next_den = parser_state.next_den * 2
650 parser_state.next_dots = parser_state.next_dots + 1
658 if num % multiplier == 0 and den % f == 0:
659 num = num / multiplier
661 current_dots = current_dots + d
663 return (str, num,den,current_dots)
666 def try_parse_rest (str, parser_state):
667 if not str or str[0] <> 'z' and str[0] <> 'x':
670 __main__.lyric_idx = -1
672 if parser_state.next_bar:
673 voices_append(parser_state.next_bar)
674 parser_state.next_bar = ''
682 (str, num,den,d) = parse_duration (str, parser_state)
683 voices_append ('%s%s' % (rest, duration_to_mudela_duration ((num,den), default_len, d)))
684 if parser_state.next_articulation:
685 voices_append (parser_state.next_articulation)
686 parser_state.next_articulation = ''
699 'J' : '', # ignore slide
700 'R' : '', # ignore roll
704 def try_parse_articulation (str, state):
706 while str and artic_tbl.has_key(str[:1]):
707 state.next_articulation = state.next_articulation + artic_tbl[str[:1]]
708 if not artic_tbl[str[:1]]:
709 sys.stderr.write("Warning: ignoring %s\n" % str[:1] )
715 # s7m2 input doesnt care about spaces
716 if re.match('[ \t]*\(', str):
717 str = string.lstrip (str)
720 while str[:1] =='(' and str[1] not in DIGITS:
721 slur_begin = slur_begin + 1
722 state.next_articulation = state.next_articulation + '('
728 # remember accidental for rest of bar
730 def set_bar_acc(note, octave, acc, state):
733 n_oct = note + octave * 7
734 state.in_acc[n_oct] = acc
736 # get accidental set in this bar or UNDEF if not set
737 def get_bar_acc(note, octave, state):
738 n_oct = note + octave * 7
739 if state.in_acc.has_key(n_oct):
740 return(state.in_acc[n_oct])
744 def clear_bar_acc(state):
745 for k in state.in_acc.keys():
750 # WAT IS ABC EEN ONTZETTENDE PROGRAMMEERPOEP !
751 def try_parse_note (str, parser_state):
770 octave = parser_state.base_octave
771 if str[0] in "ABCDEFG":
772 str = string.lower (str[0]) + str[1:]
777 if str[0] in "abcdefg":
778 notename = (ord(str[0]) - ord('a') + 5)%7
781 return str # failed; not a note!
784 __main__.lyric_idx = -1
786 if parser_state.next_bar:
787 voices_append(parser_state.next_bar)
788 parser_state.next_bar = ''
793 while str[0] == '\'':
797 (str, num,den,current_dots) = parse_duration (str, parser_state)
800 if re.match('[ \t]*\)', str):
801 str = string.lstrip (str)
805 slur_end = slur_end + 1
810 voices_append ('%s' % ')' *slur_end )
812 bar_acc = get_bar_acc(notename, octave, parser_state)
813 pit = pitch_to_mudela_name(notename, acc, bar_acc, global_key[notename])
814 oct = octave_to_mudela_quotes (octave)
815 if acc != UNDEF and (acc == global_key[notename] or acc == bar_acc):
819 voices_append ("%s%s%s%s" %
821 duration_to_mudela_duration ((num,den), default_len, current_dots)))
823 set_bar_acc(notename, octave, acc, parser_state)
824 if parser_state.next_articulation:
825 articulation = articulation + parser_state.next_articulation
826 parser_state.next_articulation = ''
828 voices_append (articulation)
830 if parser_state.parsing_tuplet:
831 parser_state.parsing_tuplet = parser_state.parsing_tuplet - 1
832 if not parser_state.parsing_tuplet:
835 voices_append ('%s' % '(' * slur_begin )
840 def junk_space (str):
841 while str and str[0] in '\t\n ':
847 def try_parse_guitar_chord (str, state):
851 while str and str[0] != '"':
857 gc = re.sub('#', '\\#', gc) # escape '#'s
858 state.next_articulation = ("-\"%s\"" % gc) + state.next_articulation
861 def try_parse_escape (str):
862 if not str or str [0] != '\\':
867 key_table = compute_key ()
871 # |] thin-thick double bar line
872 # || thin-thin double bar line
873 # [| thick-thin double bar line
876 # :: left-right repeat
892 warn_about = ['|:', '::', ':|', '|1', ':|2', '|2']
894 def try_parse_bar (str,state):
897 # first try the longer one
899 if str[:trylen] and bar_dict.has_key (str[:trylen]):
901 bs = "\\bar \"%s\";" % bar_dict[s]
903 sys.stderr.write('Warning kludging for barline `%s\'\n' % s)
908 state.next_bar = '|\n'
912 if bs <> None or state.next_bar != '':
913 if state.parsing_tuplet:
914 state.parsing_tuplet =0
923 def try_parse_tie (str):
926 voices_append (' ~ ')
929 def bracket_escape (str, state):
930 m = re.match ( '^([^\]]*)] *(.*)$', str)
934 try_parse_header_line (cmd, state)
937 def try_parse_chord_delims (str, state):
940 if re.match('[A-Z]:', str): # bracket escape
941 return bracket_escape(str, state)
943 voices_append(state.next_bar)
954 voices_append(state.next_bar)
970 voices_append ("\\spanrequest \\stop \"slur\"" * end);
974 def try_parse_grace_delims (str, state):
977 voices_append(state.next_bar)
980 voices_append ('\\grace { ')
994 select_voice('default', '')
996 sys.stderr.write ("Line ... ")
998 __main__.state = state_list[current_voice_idx]
1003 if not (lineno % happy_count):
1004 sys.stderr.write ('[%d]'% lineno)
1006 m = re.match ('^([^%]*)%(.*)$',ln) # add comments to current voice
1009 voices_append ('%% %s\n' % m.group(2))
1014 ln = try_parse_header_line (ln, state)
1016 # Try nibbling characters off until the line doesn't change.
1018 while ln != prev_ln:
1020 ln = try_parse_chord_delims (ln, state)
1021 ln = try_parse_rest (ln, state)
1022 ln = try_parse_articulation (ln,state)
1023 ln = try_parse_note (ln, state)
1024 ln = try_parse_bar (ln, state)
1025 ln = try_parse_tie (ln)
1026 ln = try_parse_escape (ln)
1027 ln = try_parse_guitar_chord (ln, state)
1028 ln = try_parse_tuplet_begin (ln, state)
1029 ln = try_parse_group_end (ln, state)
1030 ln = try_parse_grace_delims (ln, state)
1031 ln = junk_space (ln)
1034 msg = "%s: %d: Huh? Don't understand\n" % (fn, lineno)
1035 sys.stderr.write (msg)
1036 left = orig_ln[0:-len (ln)]
1037 sys.stderr.write (left + '\n')
1038 sys.stderr.write (' ' * len (left) + ln + '\n')
1042 sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
1046 Convert ABC to Mudela.
1048 Usage: abc2ly [OPTION]... ABC-FILE
1051 -h, --help this help
1052 -o, --output=FILE set output filename to FILE
1053 -v, --version version information
1056 def print_version ():
1057 print r"""abc2ly (GNU lilypond) %s""" % version
1061 (options, files) = getopt.getopt (sys.argv[1:], 'vo:h', ['help','version', 'output='])
1067 if o== '--help' or o == '-h':
1070 if o == '--version' or o == '-v':
1074 if o == '--output' or o == '-o':
1082 header['tagline'] = 'Lily was here %s -- automatically converted from ABC' % version
1087 sys.stderr.write ('Parsing... [%s]\n' % f)
1090 if not out_filename:
1091 out_filename = os.path.basename (os.path.splitext (f)[0]) + ".ly"
1092 sys.stderr.write ('Ly output to: %s...' % out_filename)
1093 outf = open (out_filename, 'w')
1095 # dump_global (outf)
1096 dump_header (outf ,header)
1101 sys.stderr.write ('\n')