Nitpick: ly:spanner-bound grob name slur -> spanner.
[lilypond.git] / scripts / etf2ly.py
blob54daa94decea6db273a297308eaa815797fb1321
1 #!@TARGET_PYTHON@
3 # info mostly taken from looking at files. See also
4 # http://lilypond.org/wiki/?EnigmaTransportFormat
6 # This supports
8 # * notes
9 # * rests
10 # * ties
11 # * slurs
12 # * lyrics
13 # * articulation
14 # * grace notes
15 # * tuplets
18 # todo:
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)
24 # * dynamics
25 # * empty measures (eg. twopt03.etf from freenote)
29 import __main__
30 import getopt
31 import sys
32 import re
33 import os
35 program_name = sys.argv[0]
37 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
38 'Han-Wen Nienhuys <hanwen@xs4all.nl>')
40 version = '@TOPLEVEL_VERSION@'
41 if version == '@' + 'TOPLEVEL_VERSION' + '@':
42 version = '(unknown version)' # uGUHGUHGHGUGH
44 """
45 @relocate-preamble@
46 """
48 ################################################################
50 import lilylib as ly
51 _ = ly._
53 finale_clefs= ['treble', 'alto', 'tenor', 'bass', 'percussion', 'treble_8', 'bass_8', 'baritone']
55 def lily_clef (fin):
56 try:
57 return finale_clefs[fin]
58 except IndexError:
59 sys.stderr.write ( '\nHuh? Found clef number %d\n' % fin)
61 return 'treble'
65 def gulp_file(f):
66 return open (f).read ()
68 # notename 0 == central C
69 distances = [0, 2, 4, 5, 7, 9, 11, 12]
70 def semitones (name, acc):
71 return (name / 7 ) * 12 + distances[name % 7] + acc
73 # represent pitches as (notename, alteration), relative to C-major scale
74 def transpose(orig, delta):
75 (oname, oacc) = orig
76 (dname, dacc) = delta
78 old_pitch =semitones (oname, oacc)
79 delta_pitch = semitones (dname, dacc)
80 nname = (oname + dname)
81 nacc = oacc
82 new_pitch = semitones (nname, nacc)
84 nacc = nacc - (new_pitch - old_pitch - delta_pitch)
86 return (nname, nacc)
90 def interpret_finale_key_sig (finale_id):
91 """
92 find the transposition of C-major scale that belongs here.
94 we are not going to insert the correct major/minor, we only want to
95 have the correct number of accidentals
96 """
98 p = (0,0)
101 bank_number = finale_id >> 8
102 accidental_bits = finale_id & 0xff
104 if 0 <= accidental_bits < 7:
105 while accidental_bits > 0:
106 p = transpose (p, (4,0)) # a fifth up
107 accidental_bits = accidental_bits - 1
108 elif 248 < accidental_bits <= 255:
109 while accidental_bits < 256:
110 p = transpose (p, (3,0))
111 accidental_bits = accidental_bits + 1
113 if bank_number == 1:
114 # minor scale
115 p = transpose (p, (5, 0))
116 p = (p[0] % 7, p[1])
118 return KeySignature (p, bank_number)
120 # should cache this.
121 def find_scale (keysig):
122 cscale = map (lambda x: (x,0), range (0,7))
123 # print "cscale: ", cscale
124 ascale = map (lambda x: (x,0), range (-2,5))
125 # print "ascale: ", ascale
126 transposition = keysig.pitch
127 if keysig.sig_type == 1:
128 transposition = transpose(transposition, (2, -1))
129 transposition = (transposition[0] % 7, transposition[1])
130 trscale = map(lambda x, k=transposition: transpose(x, k), ascale)
131 else:
132 trscale = map(lambda x, k=transposition: transpose(x, k), cscale)
133 # print "trscale: ", trscale
134 return trscale
136 def EDU_to_duration (edu):
137 log = 1
138 d = 4096
139 while d > edu:
140 d = d >> 1
141 log = log << 1
143 edu = edu - d
144 dots = 0
145 if edu == d /2:
146 dots = 1
147 elif edu == d*3/4:
148 dots = 2
149 return (log, dots)
151 def rational_to_lily_skip (rat):
152 (n,d) = rat
154 basedur = 1
155 while d and d % 2 == 0:
156 basedur = basedur << 1
157 d = d >> 1
159 str = 's%d' % basedur
160 if n <> 1:
161 str = str + '*%d' % n
162 if d <> 1:
163 str = str + '/%d' % d
165 return str
167 def gcd (a,b):
168 if b == 0:
169 return a
170 c = a
171 while c:
172 c = a % b
173 a = b
174 b = c
175 return a
178 def rat_simplify (r):
179 (n,d) = r
180 if d < 0:
181 d = -d
182 n = -n
183 if n == 0:
184 return (0,1)
185 else:
186 g = gcd (n, d)
187 return (n/g, d/g)
189 def rat_multiply (a,b):
190 (x,y) = a
191 (p,q) = b
193 return rat_simplify ((x*p, y*q))
195 def rat_add (a,b):
196 (x,y) = a
197 (p,q) = b
199 return rat_simplify ((x*q + p*y, y*q))
201 def rat_neg (a):
202 (p,q) = a
203 return (-p,q)
207 def rat_subtract (a,b ):
208 return rat_add (a, rat_neg (b))
210 def lily_notename (tuple2):
211 (n, a) = tuple2
212 nn = chr ((n+ 2)%7 + ord ('a'))
214 return nn + {-2:'eses', -1:'es', 0:'', 1:'is', 2:'isis'}[a]
217 class Tuplet:
218 def __init__ (self, number):
219 self.start_note = number
220 self.finale = []
222 def append_finale (self, fin):
223 self.finale.append (fin)
225 def factor (self):
226 n = self.finale[0][2]*self.finale[0][3]
227 d = self.finale[0][0]*self.finale[0][1]
228 return rat_simplify( (n, d))
230 def dump_start (self):
231 return '\\times %d/%d { ' % self.factor ()
233 def dump_end (self):
234 return ' }'
236 def calculate (self, chords):
237 edu_left = self.finale[0][0] * self.finale[0][1]
239 startch = chords[self.start_note]
240 c = startch
241 while c and edu_left:
242 c.tuplet = self
243 if c == startch:
244 c.chord_prefix = self.dump_start () + c.chord_prefix
246 if not c.grace:
247 edu_left = edu_left - c.EDU_duration ()
248 if edu_left == 0:
249 c.chord_suffix = c.chord_suffix+ self.dump_end ()
250 c = c.next
252 if edu_left:
253 sys.stderr.write ("\nHuh? Tuplet starting at entry %d was too short." % self.start_note)
255 class Slur:
256 def __init__ (self, number, params):
257 self.number = number
258 self.finale = params
260 def append_entry (self, finale_e):
261 self.finale.append (finale_e)
263 def calculate (self, chords):
264 startnote = self.finale[5]
265 endnote = self.finale[3*6 + 2]
266 try:
267 cs = chords[startnote]
268 ce = chords[endnote]
270 if not cs or not ce:
271 raise IndexError
273 cs.note_suffix = '-(' + cs.note_suffix
274 ce.note_suffix = ce.note_suffix + '-)'
276 except IndexError:
277 sys.stderr.write ("""\nHuh? Slur no %d between (%d,%d), with %d notes""" % (self.number, startnote, endnote, len (chords)))
280 class Global_measure:
281 def __init__ (self, number):
282 self.timesig = ''
283 self.number = number
284 self.key_signature = None
285 self.scale = None
286 self.force_break = 0
288 self.repeats = []
289 self.finale = []
291 def __str__ (self):
292 return `self.finale `
294 def set_timesig (self, finale):
295 (beats, fdur) = finale
296 (log, dots) = EDU_to_duration (fdur)
298 if dots == 1:
299 beats = beats * 3
300 log = log * 2
301 dots = 0
303 if dots <> 0:
304 sys.stderr.write ("\nHuh? Beat duration has dots? (EDU Duration = %d)" % fdur)
305 self.timesig = (beats, log)
307 def length (self):
308 return self.timesig
310 def set_key_sig (self, finale):
311 k = interpret_finale_key_sig (finale)
312 self.key_signature = k
313 self.scale = find_scale (k)
315 def set_flags (self,flag1, flag2):
317 # flag1 isn't all that interesting.
318 if flag2 & 0x8000:
319 self.force_break = 1
321 if flag2 & 0x0008:
322 self.repeats.append ('start')
323 if flag2 & 0x0004:
324 self.repeats.append ('stop')
326 if flag2 & 0x0002:
327 if flag2 & 0x0004:
328 self.repeats.append ('bracket')
330 articulation_dict ={
331 94: '^',
332 109: '\\prall',
333 84: '\\turn',
334 62: '\\mordent',
335 85: '\\fermata',
336 46: '.',
337 # 3: '>',
338 # 18: '\arpeggio' ,
341 class Articulation_def:
342 def __init__ (self, n, a, b):
343 self.finale_glyph = a & 0xff
344 self.number = n
346 def dump (self):
347 try:
348 return articulation_dict[self.finale_glyph]
349 except KeyError:
350 sys.stderr.write ("\nUnknown articulation no. %d" % self.finale_glyph)
351 sys.stderr.write ("\nPlease add an entry to articulation_dict in the Python source")
352 return None
354 class Articulation:
355 def __init__ (self, a,b, finale):
356 self.definition = finale[0]
357 self.notenumber = b
359 def calculate (self, chords, defs):
360 c = chords[self.notenumber]
362 adef = defs[self.definition]
363 lystr =adef.dump()
364 if lystr == None:
365 lystr = '"art"'
366 sys.stderr.write ("\nThis happened on note %d" % self.notenumber)
368 c.note_suffix = '-' + lystr
370 class Syllable:
371 def __init__ (self, a,b , finale):
372 self.chordnum = b
373 self.syllable = finale[1]
374 self.verse = finale[0]
375 def calculate (self, chords, lyrics):
376 self.chord = chords[self.chordnum]
378 class Verse:
379 def __init__ (self, number, body):
380 self.body = body
381 self.number = number
382 self.split_syllables ()
383 def split_syllables (self):
384 ss = re.split ('(-| +)', self.body)
386 sep = 0
387 syls = [None]
388 for s in ss:
389 if sep:
390 septor = re.sub (" +", "", s)
391 septor = re.sub ("-", " -- ", septor)
392 syls[-1] = syls[-1] + septor
393 else:
394 syls.append (s)
396 sep = not sep
398 self.syllables = syls
400 def dump (self):
401 str = ''
402 line = ''
403 for s in self.syllables[1:]:
404 line = line + ' ' + s
405 if len (line) > 72:
406 str = str + ' ' * 4 + line + '\n'
407 line = ''
409 str = """\nverse%s = \\lyricmode {\n %s }\n""" % (encodeint (self.number - 1) ,str)
410 return str
412 class KeySignature:
413 def __init__(self, pitch, sig_type = 0):
414 self.pitch = pitch
415 self.sig_type = sig_type
417 def signature_type (self):
418 if self.sig_type == 1:
419 return "\\minor"
420 else:
421 # really only for 0, but we only know about 0 and 1
422 return "\\major"
424 def equal (self, other):
425 if other and other.pitch == self.pitch and other.sig_type == self.sig_type:
426 return 1
427 else:
428 return 0
431 class Measure:
432 def __init__(self, no):
433 self.number = no
434 self.frames = [0] * 4
435 self.flags = 0
436 self.clef = 0
437 self.finale = []
438 self.global_measure = None
439 self.staff = None
440 self.valid = 1
443 def valid (self):
444 return self.valid
445 def calculate (self):
446 fs = []
448 if len (self.finale) < 2:
449 fs = self.finale[0]
451 self.clef = fs[1]
452 self.frames = [fs[0]]
453 else:
454 fs = self.finale
455 self.clef = fs[0]
456 self.flags = fs[1]
457 self.frames = fs[2:]
460 class Frame:
461 def __init__ (self, finale):
462 self.measure = None
463 self.finale = finale
464 (number, start, end ) = finale
465 self.number = number
466 self.start = start
467 self.end = end
468 self.chords = []
470 def set_measure (self, m):
471 self.measure = m
473 def calculate (self):
475 # do grace notes.
476 lastch = None
477 in_grace = 0
478 for c in self.chords:
479 if c.grace and (lastch == None or (not lastch.grace)):
480 c.chord_prefix = r'\grace {' + c.chord_prefix
481 in_grace = 1
482 elif not c.grace and lastch and lastch.grace:
483 lastch.chord_suffix = lastch.chord_suffix + ' } '
484 in_grace = 0
486 lastch = c
488 if lastch and in_grace:
489 lastch.chord_suffix += '}'
492 def dump (self):
493 str = '%% FR(%d)\n' % self.number
494 left = self.measure.global_measure.length ()
497 ln = ''
498 for c in self.chords:
499 add = c.ly_string () + ' '
500 if len (ln) + len(add) > 72:
501 str = str + ln + '\n'
502 ln = ''
503 ln = ln + add
504 left = rat_subtract (left, c.length ())
506 str = str + ln
508 if left[0] < 0:
509 sys.stderr.write ("""\nHuh? Going backwards in frame no %d, start/end (%d,%d)""" % (self.number, self.start, self.end))
510 left = (0,1)
511 if left[0]:
512 str = str + rational_to_lily_skip (left)
514 str = str + ' |\n'
515 return str
517 def encodeint (i):
518 return chr ( i + ord ('A'))
520 class Staff:
521 def __init__ (self, number):
522 self.number = number
523 self.measures = []
525 def get_measure (self, no):
526 fill_list_to (self.measures, no)
528 if self.measures[no] == None:
529 m = Measure (no)
530 self.measures [no] =m
531 m.staff = self
533 return self.measures[no]
534 def staffid (self):
535 return 'staff' + encodeint (self.number - 1)
536 def layerid (self, l):
537 return self.staffid() + 'layer%s' % chr (l -1 + ord ('A'))
539 def dump_time_key_sigs (self):
540 k = ''
541 last_key = None
542 last_time = None
543 last_clef = None
544 gap = (0,1)
545 for m in self.measures[1:]:
546 if not m or not m.valid:
547 continue # ugh.
549 g = m.global_measure
550 e = ''
552 if g:
553 if g.key_signature and not g.key_signature.equal(last_key):
554 pitch= g.key_signature.pitch
555 e = e + "\\key %s %s " % (lily_notename (pitch),
556 g.key_signature.signature_type())
558 last_key = g.key_signature
559 if last_time <> g.timesig :
560 e = e + "\\time %d/%d " % g.timesig
561 last_time = g.timesig
563 if 'start' in g.repeats:
564 e = e + ' \\bar "|:" '
567 # we don't attempt voltas since they fail easily.
568 if 0 : # and g.repeat_bar == '|:' or g.repeat_bar == ':|:' or g.bracket:
569 strs = []
570 if g.repeat_bar == '|:' or g.repeat_bar == ':|:' or g.bracket == 'end':
571 strs.append ('#f')
574 if g.bracket == 'start':
575 strs.append ('"0."')
577 str = ' '.join (['(volta %s)' % x for x in strs])
579 e = e + ' \\set Score.repeatCommands = #\'(%s) ' % str
581 if g.force_break:
582 e = e + ' \\break '
584 if last_clef <> m.clef :
585 e = e + '\\clef "%s"' % lily_clef (m.clef)
586 last_clef = m.clef
587 if e:
588 if gap <> (0,1):
589 k = k +' ' + rational_to_lily_skip (gap) + '\n'
590 gap = (0,1)
591 k = k + e
593 if g:
594 gap = rat_add (gap, g.length ())
595 if 'stop' in g.repeats:
596 k = k + ' \\bar ":|" '
598 k = '%sglobal = { %s }\n\n ' % (self.staffid (), k)
599 return k
601 def dump (self):
602 str = ''
605 layerids = []
606 for x in range (1,5): # 4 layers.
607 laystr = ''
608 last_frame = None
609 first_frame = None
610 gap = (0,1)
611 for m in self.measures[1:]:
612 if not m or not m.valid:
613 sys.stderr.write ("Skipping non-existant or invalid measure\n")
614 continue
616 fr = None
617 try:
618 fr = m.frames[x]
619 except IndexError:
620 sys.stderr.write ("Skipping nonexistent frame %d\n" % x)
621 laystr = laystr + "%% non existent frame %d (skipped)\n" % x
622 if fr:
623 first_frame = fr
624 if gap <> (0,1):
625 laystr = laystr +'} %s {\n ' % rational_to_lily_skip (gap)
626 gap = (0,1)
627 laystr = laystr + fr.dump ()
628 else:
629 if m.global_measure :
630 gap = rat_add (gap, m.global_measure.length ())
631 else:
632 sys.stderr.write ( \
633 "No global measure for staff %d measure %d\n"
634 % (self.number, m.number))
635 if first_frame:
636 l = self.layerid (x)
637 laystr = '%s = { { %s } }\n\n' % (l, laystr)
638 str = str + laystr
639 layerids.append (l)
641 str = str + self.dump_time_key_sigs ()
642 stafdef = '\\%sglobal' % self.staffid ()
643 for i in layerids:
644 stafdef = stafdef + ' \\' + i
647 str = str + '%s = \\context Staff = %s <<\n %s\n >>\n' % \
648 (self.staffid (), self.staffid (), stafdef)
649 return str
653 def ziplist (l):
654 if len (l) < 2:
655 return []
656 else:
657 return [(l[0], l[1])] + ziplist (l[2:])
660 class Chord:
661 def __init__ (self, number, contents):
662 self.pitches = []
663 self.frame = None
664 self.finale = contents[:7]
666 self.notelist = ziplist (contents[7:])
667 self.duration = None
668 self.next = None
669 self.prev = None
670 self.number = number
671 self.note_prefix= ''
672 self.note_suffix = ''
673 self.chord_suffix = ''
674 self.chord_prefix = ''
675 self.tuplet = None
676 self.grace = 0
678 def measure (self):
679 if not self.frame:
680 return None
681 return self.frame.measure
683 def length (self):
684 if self.grace:
685 return (0,1)
687 l = (1, self.duration[0])
689 d = 1 << self.duration[1]
691 dotfact = rat_subtract ((2,1), (1,d))
692 mylen = rat_multiply (dotfact, l)
694 if self.tuplet:
695 mylen = rat_multiply (mylen, self.tuplet.factor())
696 return mylen
699 def EDU_duration (self):
700 return self.finale[2]
701 def set_duration (self):
702 self.duration = EDU_to_duration(self.EDU_duration ())
704 def calculate (self):
705 self.find_realpitch ()
706 self.set_duration ()
708 flag = self.finale[4]
709 if Chord.GRACE_MASK & flag:
710 self.grace = 1
713 def find_realpitch (self):
715 meas = self.measure ()
716 tiestart = 0
717 if not meas or not meas.global_measure :
718 sys.stderr.write ('note %d not in measure\n' % self.number)
719 elif not meas.global_measure.scale:
720 sys.stderr.write ('note %d: no scale in this measure.' % self.number)
721 else:
723 for p in self.notelist:
724 (pitch, flag) = p
727 nib1 = pitch & 0x0f
729 if nib1 > 8:
730 nib1 = -(nib1 - 8)
731 rest = pitch / 16
733 scale = meas.global_measure.scale
734 (sn, sa) =scale[rest % 7]
735 sn = sn + (rest - (rest%7)) + 7
736 acc = sa + nib1
737 self.pitches.append ((sn, acc))
738 tiestart = tiestart or (flag & Chord.TIE_START_MASK)
739 if tiestart :
740 self.chord_suffix = self.chord_suffix + ' ~ '
742 REST_MASK = 0x40000000L
743 TIE_START_MASK = 0x40000000L
744 GRACE_MASK = 0x00800000L
746 def ly_string (self):
747 s = ''
749 rest = ''
752 if not (self.finale[4] & Chord.REST_MASK):
753 rest = 'r'
755 for p in self.pitches:
756 (n,a) = p
757 o = n/ 7
758 n = n % 7
760 nn = lily_notename ((n,a))
762 if o < 0:
763 nn = nn + (',' * -o)
764 elif o > 0:
765 nn = nn + ('\'' * o)
767 if s:
768 s = s + ' '
770 if rest:
771 nn = rest
773 s = s + nn
775 if not self.pitches:
776 s = 'r'
777 if len (self.pitches) > 1:
778 s = '<%s>' % s
780 s = s + '%d%s' % (self.duration[0], '.'* self.duration[1])
781 s = self.note_prefix + s + self.note_suffix
783 s = self.chord_prefix + s + self.chord_suffix
785 return s
788 def fill_list_to (list, no):
790 Add None to LIST until it contains entry number NO.
792 while len (list) <= no:
793 list.extend ([None] * (no - len(list) + 1))
794 return list
796 def read_finale_value (str):
798 Pry off one value from STR. The value may be $hex, decimal, or "string".
799 Return: (value, rest-of-STR)
801 while str and str[0] in ' \t\n':
802 str = str[1:]
804 if not str:
805 return (None,str)
807 if str[0] == '$':
808 str = str [1:]
810 hex = ''
811 while str and str[0] in '0123456789ABCDEF':
812 hex = hex + str[0]
813 str = str[1:]
816 return (long (hex, 16), str)
817 elif str[0] == '"':
818 str = str[1:]
819 s = ''
820 while str and str[0] <> '"':
821 s = s + str[0]
822 str = str[1:]
824 return (s,str)
825 elif str[0] in '-0123456789':
826 dec = ''
827 while str and str[0] in '-0123456789':
828 dec = dec + str[0]
829 str = str[1:]
831 return (int (dec), str)
832 else:
833 sys.stderr.write ("cannot convert `%s'\n" % str)
834 return (None, str)
839 def parse_etf_file (fn, tag_dict):
841 """ Read FN, putting ETF info into
842 a giant dictionary. The keys of TAG_DICT indicate which tags
843 to put into the dict.
846 sys.stderr.write ('parsing ... ' )
847 f = open (fn)
849 gulp = re.sub ('[\n\r]+', '\n', f.read ())
850 ls = gulp.split ('\n^')
852 etf_file_dict = {}
853 for k in tag_dict:
854 etf_file_dict[k] = {}
856 last_tag = None
857 last_numbers = None
860 for l in ls:
861 m = re.match ('^([a-zA-Z0-9&]+)\(([^)]+)\)', l)
862 if m and tag_dict.has_key (m.group (1)):
863 tag = m.group (1)
865 indices = tuple ([int (s) for s in m.group (2).split (',')])
866 content = l[m.end (2)+1:]
869 tdict = etf_file_dict[tag]
870 if not tdict.has_key (indices):
871 tdict[indices] = []
874 parsed = []
876 if tag == 'verse' or tag == 'block':
877 m2 = re.match ('(.*)\^end', content)
878 if m2:
879 parsed = [m2.group (1)]
880 else:
881 while content:
882 (v, content) = read_finale_value (content)
883 if v <> None:
884 parsed.append (v)
886 tdict [indices].extend (parsed)
888 last_indices = indices
889 last_tag = tag
891 continue
893 # let's not do this: this really confuses when eE happens to be before a ^text.
894 # if last_tag and last_indices:
895 # etf_file_dict[last_tag][last_indices].append (l)
897 sys.stderr.write ('\n')
898 return etf_file_dict
904 class Etf_file:
905 def __init__ (self, name):
906 self.measures = [None]
907 self.chords = [None]
908 self.frames = [None]
909 self.tuplets = [None]
910 self.staffs = [None]
911 self.slurs = [None]
912 self.articulations = [None]
913 self.syllables = [None]
914 self.verses = [None]
915 self.articulation_defs = [None]
917 ## do it
918 self.parse (name)
920 def get_global_measure (self, no):
921 fill_list_to (self.measures, no)
922 if self.measures[no] == None:
923 self.measures [no] = Global_measure (no)
925 return self.measures[no]
928 def get_staff(self,staffno):
929 fill_list_to (self.staffs, staffno)
930 if self.staffs[staffno] == None:
931 self.staffs[staffno] = Staff (staffno)
933 return self.staffs[staffno]
935 # staff-spec
936 def try_IS (self, indices, contents):
937 pass
939 def try_BC (self, indices, contents):
940 bn = indices[0]
941 where = contents[0] / 1024.0
942 def try_TP(self, indices, contents):
943 (nil, num) = indices
945 if self.tuplets[-1] == None or num <> self.tuplets[-1].start_note:
946 self.tuplets.append (Tuplet (num))
948 self.tuplets[-1].append_finale (contents)
950 def try_IM (self, indices, contents):
951 (a,b) = indices
952 fin = contents
953 self.articulations.append (Articulation (a,b,fin))
954 def try_verse (self, indices, contents):
955 a = indices[0]
956 body = contents[0]
958 body = re.sub (r"""\^[a-z]+\([^)]+\)""", "", body)
959 body = re.sub ("\^[a-z]+", "", body)
960 self.verses.append (Verse (a, body))
961 def try_ve (self,indices, contents):
962 (a,b) = indices
963 self.syllables.append (Syllable (a,b,contents))
965 def try_eE (self,indices, contents):
966 no = indices[0]
967 (prev, next, dur, pos, entryflag, extended, follow) = contents[:7]
969 fill_list_to (self.chords, no)
970 self.chords[no] =Chord (no, contents)
972 def try_Sx(self,indices, contents):
973 slurno = indices[0]
974 fill_list_to (self.slurs, slurno)
975 self.slurs[slurno] = Slur(slurno, contents)
977 def try_IX (self, indices, contents):
978 n = indices[0]
979 a = contents[0]
980 b = contents[1]
982 ix= None
983 try:
984 ix = self.articulation_defs[n]
985 except IndexError:
986 ix = Articulation_def (n,a,b)
987 self.articulation_defs.append (Articulation_def (n, a, b))
989 def try_GF(self, indices, contents):
990 (staffno,measno) = indices
992 st = self.get_staff (staffno)
993 meas = st.get_measure (measno)
994 meas.finale = contents
996 def try_FR(self, indices, contents):
997 frameno = indices [0]
999 startnote = contents[0]
1000 endnote = contents[1]
1002 fill_list_to (self.frames, frameno)
1004 self.frames[frameno] = Frame ((frameno, startnote, endnote))
1006 def try_MS (self, indices, contents):
1007 measno = indices[0]
1008 keynum = contents[1]
1009 meas =self. get_global_measure (measno)
1011 meas.set_key_sig (keynum)
1013 beats = contents[2]
1014 beatlen = contents[3]
1015 meas.set_timesig ((beats, beatlen))
1017 meas_flag1 = contents[4]
1018 meas_flag2 = contents[5]
1020 meas.set_flags (meas_flag1, meas_flag2);
1023 routine_dict = {
1024 'MS': try_MS,
1025 'FR': try_FR,
1026 'GF': try_GF,
1027 'IX': try_IX,
1028 'Sx' : try_Sx,
1029 'eE' : try_eE,
1030 'verse' : try_verse,
1031 've' : try_ve,
1032 'IM' : try_IM,
1033 'TP' : try_TP,
1034 'BC' : try_BC,
1035 'IS' : try_IS,
1038 def parse (self, etf_dict):
1039 sys.stderr.write ('reconstructing ...')
1040 sys.stderr.flush ()
1042 for (tag,routine) in Etf_file.routine_dict.items ():
1043 ks = etf_dict[tag].keys ()
1044 ks.sort ()
1045 for k in ks:
1046 routine (self, k, etf_dict[tag][k])
1048 sys.stderr.write ('processing ...')
1049 sys.stderr.flush ()
1051 self.unthread_entries ()
1053 for st in self.staffs[1:]:
1054 if not st:
1055 continue
1056 mno = 1
1057 for m in st.measures[1:]:
1058 if not m:
1059 continue
1061 m.calculate()
1062 try:
1063 m.global_measure = self.measures[mno]
1064 except IndexError:
1065 sys.stderr.write ("Non-existent global measure %d" % mno)
1066 continue
1068 frame_obj_list = [None]
1069 for frno in m.frames:
1070 try:
1071 fr = self.frames[frno]
1072 frame_obj_list.append (fr)
1073 except IndexError:
1074 sys.stderr.write ("\nNon-existent frame %d" % frno)
1076 m.frames = frame_obj_list
1077 for fr in frame_obj_list[1:]:
1078 if not fr:
1079 continue
1081 fr.set_measure (m)
1083 fr.chords = self.get_thread (fr.start, fr.end)
1084 for c in fr.chords:
1085 c.frame = fr
1086 mno = mno + 1
1088 for c in self.chords[1:]:
1089 if c:
1090 c.calculate()
1092 for f in self.frames[1:]:
1093 if f:
1094 f.calculate ()
1096 for t in self.tuplets[1:]:
1097 t.calculate (self.chords)
1099 for s in self.slurs[1:]:
1100 if s:
1101 s.calculate (self.chords)
1103 for s in self.articulations[1:]:
1104 s.calculate (self.chords, self.articulation_defs)
1106 def get_thread (self, startno, endno):
1108 thread = []
1110 c = None
1111 try:
1112 c = self.chords[startno]
1113 except IndexError:
1114 sys.stderr.write ("Huh? Frame has invalid bounds (%d,%d)\n" % (startno, endno))
1115 return []
1118 while c and c.number <> endno:
1119 thread.append (c)
1120 c = c.next
1122 if c:
1123 thread.append (c)
1125 return thread
1127 def dump (self):
1128 str = ''
1129 staffs = []
1130 for s in self.staffs[1:]:
1131 if s:
1132 str = str + '\n\n' + s.dump ()
1133 staffs.append ('\\' + s.staffid ())
1136 # should use \addlyrics ?
1138 for v in self.verses[1:]:
1139 str = str + v.dump()
1141 if len (self.verses) > 1:
1142 sys.stderr.write ("\nLyrics found; edit to use \\addlyrics to couple to a staff\n")
1144 if staffs:
1145 str += '\\version "2.3.25"\n'
1146 str = str + '<<\n %s\n>> } ' % ' '.join (staffs)
1148 return str
1151 def __str__ (self):
1152 return 'ETF FILE %s %s' % (self.measures, self.entries)
1154 def unthread_entries (self):
1155 for e in self.chords[1:]:
1156 if not e:
1157 continue
1159 e.prev = self.chords[e.finale[0]]
1160 e.next = self.chords[e.finale[1]]
1162 def identify():
1163 sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
1165 def warranty ():
1166 identify ()
1167 sys.stdout.write ('''
1174 ''' % ( _ ('Copyright (c) %s by') % '2001--2009',
1175 '\n '.join (authors),
1176 _ ('Distributed under terms of the GNU General Public License.'),
1177 _ ('It comes with NO WARRANTY.')))
1179 def get_option_parser ():
1180 p = ly.get_option_parser (usage=_ ("%s [OPTION]... ETF-FILE") % 'etf2ly',
1181 description=_ ("""Enigma Transport Format is a format used by Coda Music Technology's
1182 Finale product. etf2ly converts a subset of ETF to a ready-to-use LilyPond file.
1183 """),
1184 add_help_option=False)
1185 p.add_option("-h", "--help",
1186 action="help",
1187 help=_ ("show this help and exit"))
1188 p.version = "etf2ly (LilyPond) @TOPLEVEL_VERSION@"
1189 p.add_option("--version",
1190 action="version",
1191 help=_ ("show version number and exit"))
1192 p.add_option ('-o', '--output', help=_ ("write output to FILE"),
1193 metavar=_("FILE"),
1194 action='store')
1195 p.add_option ('-w', '--warranty', help=_ ("show warranty and copyright"),
1196 action='store_true',
1199 p.add_option_group ('',
1200 description=(
1201 _ ('Report bugs via %s')
1202 % 'http://post.gmane.org/post.php'
1203 '?group=gmane.comp.gnu.lilypond.bugs') + '\n')
1204 return p
1206 def do_options ():
1207 opt_parser = get_option_parser()
1208 (options,args) = opt_parser.parse_args ()
1209 if options.warranty:
1210 warranty ()
1211 sys.exit (0)
1213 return (options,args)
1215 (options, files) = do_options()
1216 identify()
1218 out_filename = options.output
1220 e = None
1221 for f in files:
1222 if f == '-':
1223 f = ''
1225 sys.stderr.write ('Processing `%s\'\n' % f)
1227 dict = parse_etf_file (f, Etf_file.routine_dict)
1228 e = Etf_file(dict)
1229 if not out_filename:
1230 out_filename = os.path.basename (re.sub ('(?i).etf$', '.ly', f))
1232 if out_filename == f:
1233 out_filename = os.path.basename (f + '.ly')
1235 sys.stderr.write ('Writing `%s\'' % out_filename)
1236 ly = e.dump()
1238 fo = open (out_filename, 'w')
1239 fo.write ('%% lily was here -- automatically converted by etf2ly from %s\n' % f)
1240 fo.write(ly)
1241 fo.close ()