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 # Beaming now preserved between ABC and lilypond
35 # Multiple tunes in single file not supported
36 # Blank T: header lines should write score and open a new score
37 # Not all header fields supported
38 # ABC line breaks are ignored
39 # Block comments generate error and are ignored
40 # Postscript commands are ignored
41 # lyrics not resynchronized by line breaks (lyrics must fully match notes)
51 program_name = 'abc2ly'
52 version = '@TOPLEVEL_VERSION@'
53 if version == '@' + 'TOPLEVEL_VERSION' + '@':
54 version = '(unknown version)' # uGUHGUHGHGUGH
72 current_voice_idx = -1
73 current_lyric_idx = -1
78 global_key = [0] * 7 # UGH
79 names = ["One", "Two", "Three"]
87 if re.match('^treble', s):
89 if re.match ('^-8', s):
91 state.base_octave = -2
92 voices_append("\\clef \"G_8\";\n")
95 voices_append("\\clef treble;\n")
96 elif re.match('^alto', s):
98 state.base_octave = -1
99 voices_append ("\\clef alto;\n" )
100 elif re.match('^bass',s ):
102 state.base_octave = -2
103 voices_append ("\\clef bass;\n" )
106 def select_voice (name, rol):
107 if not voice_idx_dict.has_key (name):
108 state_list.append(Parser_state())
111 voice_idx_dict[name] = len (voices) -1
112 __main__.current_voice_idx = voice_idx_dict[name]
113 __main__.state = state_list[current_voice_idx]
115 m = re.match ('^([^ \t=]*)=(.*)$', rol) # find keywork
119 a = re.match ('^("[^"]*"|[^ \t]*) *(.*)$', rol)
123 if keyword == 'clef':
125 elif keyword == "name":
126 value = re.sub ('\\\\','\\\\\\\\', value)
127 voices_append ("\\property Staff.instrument = %s\n" % value )
128 __main__.part_names = 1
129 elif keyword == "sname" or keyword == "snm":
130 voices_append ("\\property Staff.instr = %s\n" % value )
138 def dump_header (outf,hdr):
139 outf.write ('\\header {\n')
143 outf.write ('\t%s = "%s";\n'% (k,hdr[k]))
146 def dump_lyrics (outf):
148 outf.write("\n\\score\n{\n \\context Lyrics\n <\n")
149 for i in range (len (lyrics)):
150 outf.write ( lyrics [i])
152 outf.write(" >\n \\paper{}\n}\n")
154 def dump_default_bar (outf):
155 outf.write ("\n\\property Score.defaultBarType=\"empty\"\n")
158 def dump_slyrics (outf):
159 ks = voice_idx_dict.keys()
162 for i in range (len(slyrics[voice_idx_dict[k]])):
163 outf.write ("\nwords%sV%d = \\lyrics {" % (k, i))
164 outf.write ("\n" + slyrics [voice_idx_dict[k]][i])
167 def dump_voices (outf):
168 ks = voice_idx_dict.keys()
171 outf.write ("\nvoice%s = \\notes {" % k)
172 dump_default_bar(outf)
173 outf.write ("\n" + voices [voice_idx_dict[k]])
176 def dump_score (outf):
177 outf.write (r"""\score{
181 ks = voice_idx_dict.keys ();
184 if k == 'default' and len (voice_idx_dict) > 1:
186 if len ( slyrics [voice_idx_dict[k]] ):
187 outf.write ("\n \\addlyrics")
188 outf.write ("\n\t\\context Staff=\"%s\"\n\t{\n" %k )
190 outf.write ("\t \\$voicedefault\n")
191 outf.write ("\t \\$voice%s " % k)
192 outf.write ("\n\t}\n")
193 if len ( slyrics [voice_idx_dict[k]] ):
194 outf.write ("\n\t\\context Lyrics=\"%s\" \n\t<\t" % k)
195 for i in range (len(slyrics[voice_idx_dict[k]])):
196 outf.write("\n\t { \\$words%sV%d }" % ( k, i) )
197 outf.write ( "\n\t>\n" )
199 outf.write ("\n\t\\paper {\n")
201 outf.write ("\t \\translator \n\t {\n")
202 outf.write ("\t\t\\StaffContext\n")
203 outf.write ("\t\t\\consists Staff_margin_engraver;\n")
204 outf.write ("\t }\n")
205 outf.write ("\t}\n\t\\midi {}\n}\n")
209 def set_default_length (s):
210 m = re.search ('1/([0-9]+)', s)
212 __main__.default_len = string.atoi ( m.group (1))
215 def set_default_len_from_time_sig (s):
216 m = re.search ('([0-9]+)/([0-9]+)', s)
218 n = string.atoi (m.group (1))
219 d = string.atoi (m.group (2))
220 if (n * 1.0 )/(d * 1.0) < 0.75:
221 __main__.default_len = 16
223 __main__.default_len = 8
232 sys.stderr.write ("can't open file: %s\n" % f)
236 sys.stderr.write ("gulped emty file: %s\n" % f)
241 # pitch manipulation. Tuples are (name, alteration).
242 # 0 is (central) C. Alteration -1 is a flat, Alteration +1 is a sharp
243 # pitch in semitones.
244 def semitone_pitch (tup):
254 p = p + t* 2 + tup[1]
257 def fifth_above_pitch (tup):
258 (n, a) = (tup[0] + 4, tup[1])
260 difference = 7 - (semitone_pitch ((n,a)) - semitone_pitch (tup))
271 (t,a) = fifth_above_pitch (p)
272 if semitone_pitch((t,a)) % 12 == 0:
284 (t,a) = quart_above_pitch (p)
285 if semitone_pitch((t,a)) % 12 == 0:
291 def quart_above_pitch (tup):
292 (n, a) = (tup[0] + 3, tup[1])
294 difference = 5 - (semitone_pitch ((n,a)) - semitone_pitch (tup))
299 key_lookup = { # abc to lilypond key mode names
307 'mix' : 'mixolydian',
316 if k and k[0] == '#':
319 elif k and k[0] == 'b':
323 return '%s \\major' % key
326 if key_lookup.has_key(type):
327 return("%s \\%s" % ( key, key_lookup[type]))
328 sys.stderr.write("Unknown key type %s ignored\n" % type)
331 def shift_key (note, acc , shift):
332 s = semitone_pitch((note, acc))
333 s = (s + shift + 12) % 12
345 key_shift = { # semitone shifts for key mode names
359 intkey = (ord (k[0]) - ord('a') + 5) % 7
363 if k and k[0] == 'b':
366 elif k and k[0] == '#':
370 if k and key_shift.has_key(k):
371 (intkey, intkeyacc) = shift_key(intkey, intkeyacc, key_shift[k])
372 keytup = (intkey, intkeyacc)
374 sharp_key_seq = sharp_keys ()
375 flat_key_seq = flat_keys ()
379 if keytup in sharp_key_seq:
381 key_count = sharp_key_seq.index (keytup)
382 accseq = map (lambda x: (4*x -1 ) % 7, range (1, key_count + 1))
384 elif keytup in flat_key_seq:
386 key_count = flat_key_seq.index (keytup)
387 accseq = map (lambda x: (3*x + 3 ) % 7, range (1, key_count + 1))
393 key_table[a] = key_table[a] + accsign
408 def try_parse_tuplet_begin (str, state):
409 if re.match ('\([2-9]', str):
412 state.parsing_tuplet = string.atoi (dig[0])
414 voices_append ("\\times %s {" % tup_lookup[dig])
417 def try_parse_group_end (str, state):
418 if str and str[0] in HSPACE:
422 def header_append (key, a):
424 if header.has_key (key):
425 s = header[key] + "\n"
429 linelen = len (v) - string.rfind(v, '\n')
430 if linelen + len (a) > 80:
434 def stuff_append (stuff, idx, a):
438 stuff [idx] = wordwrap(a, stuff[idx])
442 def voices_append(a):
443 if current_voice_idx < 0:
444 select_voice ('default', '')
446 stuff_append (voices, current_voice_idx, a)
448 def lyrics_append(a):
449 a = re.sub ( '#', '\\#', a) # latex does not like naked #'s
450 a = re.sub ( '"', '\\"', a) # latex does not like naked "'s
451 a = '\t{ \\lyrics "' + a + '" }\n'
452 stuff_append (lyrics, current_lyric_idx, a)
454 # break lyrics to words and put "'s around words containing numbers and '"'s
459 m = re.match('[ \t]*([^ \t]*)[ \t]*(.*$)', str)
463 word = re.sub('"', '\\"', word) # escape "
464 if re.match('.*[0-9"]', word):
465 word = re.sub('_', ' ', word) # _ causes probs inside ""
466 ret = ret + '\"' + word + '\" '
468 ret = ret + word + ' '
473 def slyrics_append(a):
474 a = re.sub ( '_', ' _ ', a) # _ to ' _ '
475 a = re.sub ( '-', '- ', a) # split words with -
476 a = re.sub ( '\\\\- ', '-', a) # unless \-
477 a = re.sub ( '~', '_', a) # ~ to space('_')
478 a = re.sub ( '\*', '_ ', a) # * to to space
479 a = re.sub ( '#', '\\#', a) # latex does not like naked #'s
480 if re.match('.*[0-9"]', a): # put numbers and " into quoted string
482 a = re.sub ( '$', ' ', a) # insure space between lines
483 __main__.lyric_idx = lyric_idx + 1
484 if len(slyrics[current_voice_idx]) <= lyric_idx:
485 slyrics[current_voice_idx].append(a)
487 v = slyrics[current_voice_idx][lyric_idx]
488 slyrics[current_voice_idx][lyric_idx] = wordwrap(a, slyrics[current_voice_idx][lyric_idx])
491 def try_parse_header_line (ln, state):
492 m = re.match ('^([A-Za-z]): *(.*)$', ln)
498 a = re.sub('[ \t]*$','', a) #strip trailing blanks
499 if header.has_key('title'):
501 header['title'] = header['title'] + '\\\\\\\\' + a
506 if not state.common_time:
507 state.common_time = 1
508 voices_append ("\\property Staff.timeSignatureStyle=\"C\"\n")
511 if not state.common_time:
512 state.common_time = 1
513 voices_append ("\\property Staff.timeSignatureStyle=\"C\"\n")
515 if not length_specified:
516 set_default_len_from_time_sig (a)
517 voices_append ('\\time %s;' % a)
522 m = re.match ('^([^ \t]*) *(.*)$', a) # seperate clef info
524 __main__.global_key =compute_key (m.group(1))# ugh.
525 voices_append ('\\key %s;' % lily_key(m.group(1)))
526 check_clef(m.group(2))
528 __main__.global_key =compute_key (a)# ugh.
529 voices_append ('\\key %s \\major;' % lily_key(a))
530 if g == 'O': # Origin
531 header ['origin'] = a
532 if g == 'X': # Reference Number
533 header ['crossRefNumber'] = a
536 if g == 'H': # History
537 header_append ('history', a)
540 if g == 'C': # Composer
541 if header.has_key('composer'):
543 header['composer'] = header['composer'] + '\\\\\\\\' + a
545 header['composer'] = a
547 header ['subtitle'] = a
548 if g == 'L': # Default note length
549 set_default_length (ln)
551 voice = re.sub (' .*$', '', a)
552 rest = re.sub ('^[^ \t]* *', '', a)
554 voices_append(state.next_bar)
556 select_voice (voice, rest)
559 if g == 'w': # vocals
565 # we use in this order specified accidental, active accidental for bar,
566 # active accidental for key
567 def pitch_to_mudela_name (name, acc, bar_acc, key):
580 return(chr (name + ord('c')) + s)
583 def octave_to_mudela_quotes (o):
596 while str and str[0] in DIGITS:
597 durstr = durstr + str[0]
602 n =string.atoi (durstr)
606 def duration_to_mudela_duration (multiply_tup, defaultlen, dots):
608 # (num / den) / defaultlen < 1/base
609 while base * multiply_tup[0] < multiply_tup[1]:
611 return '%d%s' % ( base, '.'* dots)
616 self.next_articulation = ''
620 self.parsing_tuplet = 0
627 # return (str, num,den,dots)
628 def parse_duration (str, parser_state):
630 den = parser_state.next_den
631 parser_state.next_den = 1
633 (str, num) = parse_num (str)
638 while str[:1] == '/':
642 (str, d) =parse_num (str)
646 den = den * default_len
648 current_dots = parser_state.next_dots
649 parser_state.next_dots = 0
650 if re.match ('[ \t]*[<>]', str):
651 while str[0] in HSPACE:
655 current_dots = current_dots + 1;
656 parser_state.next_den = parser_state.next_den * 2
661 parser_state.next_dots = parser_state.next_dots + 1
669 if num % multiplier == 0 and den % f == 0:
670 num = num / multiplier
672 current_dots = current_dots + d
674 return (str, num,den,current_dots)
677 def try_parse_rest (str, parser_state):
678 if not str or str[0] <> 'z' and str[0] <> 'x':
681 __main__.lyric_idx = -1
683 if parser_state.next_bar:
684 voices_append(parser_state.next_bar)
685 parser_state.next_bar = ''
693 (str, num,den,d) = parse_duration (str, parser_state)
694 voices_append ('%s%s' % (rest, duration_to_mudela_duration ((num,den), default_len, d)))
695 if parser_state.next_articulation:
696 voices_append (parser_state.next_articulation)
697 parser_state.next_articulation = ''
710 'J' : '', # ignore slide
711 'R' : '', # ignore roll
715 def try_parse_articulation (str, state):
717 while str and artic_tbl.has_key(str[:1]):
718 state.next_articulation = state.next_articulation + artic_tbl[str[:1]]
719 if not artic_tbl[str[:1]]:
720 sys.stderr.write("Warning: ignoring %s\n" % str[:1] )
726 # s7m2 input doesnt care about spaces
727 if re.match('[ \t]*\(', str):
728 str = string.lstrip (str)
731 while str[:1] =='(' and str[1] not in DIGITS:
732 slur_begin = slur_begin + 1
733 state.next_articulation = state.next_articulation + '('
739 # remember accidental for rest of bar
741 def set_bar_acc(note, octave, acc, state):
744 n_oct = note + octave * 7
745 state.in_acc[n_oct] = acc
747 # get accidental set in this bar or UNDEF if not set
748 def get_bar_acc(note, octave, state):
749 n_oct = note + octave * 7
750 if state.in_acc.has_key(n_oct):
751 return(state.in_acc[n_oct])
755 def clear_bar_acc(state):
756 for k in state.in_acc.keys():
761 # WAT IS ABC EEN ONTZETTENDE PROGRAMMEERPOEP !
762 def try_parse_note (str, parser_state):
781 octave = parser_state.base_octave
782 if str[0] in "ABCDEFG":
783 str = string.lower (str[0]) + str[1:]
788 if str[0] in "abcdefg":
789 notename = (ord(str[0]) - ord('a') + 5)%7
792 return str # failed; not a note!
795 __main__.lyric_idx = -1
797 if parser_state.next_bar:
798 voices_append(parser_state.next_bar)
799 parser_state.next_bar = ''
804 while str[0] == '\'':
808 (str, num,den,current_dots) = parse_duration (str, parser_state)
811 if re.match('[ \t]*\)', str):
812 str = string.lstrip (str)
816 slur_end = slur_end + 1
821 voices_append ('%s' % ')' *slur_end )
823 bar_acc = get_bar_acc(notename, octave, parser_state)
824 pit = pitch_to_mudela_name(notename, acc, bar_acc, global_key[notename])
825 oct = octave_to_mudela_quotes (octave)
826 if acc != UNDEF and (acc == global_key[notename] or acc == bar_acc):
830 voices_append ("%s%s%s%s" %
832 duration_to_mudela_duration ((num,den), default_len, current_dots)))
834 set_bar_acc(notename, octave, acc, parser_state)
835 if parser_state.next_articulation:
836 articulation = articulation + parser_state.next_articulation
837 parser_state.next_articulation = ''
839 voices_append (articulation)
841 if parser_state.parsing_tuplet:
842 parser_state.parsing_tuplet = parser_state.parsing_tuplet - 1
843 if not parser_state.parsing_tuplet:
846 voices_append ('%s' % '(' * slur_begin )
851 def junk_space (str):
852 while str and str[0] in '\t\n ':
858 def try_parse_guitar_chord (str, state):
862 while str and str[0] != '"':
868 gc = re.sub('#', '\\#', gc) # escape '#'s
869 state.next_articulation = ("-\"%s\"" % gc) + state.next_articulation
872 def try_parse_escape (str):
873 if not str or str [0] != '\\':
878 key_table = compute_key ()
882 # |] thin-thick double bar line
883 # || thin-thin double bar line
884 # [| thick-thin double bar line
887 # :: left-right repeat
904 warn_about = ['|:', '::', ':|', '|1', ':|2', '|2']
906 def try_parse_bar (str,state):
909 # first try the longer one
910 for trylen in [3,2,1]:
911 if str[:trylen] and bar_dict.has_key (str[:trylen]):
913 bs = "\\bar \"%s\";" % bar_dict[s]
915 sys.stderr.write('Warning kludging for barline `%s\'\n' % s)
920 state.next_bar = '|\n'
924 if bs <> None or state.next_bar != '':
925 if state.parsing_tuplet:
926 state.parsing_tuplet =0
935 def try_parse_tie (str):
938 voices_append (' ~ ')
941 def bracket_escape (str, state):
942 m = re.match ( '^([^\]]*)] *(.*)$', str)
946 try_parse_header_line (cmd, state)
949 def try_parse_chord_delims (str, state):
952 if re.match('[A-Z]:', str): # bracket escape
953 return bracket_escape(str, state)
955 voices_append(state.next_bar)
966 voices_append(state.next_bar)
982 voices_append ("\\spanrequest \\stop \"slur\"" * end);
986 def try_parse_grace_delims (str, state):
989 voices_append(state.next_bar)
992 voices_append ('\\grace { ')
1002 def parse_file (fn):
1006 select_voice('default', '')
1008 sys.stderr.write ("Line ... ")
1010 __main__.state = state_list[current_voice_idx]
1015 if not (lineno % happy_count):
1016 sys.stderr.write ('[%d]'% lineno)
1018 m = re.match ('^([^%]*)%(.*)$',ln) # add comments to current voice
1021 voices_append ('%% %s\n' % m.group(2))
1026 ln = try_parse_header_line (ln, state)
1028 # Try nibbling characters off until the line doesn't change.
1030 while ln != prev_ln:
1032 ln = try_parse_chord_delims (ln, state)
1033 ln = try_parse_rest (ln, state)
1034 ln = try_parse_articulation (ln,state)
1035 ln = try_parse_note (ln, state)
1036 ln = try_parse_bar (ln, state)
1037 ln = try_parse_tie (ln)
1038 ln = try_parse_escape (ln)
1039 ln = try_parse_guitar_chord (ln, state)
1040 ln = try_parse_tuplet_begin (ln, state)
1041 ln = try_parse_group_end (ln, state)
1042 ln = try_parse_grace_delims (ln, state)
1043 ln = junk_space (ln)
1046 msg = "%s: %d: Huh? Don't understand\n" % (fn, lineno)
1047 sys.stderr.write (msg)
1048 left = orig_ln[0:-len (ln)]
1049 sys.stderr.write (left + '\n')
1050 sys.stderr.write (' ' * len (left) + ln + '\n')
1054 sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
1058 Convert ABC to Mudela.
1060 Usage: abc2ly [OPTIONS]... ABC-FILE
1063 -h, --help this help
1064 -o, --output=FILE set output filename to FILE
1065 -v, --version version information
1067 This program converts ABC music files (see
1068 http://www.gre.ac.uk/~c.walshaw/abc2mtex/abc.txt) To LilyPond input.
1071 def print_version ():
1072 print r"""abc2ly (GNU lilypond) %s""" % version
1076 (options, files) = getopt.getopt (sys.argv[1:], 'vo:h', ['help','version', 'output='])
1082 if o== '--help' or o == '-h':
1085 if o == '--version' or o == '-v':
1089 if o == '--output' or o == '-o':
1097 header['tagline'] = 'Lily was here %s -- automatically converted from ABC' % version
1102 sys.stderr.write ('Parsing... [%s]\n' % f)
1105 if not out_filename:
1106 out_filename = os.path.basename (os.path.splitext (f)[0]) + ".ly"
1107 sys.stderr.write ('Ly output to: %s...' % out_filename)
1108 outf = open (out_filename, 'w')
1110 # dump_global (outf)
1111 dump_header (outf ,header)
1116 sys.stderr.write ('\n')