3 # info mostly taken from looking at files. See also
4 # http://www.cs.uu.nl/~hanwen/lily-devel/etf.html
19 # * slur/stem directions
20 # * voices (2nd half of frame?)
21 # * more intelligent lyrics
22 # * beams (better use autobeam?)
23 # * more robust: try entertainer.etf (freenote)
27 program_name = 'etf2ly'
28 version = '@TOPLEVEL_VERSION@'
29 if version == '@' + 'TOPLEVEL_VERSION' + '@':
30 version = '(unknown version)' # uGUHGUHGHGUGH
39 finale_clefs= ['treble', 'alto', 'tenor', 'bass', 'percussion', 'treble8vb', 'bass8vb', 'baritone']
42 return finale_clefs[fin]
45 return open (f).read ()
47 # notename 0 == central C
48 distances = [0, 2, 4, 5, 7, 9, 11, 12]
49 def semitones (name, acc):
50 return (name / 7 ) * 12 + distances[name % 7] + acc
52 # represent pitches as (notename, alteration), relative to C-major scale
53 def transpose(orig, delta):
57 old_pitch =semitones (oname, oacc)
58 delta_pitch = semitones (dname, dacc)
59 nname = (oname + dname)
61 new_pitch = semitones (nname, nacc)
63 nacc = nacc - (new_pitch - old_pitch - delta_pitch)
69 # find transposition of C-major scale that belongs here.
70 def interpret_finale_key_sig (finale_id):
72 if 0 <= finale_id < 7:
74 p = transpose (p, (4,0)) # a fifth up
75 finale_id = finale_id - 1
76 elif 248 < finale_id <= 255:
77 while finale_id < 256:
78 p = transpose (p, (3,0))
79 finale_id = finale_id + 1
85 def find_scale (transposition):
86 cscale = map (lambda x: (x,0), range (0,7))
87 trscale = map(lambda x, k=transposition: transpose(x, k), cscale)
102 def rat_simplify (r):
113 def rat_multiply (a,b):
117 return rat_simplify ((x*p, y*q))
123 return rat_simplify ((x*q + p*y, y*q))
129 def rat_subtract (a,b ):
130 return rat_add (a, rat_neg (b))
132 def lily_notename (tuple2):
134 nn = chr ((n+ 2)%7 + ord ('a'))
149 def __init__ (self, number):
150 self.start_note = number
153 def append_finale (self, fin):
154 self.finale.append (fin)
157 n = self.finale[0][2]*self.finale[0][3]
158 d = self.finale[0][0]*self.finale[0][1]
159 return rat_simplify( (n, d))
161 def dump_start (self):
162 return '\\times %d/%d { ' % self.factor ()
167 def calculate (self, chords):
168 edu_left = self.finale[0][0] * self.finale[0][1]
170 startch = chords[self.start_note]
172 while c and edu_left:
175 c.chord_prefix = self.dump_start () + c.chord_prefix
178 edu_left = edu_left - c.EDU_duration ()
180 c.chord_suffix = c.chord_suffix+ self.dump_end ()
184 sys.stderr.write ("\nHuh? Tuplet starting at entry %d was too short." % self.start_note)
187 def __init__ (self, number):
191 def append_entry (self, finale_e):
192 self.finale.append (finale_e)
194 def calculate (self, chords):
195 startnote = self.finale[0][5]
196 endnote = self.finale[3][2]
198 cs = chords[startnote]
204 cs.note_suffix = '(' + cs.note_suffix
205 ce.note_prefix = ce.note_prefix + ')'
207 sys.stderr.write ("""\nHuh? Slur no %d between (%d,%d), with %d notes""" % (self.number, startnote, endnote, len (chords)))
210 class Global_measure:
211 def __init__ (self, number):
214 self.keysignature = None
220 return `self.finale `
222 def set_timesig (self, finale):
223 (beats, fdur) = finale
224 (log, dots) = EDU_to_duration (fdur)
226 self.timesig = (beats, log)
231 def set_keysig (self, finale):
232 k = interpret_finale_key_sig (finale)
233 self.keysignature = k
234 self.scale = find_scale (k)
242 18: '"arp"' , # arpeggio
246 def __init__ (self, a,b, finale):
247 self.type = finale[0]
249 def calculate (self, chords):
250 c = chords[self.notenumber]
253 a = articulation_dict[self.type]
255 sys.stderr.write ("\nUnknown articulation %d" % self.type)
258 c.note_suffix = '-' + a + c.note_suffix
261 def __init__ (self, a,b , finale):
263 self.syllable = finale[1]
264 self.verse = finale[0]
265 def calculate (self, chords, lyrics):
266 self.chord = chords[self.chordnum]
269 def __init__ (self, number, body):
272 self.split_syllables ()
273 def split_syllables (self):
274 ss = re.split ('(-| +)', self.body)
280 septor = re.sub (" +", "", s)
281 septor = re.sub ("-", " -- ", septor)
282 syls[-1] = syls[-1] + septor
288 self.syllables = syls
293 for s in self.syllables[1:]:
294 line = line + ' ' + s
296 str = str + ' ' * 4 + line + '\n'
299 str = """\nverse%s = \\lyrics {\n %s}\n""" % (encodeint (self.number - 1) ,str)
304 def __init__(self, no):
306 self.frames = [0] * 4
310 self.global_measure = None
313 def add_finale_entry (self, entry):
314 self.finale.append (entry)
316 def calculate (self):
317 if len (self.finale) < 2:
318 sys.stderr.write ("Measure %d in staff %d has incomplete information.\n" % (self.number, self.staff.number))
325 self.clef = string.atoi (f0[0])
326 self.flags = string.atoi (f0[1])
327 fs = map (string.atoi, list (f0[2:]) + [f1[0]])
332 def __init__ (self, finale):
335 (number, start, end ) = finale
341 def set_measure (self, m):
344 def calculate (self):
348 for c in self.chords:
349 if c.grace and (lastch == None or (not lastch.grace)):
350 c.chord_prefix = r'\grace {' + c.chord_prefix
351 elif not c.grace and lastch and lastch.grace:
352 lastch.chord_suffix = lastch.chord_suffix + ' } '
359 str = '%% FR(%d)\n' % self.number
360 left = self.measure.global_measure.length ()
364 for c in self.chords:
365 add = c.ly_string () + ' '
366 if len (ln) + len(add) > 72:
367 str = str + ln + '\n'
370 left = rat_subtract (left, c.length ())
375 sys.stderr.write ("""\nHuh? Going backwards in frame no %d, start/end (%d,%d)""" % (self.number, self.start, self.end))
378 str = str + rat_to_lily_duration (left)
384 return chr ( i + ord ('A'))
387 def __init__ (self, number):
391 def get_measure (self, no):
392 if len (self.measures) <= no:
393 self.measures = self.measures + [None]* (1 + no - len (self.measures))
395 if self.measures[no] == None:
397 self.measures [no] =m
401 return self.measures[no]
403 return 'staff' + encodeint (self.number - 1)
404 def layerid (self, l):
405 return self.staffid() + 'layer%s' % chr (l -1 + ord ('A'))
407 def dump_time_key_sigs (self):
413 for m in self.measures[1:]:
419 if last_key <> g.keysignature:
420 e = e + "\\key %s \\major; " % lily_notename (g.keysignature)
421 last_key = g.keysignature
422 if last_time <> g.timesig :
423 e = e + "\\time %d/%d; " % g.timesig
424 last_time = g.timesig
425 if last_clef <> m.clef :
426 e = e + '\\clef %s;' % lily_clef (m.clef)
430 k = k +' ' + rat_to_lily_duration (gap) + '\n'
434 gap = rat_add (gap, g.length ())
437 k = '%sglobal = \\notes { %s }\n\n ' % (self.staffid (), k)
445 for x in range (1,5): # 4 layers.
450 for m in self.measures[1:]:
459 laystr = laystr +'} %s {\n ' % rat_to_lily_duration (gap)
461 laystr = laystr + fr.dump ()
463 gap = rat_add (gap, m.global_measure.length ())
467 laystr = '%s = \\notes { { %s } }\n\n' % (l, laystr)
471 str = str + self.dump_time_key_sigs ()
472 stafdef = '\\%sglobal' % self.staffid ()
474 stafdef = stafdef + ' \\' + i
477 str = str + '%s = \\context Staff = %s <\n %s\n >\n' % \
478 (self.staffid (), self.staffid (), stafdef)
482 def EDU_to_duration (edu):
497 def rat_to_lily_duration (rat):
501 while d and d % 2 == 0:
502 basedur = basedur << 1
505 str = 's%d' % basedur
507 str = str + '*%d' % n
509 str = str + '/%d' % d
515 def __init__ (self, finale_entry):
518 self.finale = finale_entry
523 self.note_suffix = ''
524 self.chord_suffix = ''
525 self.chord_prefix = ''
532 return self.frame.measure
538 l = (1, self.duration[0])
540 d = 1 << self.duration[1]
542 dotfact = rat_subtract ((2,1), (1,d))
543 mylen = rat_multiply (dotfact, l)
546 mylen = rat_multiply (mylen, self.tuplet.factor())
550 return self.finale[0][0]
552 def EDU_duration (self):
553 return self.finale[0][3]
554 def set_duration (self):
555 self.duration = EDU_to_duration(self.EDU_duration ())
556 def calculate (self):
557 self.find_realpitch ()
560 flag = self.finale[0][5]
561 if Chord.GRACE_MASK & flag:
565 def find_realpitch (self):
567 ((no, prev, next, dur, pos, entryflag, extended, follow), notelist) = self.finale
569 meas = self.measure ()
571 if not meas or not meas.global_measure :
572 print 'note %d not in measure' % self.number ()
573 elif not meas.global_measure.scale:
574 print 'note %d: no scale in this measure.' % self.number ()
584 scale = meas.global_measure.scale
585 (sn, sa) =scale[rest % 7]
586 sn = sn + (rest - (rest%7)) + 7
588 self.pitches.append ((sn, acc))
589 tiestart = tiestart or (flag & Chord.TIE_START_MASK)
591 self.chord_suffix = self.chord_suffix + ' ~ '
593 REST_MASK = 0x40000000L
594 TIE_START_MASK = 0x40000000L
595 GRACE_MASK = 0x00800000L
597 def ly_string (self):
602 if not (self.finale[0][5] & Chord.REST_MASK):
605 for p in self.pitches:
610 nn = lily_notename ((n,a))
623 s = s + '%s%d%s' % (nn, self.duration[0], '.'* self.duration[1])
626 s = 'r%d%s' % (self.duration[0] , '.'* self.duration[1])
627 s = self.note_prefix + s + self.note_suffix
628 if len (self.pitches) > 1:
631 s = self.chord_prefix + s + self.chord_suffix
634 GFre = re.compile(r"""^\^GF\(([0-9-]+),([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
635 BCre = re.compile (r"""^\^BC\(([0-9-]+)\) ([0-9-]+) .*$""")
636 eEre = re.compile(r"""^\^eE\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) \$([0-9A-Fa-f]+) ([0-9-]+) ([0-9-]+)""")
637 FRre = re.compile (r"""^\^FR\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
638 MSre = re.compile (r"""^\^MS\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
639 note_re = re.compile (r"""^ +([0-9-]+) \$([A-Fa-f0-9]+)""")
640 Sxre = re.compile (r"""^\^Sx\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
641 IMre = re.compile (r"""^\^IM\(([0-9-]+),([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
642 vere = re.compile(r"""^\^(ve|ch|se)\(([0-9-]+),([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
643 versere = re.compile(r"""^\^verse\(([0-9]+)\)(.*)\^end""")
645 TPre = re.compile(r"""^\^TP\(([0-9]+),([0-9]+)\) *([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
649 def __init__ (self, name):
650 self.measures = [None]
651 self.entries = [None]
654 self.tuplets = [None]
657 self.articulations = [None]
658 self.syllables = [None]
664 def get_global_measure (self, no):
665 if len (self.measures) <= no:
666 self.measures = self.measures + [None]* (1 + no - len (self.measures))
668 if self.measures[no] == None:
669 self.measures [no] = Global_measure (no)
671 return self.measures[no]
674 def get_staff(self,staffno):
675 if len (self.staffs) <= staffno:
676 self.staffs = self.staffs + [None] * (1 + staffno - len (self.staffs))
678 if self.staffs[staffno] == None:
679 self.staffs[staffno] = Staff (staffno)
681 return self.staffs[staffno]
684 def try_IS (self, l):
687 def try_BC (self, l):
690 bn = string.atoi (m.group (1))
691 where = string.atoi (m.group (2)) / 1024.0
696 (nil, num) = map (string.atoi, (m.groups ()[0:2]))
697 entries = map (string.atoi, (m.groups ()[2:]))
699 if self.tuplets[-1] == None or num <> self.tuplets[-1].start_note:
700 self.tuplets.append (Tuplet (num))
702 self.tuplets[-1].append_finale (entries)
704 def try_IM (self, l):
707 a = string.atoi (m.group (1))
708 b = string.atoi (m.group (2))
710 fin = map (string.atoi, m.groups ()[2:])
712 self.articulations.append (Articulation (a,b,fin))
714 def try_verse (self,l):
715 m = versere .match (l)
717 a = string.atoi (m.group (1))
720 body = re.sub (r"""\^[a-z]+\([^)]+\)""", "", body)
721 body = re.sub ("\^[a-z]+", "", body)
722 self.verses.append (Verse (a, body))
728 a = string.atoi (m.group (1))
729 b = string.atoi (m.group (2))
731 fin = map (string.atoi, m.groups ()[2:])
733 self.syllables.append (Syllable (a,b,fin))
735 def try_eE (self, l):
739 (no, prev, next, dur, pos, entryflag, extended, follow) = tup
740 (no, prev, next, dur, pos,extended, follow) \
741 = tuple (map (string.atoi, [no,prev,next,dur,pos,extended,follow]))
743 entryflag = string.atol (entryflag,16)
744 if no > len (self.entries):
745 sys.stderr.write ("\nHuh? Entry number to large,\nexpected %d got %d. Filling with void entries.\n" % (len(self.entries), no ))
746 while len (self.entries) <> no:
747 c = ((len (self.entries), 0, 0, 0, 0, 0L, 0, 0), [])
748 self.entries.append (c)
750 current_entry = ((no, prev, next, dur, pos, entryflag, extended, follow), [])
751 self.entries.append (current_entry)
757 slurno = string.atoi (m.group (1))
759 if len (self.slurs) == slurno:
760 self.slurs.append (Slur (slurno))
762 params = list (m.groups ()[1:])
763 params = map (string.atoi, params)
764 self.slurs[-1].append_entry (params)
770 (staffno,measno) = m.groups ()[0:2]
771 s = string.atoi (staffno)
772 me = string.atoi (measno)
774 entry = m.groups () [2:]
775 st = self.get_staff (s)
776 meas = st.get_measure (me)
777 meas.add_finale_entry (entry)
783 (frameno, startnote, endnote, foo, bar) = m.groups ()
784 (frameno, startnote, endnote) = tuple (map (string.atoi, [frameno, startnote, endnote]))
785 if frameno > len (self.frames):
786 sys.stderr.write ("Frame no %d missing, filling up to %d\n" % (len(self.frames), frameno))
787 while frameno <> len (self.frames):
788 self.frames.append (Frame ((len (self.frames), 0,0) ))
790 self.frames.append (Frame ((frameno, startnote, endnote)))
793 def try_MS (self, l):
796 measno = string.atoi (m.group (1))
797 keynum = string.atoi (m.group (3))
798 meas =self. get_global_measure (measno)
799 meas.set_keysig (keynum)
801 beats = string.atoi (m.group (4))
802 beatlen = string.atoi (m.group (5))
803 meas.set_timesig ((beats, beatlen))
807 def try_note (self, l):
808 m = note_re.match (l)
810 (pitch, flag) = m.groups ()
811 pitch = string.atoi (pitch)
812 flag = string.atol (flag,16)
813 self.entries[-1][1].append ((pitch,flag))
815 def parse (self, name):
816 sys.stderr.write ('parsing ...')
819 gulp = open (name).read ()
821 gulp = re.sub ('[\n\r]+', '\n', gulp)
822 ls = string.split (gulp, '\n')
833 m = self.try_note (l)
843 m = self.try_verse (l)
845 sys.stderr.write ('processing ...')
848 self.unthread_entries ()
850 for st in self.staffs[1:]:
854 for m in st.measures[1:]:
858 m.global_measure = self.measures[mno]
861 frame_obj_list = [None]
862 for frno in m.frames:
863 fr = self.frames[frno]
864 frame_obj_list.append (fr)
866 m.frames = frame_obj_list
867 for fr in frame_obj_list[1:]:
873 fr.chords = self.get_thread (fr.start, fr.end)
878 for c in self.chords[1:]:
881 for f in self.frames[1:]:
884 for t in self.tuplets[1:]:
885 t.calculate (self.chords)
887 for s in self.slurs [1:]:
888 s.calculate (self.chords)
889 for s in self.articulations[1:]:
890 s.calculate (self.chords)
892 def get_thread (self, startno, endno):
895 c = self.chords[startno]
896 while c and c.number () <> endno:
908 for s in self.staffs[1:]:
910 str = str + '\n\n' + s.dump ()
911 staffs.append ('\\' + s.staffid ())
914 # should use \addlyrics ?
916 for v in self.verses[1:]:
919 if len (self.verses) > 1:
920 sys.stderr.write ("\nLyrics found; edit to use \\addlyrics to couple to a staff\n")
923 str = str + '\\score { < %s > } ' % string.join (staffs)
929 return 'ETF FILE %s %s' % (self.measures, self.entries)
931 def unthread_entries (self):
933 for e in self.entries[1:]:
934 self.chords.append (Chord (e))
936 for e in self.chords[1:]:
937 e.prev = self.chords[e.finale[0][1]]
938 e.next = self.chords[e.finale[0][2]]
946 sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
950 Convert ETF to LilyPond.
952 Usage: etf2ly [OPTION]... ETF-FILE
956 -o, --output=FILE set output filename to FILE
957 -v, --version version information
959 Enigma Transport Format is a format used by Coda Music Technology's
960 Finale product. This program will convert a subset of ETF to a
961 ready-to-use lilypond file.
966 def print_version ():
967 print r"""etf2ly (GNU lilypond) %s""" % version
971 (options, files) = getopt.getopt (sys.argv[1:], 'vo:h', ['help','version', 'output='])
977 if o== '--help' or o == '-h':
980 if o == '--version' or o == '-v':
984 if o == '--output' or o == '-o':
992 # header['tagline'] = 'Lily was here %s -- automatically converted from ABC' % version
997 sys.stderr.write ('Processing `%s\'\n' % f)
1000 out_filename = os.path.basename (re.sub ('(?i).etf$', '.ly', f))
1002 if out_filename == f:
1003 out_filename = os.path.basename (f + '.ly')
1005 sys.stderr.write ('Writing `%s\'' % out_filename)
1010 fo = open (out_filename, 'w')
1011 fo.write ('%% lily was here -- automatically converted by etf2ly from %s\n' % f)