abcjs 6.2.2 → 6.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/RELEASE.md +39 -0
  2. package/abc2xml_239/abc2xml.html +769 -0
  3. package/abc2xml_239/abc2xml.py +2248 -0
  4. package/abc2xml_239/abc2xml_changelog.html +124 -0
  5. package/abc2xml_239/lazy-river.abc +26 -0
  6. package/abc2xml_239/lazy-river.xml +3698 -0
  7. package/abc2xml_239/mean-to-me.abc +22 -0
  8. package/abc2xml_239/mean-to-me.xml +2954 -0
  9. package/abc2xml_239/pyparsing.py +3672 -0
  10. package/abc2xml_239/pyparsing.pyc +0 -0
  11. package/dist/abcjs-basic-min.js +2 -2
  12. package/dist/abcjs-basic.js +160 -71
  13. package/dist/abcjs-basic.js.map +1 -1
  14. package/dist/abcjs-plugin-min.js +2 -2
  15. package/package.json +1 -1
  16. package/src/api/abc_tablatures.js +3 -0
  17. package/src/api/abc_tunebook_svg.js +5 -3
  18. package/src/parse/abc_parse_music.js +18 -53
  19. package/src/parse/abc_parse_settings.js +165 -0
  20. package/src/synth/create-synth.js +4 -0
  21. package/src/synth/place-note.js +6 -0
  22. package/src/synth/play-event.js +7 -5
  23. package/src/tablatures/tab-absolute-elements.js +3 -2
  24. package/src/tablatures/tab-renderer.js +2 -1
  25. package/src/test/abc_parser_lint.js +12 -12
  26. package/src/write/creation/abstract-engraver.js +6 -0
  27. package/src/write/creation/decoration.js +2 -0
  28. package/src/write/creation/glyphs.js +1 -1
  29. package/src/write/draw/glissando.js +1 -0
  30. package/src/write/draw/set-paper-size.js +1 -1
  31. package/src/write/draw/tie.js +9 -1
  32. package/src/write/engraver-controller.js +7 -1
  33. package/src/write/interactive/selection.js +6 -0
  34. package/src/write/layout/layout.js +33 -3
  35. package/types/index.d.ts +28 -20
  36. package/version.js +1 -1
@@ -0,0 +1,2248 @@
1
+ #!/usr/bin/env python
2
+ # coding=latin-1
3
+ '''
4
+ Copyright (C) 2012-2018: Willem G. Vree
5
+ Contributions: Nils Liberg, Nicolas Froment, Norman Schmidt, Reinier Maliepaard, Martin Tarenskeen,
6
+ Paul Villiger, Alexander Scheutzow, Herbert Schneider, David Randolph, Michael Strasser
7
+
8
+ This program is free software; you can redistribute it and/or modify it under the terms of the
9
+ Lesser GNU General Public License as published by the Free Software Foundation;
10
+
11
+ This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
12
+ without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
+ See the Lesser GNU General Public License for more details. <http://www.gnu.org/licenses/lgpl.html>.
14
+ '''
15
+
16
+ from functools import reduce
17
+ from pyparsing import Word, OneOrMore, Optional, Literal, NotAny, MatchFirst
18
+ from pyparsing import Group, oneOf, Suppress, ZeroOrMore, Combine, FollowedBy
19
+ from pyparsing import srange, CharsNotIn, StringEnd, LineEnd, White, Regex
20
+ from pyparsing import nums, alphas, alphanums, ParseException, Forward
21
+ try: import xml.etree.cElementTree as E
22
+ except: import xml.etree.ElementTree as E
23
+ import types, sys, os, re, datetime
24
+
25
+ VERSION = 239
26
+
27
+ python3 = sys.version_info[0] > 2
28
+ lmap = lambda f, xs: list (map (f, xs)) # eager map for python 3
29
+ if python3:
30
+ int_type = int
31
+ list_type = list
32
+ str_type = str
33
+ uni_type = str
34
+ stdin = sys.stdin.buffer if sys.stdin else None # read binary if stdin available!
35
+ else:
36
+ int_type = types.IntType
37
+ list_type = types.ListType
38
+ str_type = types.StringTypes
39
+ uni_type = types.UnicodeType
40
+ stdin = sys.stdin
41
+
42
+ info_list = [] # diagnostic messages
43
+ def info (s, warn=1):
44
+ x = (warn and '-- ' or '') + s
45
+ info_list.append (x + '\n') # collect messages
46
+ if __name__ == '__main__': # only write to stdout when called as main progeam
47
+ try: sys.stderr.write (x + '\n')
48
+ except: sys.stderr.write (repr (x) + '\n')
49
+
50
+ def getInfo (): # get string of diagnostic messages, then clear messages
51
+ global info_list
52
+ xs = ''.join (info_list)
53
+ info_list = []
54
+ return xs
55
+
56
+ def abc_grammar (): # header, voice and lyrics grammar for ABC
57
+ #-----------------------------------------------------------------
58
+ # expressions that catch and skip some syntax errors (see corresponding parse expressions)
59
+ #-----------------------------------------------------------------
60
+ b1 = Word (u"-,'<>\u2019#", exact=1) # catch misplaced chars in chords
61
+ b2 = Regex ('[^H-Wh-w~=]*') # same in user defined symbol definition
62
+ b3 = Regex ('[^=]*') # same, second part
63
+
64
+ #-----------------------------------------------------------------
65
+ # ABC header (field_str elements are matched later with reg. epr's)
66
+ #-----------------------------------------------------------------
67
+
68
+ number = Word (nums).setParseAction (lambda t: int (t[0]))
69
+ field_str = Regex (r'[^]]*') # match anything until end of field
70
+ field_str.setParseAction (lambda t: t[0].strip ()) # and strip spacing
71
+
72
+ userdef_symbol = Word (srange ('[H-Wh-w~]'), exact=1)
73
+ fieldId = oneOf ('K L M Q P I T C O A Z N G H R B D F S E r Y') # info fields
74
+ X_field = Literal ('X') + Suppress (':') + field_str
75
+ U_field = Literal ('U') + Suppress (':') + b2 + Optional (userdef_symbol, 'H') + b3 + Suppress ('=') + field_str
76
+ V_field = Literal ('V') + Suppress (':') + Word (alphanums + '_') + field_str
77
+ inf_fld = fieldId + Suppress (':') + field_str
78
+ ifield = Suppress ('[') + (X_field | U_field | V_field | inf_fld) + Suppress (']')
79
+ abc_header = OneOrMore (ifield) + StringEnd ()
80
+
81
+ #---------------------------------------------------------------------------------
82
+ # I:score with recursive part groups and {* grand staff marker
83
+ #---------------------------------------------------------------------------------
84
+
85
+ voiceId = Suppress (Optional ('*')) + Word (alphanums + '_')
86
+ voice_gr = Suppress ('(') + OneOrMore (voiceId | Suppress ('|')) + Suppress (')')
87
+ simple_part = voiceId | voice_gr | Suppress ('|')
88
+ grand_staff = oneOf ('{* {') + OneOrMore (simple_part) + Suppress ('}')
89
+ part = Forward ()
90
+ part_seq = OneOrMore (part | Suppress ('|'))
91
+ brace_gr = Suppress ('{') + part_seq + Suppress ('}')
92
+ bracket_gr = Suppress ('[') + part_seq + Suppress (']')
93
+ part <<= MatchFirst (simple_part | grand_staff | brace_gr | bracket_gr | Suppress ('|'))
94
+ abc_scoredef = Suppress (oneOf ('staves score')) + OneOrMore (part)
95
+
96
+ #----------------------------------------
97
+ # ABC lyric lines (white space sensitive)
98
+ #----------------------------------------
99
+
100
+ skip_note = oneOf ('* - ~')
101
+ extend_note = Literal ('_')
102
+ measure_end = Literal ('|')
103
+ syl_str = CharsNotIn ('*~-_| \t\n\\]')
104
+ syl_chars = Combine (OneOrMore (syl_str | Regex (r'\\.')))
105
+ white = Word (' \t')
106
+ syllable = Combine (Optional ('~') + syl_chars + ZeroOrMore (Literal ('~') + syl_chars)) + Optional ('-')
107
+ lyr_elem = (syllable | skip_note | extend_note | measure_end) + Optional (white).suppress ()
108
+ lyr_line = Optional (white).suppress () + ZeroOrMore (lyr_elem)
109
+
110
+ syllable.setParseAction (lambda t: pObj ('syl', t))
111
+ skip_note.setParseAction (lambda t: pObj ('skip', t))
112
+ extend_note.setParseAction (lambda t: pObj ('ext', t))
113
+ measure_end.setParseAction (lambda t: pObj ('sbar', t))
114
+ lyr_line_wsp = lyr_line.leaveWhitespace () # parse actions must be set before calling leaveWhitespace
115
+
116
+ #---------------------------------------------------------------------------------
117
+ # ABC voice (not white space sensitive, beams detected in note/rest parse actions)
118
+ #---------------------------------------------------------------------------------
119
+
120
+ inline_field = Suppress ('[') + (inf_fld | U_field | V_field) + Suppress (']')
121
+ lyr_fld = Suppress ('[') + Suppress ('w') + Suppress (':') + lyr_line_wsp + Suppress (']') # lyric line
122
+ lyr_blk = OneOrMore (lyr_fld) # verses
123
+ fld_or_lyr = inline_field | lyr_blk # inline field or block of lyric verses
124
+
125
+ note_length = Optional (number, 1) + Group (ZeroOrMore ('/')) + Optional (number, 2)
126
+ octaveHigh = OneOrMore ("'").setParseAction (lambda t: len(t))
127
+ octaveLow = OneOrMore (',').setParseAction (lambda t: -len(t))
128
+ octave = octaveHigh | octaveLow
129
+
130
+ basenote = oneOf ('C D E F G A B c d e f g a b y') # includes spacer for parse efficiency
131
+ accidental = oneOf ('^^ __ ^ _ =')
132
+ rest_sym = oneOf ('x X z Z')
133
+ slur_beg = oneOf ("( (, (' .( .(, .('") + ~Word (nums) # no tuplet_start
134
+ slur_ends = OneOrMore (oneOf (') .)'))
135
+
136
+ long_decoration = Combine (oneOf ('! +') + CharsNotIn ('!+ \n') + oneOf ('! +'))
137
+ staccato = Literal ('.') + ~Literal ('|') # avoid dotted barline
138
+ pizzicato = Literal ('!+!') # special case: plus sign is old style deco marker
139
+ decoration = slur_beg | staccato | userdef_symbol | long_decoration | pizzicato
140
+ decorations = OneOrMore (decoration)
141
+
142
+ tie = oneOf ('.- -')
143
+ rest = Optional (accidental) + rest_sym + note_length
144
+ pitch = Optional (accidental) + basenote + Optional (octave, 0)
145
+ note = pitch + note_length + Optional (tie) + Optional (slur_ends)
146
+ dec_note = Optional (decorations) + pitch + note_length + Optional (tie) + Optional (slur_ends)
147
+ chord_note = dec_note | rest | b1
148
+ grace_notes = Forward ()
149
+ chord = Suppress ('[') + OneOrMore (chord_note | grace_notes) + Suppress (']') + note_length + Optional (tie) + Optional (slur_ends)
150
+ stem = note | chord | rest
151
+
152
+ broken = Combine (OneOrMore ('<') | OneOrMore ('>'))
153
+
154
+ tuplet_num = Suppress ('(') + number
155
+ tuplet_into = Suppress (':') + Optional (number, 0)
156
+ tuplet_notes = Suppress (':') + Optional (number, 0)
157
+ tuplet_start = tuplet_num + Optional (tuplet_into + Optional (tuplet_notes))
158
+
159
+ acciaccatura = Literal ('/')
160
+ grace_stem = Optional (decorations) + stem
161
+ grace_notes <<= Group (Suppress ('{') + Optional (acciaccatura) + OneOrMore (grace_stem) + Suppress ('}'))
162
+
163
+ text_expression = Optional (oneOf ('^ _ < > @'), '^') + Optional (CharsNotIn ('"'), "")
164
+ chord_accidental = oneOf ('# b =')
165
+ triad = oneOf ('ma Maj maj M mi min m aug dim o + -')
166
+ seventh = oneOf ('7 ma7 Maj7 M7 maj7 mi7 min7 m7 dim7 o7 -7 aug7 +7 m7b5 mi7b5')
167
+ sixth = oneOf ('6 ma6 M6 mi6 min6 m6')
168
+ ninth = oneOf ('9 ma9 M9 maj9 Maj9 mi9 min9 m9')
169
+ elevn = oneOf ('11 ma11 M11 maj11 Maj11 mi11 min11 m11')
170
+ thirt = oneOf ('13 ma13 M13 maj13 Maj13 mi13 min13 m13')
171
+ suspended = oneOf ('sus sus2 sus4')
172
+ chord_degree = Combine (Optional (chord_accidental) + oneOf ('2 4 5 6 7 9 11 13'))
173
+ chord_kind = Optional (seventh | sixth | ninth | elevn | thirt | triad) + Optional (suspended)
174
+ chord_root = oneOf ('C D E F G A B') + Optional (chord_accidental)
175
+ chord_bass = oneOf ('C D E F G A B') + Optional (chord_accidental) # needs a different parse action
176
+ chordsym = chord_root + chord_kind + ZeroOrMore (chord_degree) + Optional (Suppress ('/') + chord_bass)
177
+ chord_sym = chordsym + Optional (Literal ('(') + CharsNotIn (')') + Literal (')')).suppress ()
178
+ chord_or_text = Suppress ('"') + (chord_sym ^ text_expression) + Suppress ('"')
179
+
180
+ volta_nums = Optional ('[').suppress () + Combine (Word (nums) + ZeroOrMore (oneOf (', -') + Word (nums)))
181
+ volta_text = Literal ('[').suppress () + Regex (r'"[^"]+"')
182
+ volta = volta_nums | volta_text
183
+ invisible_barline = oneOf ('[|] []')
184
+ dashed_barline = oneOf (': .|')
185
+ double_rep = Literal (':') + FollowedBy (':') # otherwise ambiguity with dashed barline
186
+ voice_overlay = Combine (OneOrMore ('&'))
187
+ bare_volta = FollowedBy (Literal ('[') + Word (nums)) # no barline, but volta follows (volta is parsed in next measure)
188
+ bar_left = (oneOf ('[|: |: [: :') + Optional (volta)) | Optional ('|').suppress () + volta | oneOf ('| [|')
189
+ bars = ZeroOrMore (':') + ZeroOrMore ('[') + OneOrMore (oneOf ('| ]'))
190
+ bar_right = invisible_barline | double_rep | Combine (bars) | dashed_barline | voice_overlay | bare_volta
191
+
192
+ errors = ~bar_right + Optional (Word (' \n')) + CharsNotIn (':&|', exact=1)
193
+ linebreak = Literal ('$') | ~decorations + Literal ('!') # no need for I:linebreak !!!
194
+ element = fld_or_lyr | broken | decorations | stem | chord_or_text | grace_notes | tuplet_start | linebreak | errors
195
+ measure = Group (ZeroOrMore (inline_field) + Optional (bar_left) + ZeroOrMore (element) + bar_right + Optional (linebreak) + Optional (lyr_blk))
196
+ noBarMeasure = Group (ZeroOrMore (inline_field) + Optional (bar_left) + OneOrMore (element) + Optional (linebreak) + Optional (lyr_blk))
197
+ abc_voice = ZeroOrMore (measure) + Optional (noBarMeasure | Group (bar_left)) + ZeroOrMore (inline_field).suppress () + StringEnd ()
198
+
199
+ #----------------------------------------
200
+ # I:percmap note [step] [midi] [note-head]
201
+ #----------------------------------------
202
+
203
+ white2 = (white | StringEnd ()).suppress ()
204
+ w3 = Optional (white2)
205
+ percid = Word (alphanums + '-')
206
+ step = basenote + Optional (octave, 0)
207
+ pitchg = Group (Optional (accidental, '') + step + FollowedBy (white2))
208
+ stepg = Group (step + FollowedBy (white2)) | Literal ('*')
209
+ midi = (Literal ('*') | number | pitchg | percid)
210
+ nhd = Optional (Combine (percid + Optional ('+')), '')
211
+ perc_wsp = Literal ('percmap') + w3 + pitchg + w3 + Optional (stepg, '*') + w3 + Optional (midi, '*') + w3 + nhd
212
+ abc_percmap = perc_wsp.leaveWhitespace ()
213
+
214
+ #----------------------------------------------------------------
215
+ # Parse actions to convert all relevant results into an abstract
216
+ # syntax tree where all tree nodes are instances of pObj
217
+ #----------------------------------------------------------------
218
+
219
+ ifield.setParseAction (lambda t: pObj ('field', t))
220
+ grand_staff.setParseAction (lambda t: pObj ('grand', t, 1)) # 1 = keep ordered list of results
221
+ brace_gr.setParseAction (lambda t: pObj ('bracegr', t, 1))
222
+ bracket_gr.setParseAction (lambda t: pObj ('bracketgr', t, 1))
223
+ voice_gr.setParseAction (lambda t: pObj ('voicegr', t, 1))
224
+ voiceId.setParseAction (lambda t: pObj ('vid', t, 1))
225
+ abc_scoredef.setParseAction (lambda t: pObj ('score', t, 1))
226
+ note_length.setParseAction (lambda t: pObj ('dur', (t[0], (t[2] << len (t[1])) >> 1)))
227
+ chordsym.setParseAction (lambda t: pObj ('chordsym', t))
228
+ chord_root.setParseAction (lambda t: pObj ('root', t))
229
+ chord_kind.setParseAction (lambda t: pObj ('kind', t))
230
+ chord_degree.setParseAction (lambda t: pObj ('degree', t))
231
+ chord_bass.setParseAction (lambda t: pObj ('bass', t))
232
+ text_expression.setParseAction (lambda t: pObj ('text', t))
233
+ inline_field.setParseAction (lambda t: pObj ('inline', t))
234
+ lyr_fld.setParseAction (lambda t: pObj ('lyr_fld', t, 1))
235
+ lyr_blk.setParseAction (lambda t: pObj ('lyr_blk', t, 1)) # 1 = keep ordered list of lyric lines
236
+ grace_notes.setParseAction (doGrace)
237
+ acciaccatura.setParseAction (lambda t: pObj ('accia', t))
238
+ note.setParseAction (noteActn)
239
+ rest.setParseAction (restActn)
240
+ decorations.setParseAction (lambda t: pObj ('deco', t))
241
+ pizzicato.setParseAction (lambda t: ['!plus!']) # translate !+!
242
+ slur_ends.setParseAction (lambda t: pObj ('slurs', t))
243
+ chord.setParseAction (lambda t: pObj ('chord', t, 1))
244
+ dec_note.setParseAction (noteActn)
245
+ tie.setParseAction (lambda t: pObj ('tie', t))
246
+ pitch.setParseAction (lambda t: pObj ('pitch', t))
247
+ bare_volta.setParseAction (lambda t: ['|']) # return barline that user forgot
248
+ dashed_barline.setParseAction (lambda t: ['.|'])
249
+ bar_right.setParseAction (lambda t: pObj ('rbar', t))
250
+ bar_left.setParseAction (lambda t: pObj ('lbar', t))
251
+ broken.setParseAction (lambda t: pObj ('broken', t))
252
+ tuplet_start.setParseAction (lambda t: pObj ('tup', t))
253
+ linebreak.setParseAction (lambda t: pObj ('linebrk', t))
254
+ measure.setParseAction (doMaat)
255
+ noBarMeasure.setParseAction (doMaat)
256
+ b1.setParseAction (errorWarn)
257
+ b2.setParseAction (errorWarn)
258
+ b3.setParseAction (errorWarn)
259
+ errors.setParseAction (errorWarn)
260
+
261
+ return abc_header, abc_voice, abc_scoredef, abc_percmap
262
+
263
+ class pObj (object): # every relevant parse result is converted into a pObj
264
+ def __init__ (s, name, t, seq=0): # t = list of nested parse results
265
+ s.name = name # name uniqueliy identifies this pObj
266
+ rest = [] # collect parse results that are not a pObj
267
+ attrs = {} # new attributes
268
+ for x in t: # nested pObj's become attributes of this pObj
269
+ if type (x) == pObj:
270
+ attrs [x.name] = attrs.get (x.name, []) + [x]
271
+ else:
272
+ rest.append (x) # collect non-pObj's (mostly literals)
273
+ for name, xs in attrs.items ():
274
+ if len (xs) == 1: xs = xs[0] # only list if more then one pObj
275
+ setattr (s, name, xs) # create the new attributes
276
+ s.t = rest # all nested non-pObj's (mostly literals)
277
+ s.objs = seq and t or [] # for nested ordered (lyric) pObj's
278
+
279
+ def __repr__ (s): # make a nice string representation of a pObj
280
+ r = []
281
+ for nm in dir (s):
282
+ if nm.startswith ('_'): continue # skip build in attributes
283
+ elif nm == 'name': continue # redundant
284
+ else:
285
+ x = getattr (s, nm)
286
+ if not x: continue # s.t may be empty (list of non-pObj's)
287
+ if type (x) == list_type: r.extend (x)
288
+ else: r.append (x)
289
+ xs = []
290
+ for x in r: # recursively call __repr__ and convert all strings to latin-1
291
+ if isinstance (x, str_type): xs.append (x) # string -> no recursion
292
+ else: xs.append (repr (x)) # pObj -> recursive call
293
+ return '(' + s.name + ' ' +','.join (xs) + ')'
294
+
295
+ global prevloc # global to remember previous match position of a note/rest
296
+ prevloc = 0
297
+ def detectBeamBreak (line, loc, t):
298
+ global prevloc # location in string 'line' of previous note match
299
+ xs = line[prevloc:loc+1] # string between previous and current note match
300
+ xs = xs.lstrip () # first note match starts on a space!
301
+ prevloc = loc # location in string 'line' of current note match
302
+ b = pObj ('bbrk', [' ' in xs]) # space somewhere between two notes -> beambreak
303
+ t.insert (0, b) # insert beambreak as a nested parse result
304
+
305
+ def noteActn (line, loc, t): # detect beambreak between previous and current note/rest
306
+ if 'y' in t[0].t: return [] # discard spacer
307
+ detectBeamBreak (line, loc, t) # adds beambreak to parse result t as side effect
308
+ return pObj ('note', t)
309
+
310
+ def restActn (line, loc, t): # detect beambreak between previous and current note/rest
311
+ detectBeamBreak (line, loc, t) # adds beambreak to parse result t as side effect
312
+ return pObj ('rest', t)
313
+
314
+ def errorWarn (line, loc, t): # warning for misplaced symbols and skip them
315
+ if not t[0]: return [] # only warn if catched string not empty
316
+ info ('**misplaced symbol: %s' % t[0], warn=0)
317
+ lineCopy = line [:]
318
+ if loc > 40:
319
+ lineCopy = line [loc - 40: loc + 40]
320
+ loc = 40
321
+ info (lineCopy.replace ('\n', ' '), warn=0)
322
+ info (loc * '-' + '^', warn=0)
323
+ return []
324
+
325
+ #-------------------------------------------------------------
326
+ # transformations of a measure (called by parse action doMaat)
327
+ #-------------------------------------------------------------
328
+
329
+ def simplify (a, b): # divide a and b by their greatest common divisor
330
+ x, y = a, b
331
+ while b: a, b = b, a % b
332
+ return x // a, y // a
333
+
334
+ def doBroken (prev, brk, x):
335
+ if not prev: info ('error in broken rhythm: %s' % x); return # no changes
336
+ nom1, den1 = prev.dur.t # duration of first note/chord
337
+ nom2, den2 = x.dur.t # duration of second note/chord
338
+ if brk == '>':
339
+ nom1, den1 = simplify (3 * nom1, 2 * den1)
340
+ nom2, den2 = simplify (1 * nom2, 2 * den2)
341
+ elif brk == '<':
342
+ nom1, den1 = simplify (1 * nom1, 2 * den1)
343
+ nom2, den2 = simplify (3 * nom2, 2 * den2)
344
+ elif brk == '>>':
345
+ nom1, den1 = simplify (7 * nom1, 4 * den1)
346
+ nom2, den2 = simplify (1 * nom2, 4 * den2)
347
+ elif brk == '<<':
348
+ nom1, den1 = simplify (1 * nom1, 4 * den1)
349
+ nom2, den2 = simplify (7 * nom2, 4 * den2)
350
+ else: return # give up
351
+ prev.dur.t = nom1, den1 # change duration of previous note/chord
352
+ x.dur.t = nom2, den2 # and current note/chord
353
+
354
+ def convertBroken (t): # convert broken rhythms to normal note durations
355
+ prev = None # the last note/chord before the broken symbol
356
+ brk = '' # the broken symbol
357
+ remove = [] # indexes to broken symbols (to be deleted) in measure
358
+ for i, x in enumerate (t): # scan all elements in measure
359
+ if x.name == 'note' or x.name == 'chord' or x.name == 'rest':
360
+ if brk: # a broken symbol was encountered before
361
+ doBroken (prev, brk, x) # change duration previous note/chord/rest and current one
362
+ brk = ''
363
+ else:
364
+ prev = x # remember the last note/chord/rest
365
+ elif x.name == 'broken':
366
+ brk = x.t[0] # remember the broken symbol (=string)
367
+ remove.insert (0, i) # and its index, highest index first
368
+ for i in remove: del t[i] # delete broken symbols from high to low
369
+
370
+ def ptc2midi (n): # convert parsed pitch attribute to a midi number
371
+ pt = getattr (n, 'pitch', '')
372
+ if pt:
373
+ p = pt.t
374
+ if len (p) == 3: acc, step, oct = p
375
+ else: acc = ''; step, oct = p
376
+ nUp = step.upper ()
377
+ oct = (4 if nUp == step else 5) + int (oct)
378
+ midi = oct * 12 + [0,2,4,5,7,9,11]['CDEFGAB'.index (nUp)] + {'^':1,'_':-1}.get (acc, 0) + 12
379
+ else: midi = 130 # all non pitch objects first
380
+ return midi
381
+
382
+ def convertChord (t): # convert chord to sequence of notes in musicXml-style
383
+ ins = []
384
+ for i, x in enumerate (t):
385
+ if x.name == 'chord':
386
+ if hasattr (x, 'rest') and not hasattr (x, 'note'): # chords containing only rests
387
+ if type (x.rest) == list_type: x.rest = x.rest[0] # more rests == one rest
388
+ ins.insert (0, (i, [x.rest])) # just output a single rest, no chord
389
+ continue
390
+ num1, den1 = x.dur.t # chord duration
391
+ tie = getattr (x, 'tie', None) # chord tie
392
+ slurs = getattr (x, 'slurs', []) # slur endings
393
+ if type (x.note) != list_type: x.note = [x.note] # when chord has only one note ...
394
+ elms = []; j = 0 # sort chord notes, highest first
395
+ nss = sorted (x.objs, key = ptc2midi, reverse=1) if mxm.orderChords else x.objs
396
+ for nt in nss: # all chord elements (note | decorations | rest | grace note)
397
+ if nt.name == 'note':
398
+ num2, den2 = nt.dur.t # note duration * chord duration
399
+ nt.dur.t = simplify (num1 * num2, den1 * den2)
400
+ if tie: nt.tie = tie # tie on all chord notes
401
+ if j == 0 and slurs: nt.slurs = slurs # slur endings only on first chord note
402
+ if j > 0: nt.chord = pObj ('chord', [1]) # label all but first as chord notes
403
+ else: # remember all pitches of the chord in the first note
404
+ pitches = [n.pitch for n in x.note] # to implement conversion of erroneous ties to slurs
405
+ nt.pitches = pObj ('pitches', pitches)
406
+ j += 1
407
+ if nt.name not in ['dur','tie','slurs','rest']: elms.append (nt)
408
+ ins.insert (0, (i, elms)) # chord position, [note|decotation|grace note]
409
+ for i, notes in ins: # insert from high to low
410
+ for nt in reversed (notes):
411
+ t.insert (i+1, nt) # insert chord notes after chord
412
+ del t[i] # remove chord itself
413
+
414
+ def doMaat (t): # t is a Group() result -> the measure is in t[0]
415
+ convertBroken (t[0]) # remove all broken rhythms and convert to normal durations
416
+ convertChord (t[0]) # replace chords by note sequences in musicXML style
417
+
418
+ def doGrace (t): # t is a Group() result -> the grace sequence is in t[0]
419
+ convertChord (t[0]) # a grace sequence may have chords
420
+ for nt in t[0]: # flag all notes within the grace sequence
421
+ if nt.name == 'note': nt.grace = 1 # set grace attribute
422
+ return t[0] # ungroup the parse result
423
+ #--------------------
424
+ # musicXML generation
425
+ #----------------------------------
426
+
427
+ def compChordTab (): # avoid some typing work: returns mapping constant {ABC chordsyms -> musicXML kind}
428
+ maj, min, aug, dim, dom, ch7, ch6, ch9, ch11, ch13, hd = 'major minor augmented diminished dominant -seventh -sixth -ninth -11th -13th half-diminished'.split ()
429
+ triad = zip ('ma Maj maj M mi min m aug dim o + -'.split (), [maj, maj, maj, maj, min, min, min, aug, dim, dim, aug, min])
430
+ seventh = zip ('7 ma7 Maj7 M7 maj7 mi7 min7 m7 dim7 o7 -7 aug7 +7 m7b5 mi7b5'.split (),
431
+ [dom, maj+ch7, maj+ch7, maj+ch7, maj+ch7, min+ch7, min+ch7, min+ch7, dim+ch7, dim+ch7, min+ch7, aug+ch7, aug+ch7, hd, hd])
432
+ sixth = zip ('6 ma6 M6 mi6 min6 m6'.split (), [maj+ch6, maj+ch6, maj+ch6, min+ch6, min+ch6, min+ch6])
433
+ ninth = zip ('9 ma9 M9 maj9 Maj9 mi9 min9 m9'.split (), [dom+ch9, maj+ch9, maj+ch9, maj+ch9, maj+ch9, min+ch9, min+ch9, min+ch9])
434
+ elevn = zip ('11 ma11 M11 maj11 Maj11 mi11 min11 m11'.split (), [dom+ch11, maj+ch11, maj+ch11, maj+ch11, maj+ch11, min+ch11, min+ch11, min+ch11])
435
+ thirt = zip ('13 ma13 M13 maj13 Maj13 mi13 min13 m13'.split (), [dom+ch13, maj+ch13, maj+ch13, maj+ch13, maj+ch13, min+ch13, min+ch13, min+ch13])
436
+ sus = zip ('sus sus4 sus2'.split (), ['suspended-fourth', 'suspended-fourth', 'suspended-second'])
437
+ return dict (list (triad) + list (seventh) + list (sixth) + list (ninth) + list (elevn) + list (thirt) + list (sus))
438
+
439
+ def addElem (parent, child, level):
440
+ indent = 2
441
+ chldrn = list (parent)
442
+ if chldrn:
443
+ chldrn[-1].tail += indent * ' '
444
+ else:
445
+ parent.text = '\n' + level * indent * ' '
446
+ parent.append (child)
447
+ child.tail = '\n' + (level-1) * indent * ' '
448
+
449
+ def addElemT (parent, tag, text, level):
450
+ e = E.Element (tag)
451
+ e.text = text
452
+ addElem (parent, e, level)
453
+ return e
454
+
455
+ def mkTmod (tmnum, tmden, lev):
456
+ tmod = E.Element ('time-modification')
457
+ addElemT (tmod, 'actual-notes', str (tmnum), lev + 1)
458
+ addElemT (tmod, 'normal-notes', str (tmden), lev + 1)
459
+ return tmod
460
+
461
+ def addDirection (parent, elems, lev, gstaff, subelms=[], placement='below', cue_on=0):
462
+ dir = E.Element ('direction', placement=placement)
463
+ addElem (parent, dir, lev)
464
+ if type (elems) != list_type: elems = [(elems, subelms)] # ugly hack to provide for multiple direction types
465
+ for elem, subelms in elems: # add direction types
466
+ typ = E.Element ('direction-type')
467
+ addElem (dir, typ, lev + 1)
468
+ addElem (typ, elem, lev + 2)
469
+ for subel in subelms: addElem (elem, subel, lev + 3)
470
+ if cue_on: addElem (dir, E.Element ('level', size='cue'), lev + 1)
471
+ if gstaff: addElemT (dir, 'staff', str (gstaff), lev + 1)
472
+ return dir
473
+
474
+ def removeElems (root_elem, parent_str, elem_str):
475
+ for p in root_elem.findall (parent_str):
476
+ e = p.find (elem_str)
477
+ if e != None: p.remove (e)
478
+
479
+ def alignLyr (vce, lyrs):
480
+ empty_el = pObj ('leeg', '*')
481
+ for k, lyr in enumerate (lyrs): # lyr = one full line of lyrics
482
+ i = 0 # syl counter
483
+ for elem in vce: # reiterate the voice block for each lyrics line
484
+ if elem.name == 'note' and not (hasattr (elem, 'chord') or hasattr (elem, 'grace')):
485
+ if i >= len (lyr): lr = empty_el
486
+ else: lr = lyr [i]
487
+ lr.t[0] = lr.t[0].replace ('%5d',']')
488
+ elem.objs.append (lr)
489
+ if lr.name != 'sbar': i += 1
490
+ if elem.name == 'rbar' and i < len (lyr) and lyr[i].name == 'sbar': i += 1
491
+ return vce
492
+
493
+ slur_move = re.compile (r'(?<![!+])([}><][<>]?)(\)+)') # (?<!...) means: not preceeded by ...
494
+ mm_rest = re.compile (r'([XZ])(\d+)')
495
+ bar_space = re.compile (r'([:|][ |\[\]]+[:|])') # barlines with spaces
496
+ def fixSlurs (x): # repair slurs when after broken sign or grace-close
497
+ def f (mo): # replace a multi-measure rest by single measure rests
498
+ n = int (mo.group (2))
499
+ return (n * (mo.group (1) + '|')) [:-1]
500
+ def g (mo): # squash spaces in barline expressions
501
+ return mo.group (1).replace (' ','')
502
+ x = mm_rest.sub (f, x)
503
+ x = bar_space.sub (g, x)
504
+ return slur_move.sub (r'\2\1', x)
505
+
506
+ def splitHeaderVoices (abctext):
507
+ escField = lambda x: '[' + x.replace (']',r'%5d') + ']' # hope nobody uses %5d in a field
508
+ r1 = re.compile (r'%.*$') # comments
509
+ r2 = re.compile (r'^([A-Zw]:.*$)|\[[A-Zw]:[^]]*]$') # information field, including lyrics
510
+ r3 = re.compile (r'^%%(?=[^%])') # directive: ^%% folowed by not a %
511
+ xs, nx, mcont, fcont = [], 0, 0, 0 # result lines, X-encountered, music continuation, field continuation
512
+ mln = fln = '' # music line, field line
513
+ for x in abctext.splitlines ():
514
+ x = x.strip ()
515
+ if not x and nx == 1: break # end of tune (empty line)
516
+ if x.startswith ('X:'):
517
+ if nx == 1: break # second tune starts without an empty line !!
518
+ nx = 1 # start first tune
519
+ x = r3.sub ('I:', x) # replace %% -> I:
520
+ x2 = r1.sub ('', x) # remove comment
521
+ while x2.endswith ('*') and not (x2.startswith ('w:') or x2.startswith ('+:') or 'percmap' in x2):
522
+ x2 = x2[:-1] # remove old syntax for right adjusting
523
+ if not x2: continue # empty line
524
+ if x2[:2] == 'W:':
525
+ field = x2 [2:].strip ()
526
+ ftype = mxm.metaMap.get ('W', 'W') # respect the (user defined --meta) mapping of various ABC fields to XML meta data types
527
+ c = mxm.metadata.get (ftype, '')
528
+ mxm.metadata [ftype] = c + '\n' + field if c else field # concatenate multiple info fields with new line as separator
529
+ continue # skip W: lyrics
530
+ if x2[:2] == '+:': # field continuation
531
+ fln += x2[2:]
532
+ continue
533
+ ro = r2.match (x2) # single field on a line
534
+ if ro: # field -> inline_field, escape all ']'
535
+ if fcont: # old style \-info-continuation active
536
+ fcont = x2 [-1] == '\\' # possible further \-info-continuation
537
+ fln += re.sub (r'^.:(.*?)\\*$', r'\1', x2) # add continuation, remove .: and \
538
+ continue
539
+ if fln: mln += escField (fln)
540
+ if x2.startswith ('['): x2 = x2.strip ('[]')
541
+ fcont = x2 [-1] == '\\' # first encounter of old style \-info-continuation
542
+ fln = x2.rstrip ('\\') # remove continuation from field and inline brackets
543
+ continue
544
+ if nx == 1: # x2 is a new music line
545
+ fcont = 0 # stop \-continuations (-> only adjacent \-info-continuations are joined)
546
+ if fln:
547
+ mln += escField (fln)
548
+ fln = ''
549
+ if mcont:
550
+ mcont = x2 [-1] == '\\'
551
+ mln += x2.rstrip ('\\')
552
+ else:
553
+ if mln: xs.append (mln); mln = ''
554
+ mcont = x2 [-1] == '\\'
555
+ mln = x2.rstrip ('\\')
556
+ if not mcont: xs.append (mln); mln = ''
557
+ if fln: mln += escField (fln)
558
+ if mln: xs.append (mln)
559
+
560
+ hs = re.split (r'(\[K:[^]]*\])', xs [0]) # look for end of header K:
561
+ if len (hs) == 1: header = hs[0]; xs [0] = '' # no K: present
562
+ else: header = hs [0] + hs [1]; xs [0] = ''.join (hs[2:]) # h[1] is the first K:
563
+ abctext = '\n'.join (xs) # the rest is body text
564
+ hfs, vfs = [], []
565
+ for x in header[1:-1].split (']['):
566
+ if x[0] == 'V': vfs.append (x) # filter voice- and midi-definitions
567
+ elif x[:6] == 'I:MIDI': vfs.append (x) # from the header to vfs
568
+ elif x[:9] == 'I:percmap': vfs.append (x) # and also percmap
569
+ else: hfs.append (x) # all other fields stay in header
570
+ header = '[' + ']['.join (hfs) + ']' # restore the header
571
+ abctext = ('[' + ']['.join (vfs) + ']' if vfs else '') + abctext # prepend voice/midi from header before abctext
572
+
573
+ xs = abctext.split ('[V:')
574
+ if len (xs) == 1: abctext = '[V:1]' + abctext # abc has no voice defs at all
575
+ elif re.sub (r'\[[A-Z]:[^]]*\]', '', xs[0]).strip (): # remove inline fields from starting text, if any
576
+ abctext = '[V:1]' + abctext # abc with voices has no V: at start
577
+
578
+ r1 = re.compile (r'\[V:\s*(\S*)[ \]]') # get voice id from V: field (skip spaces betwee V: and ID)
579
+ vmap = {} # {voice id -> [voice abc string]}
580
+ vorder = {} # mark document order of voices
581
+ xs = re.split (r'(\[V:[^]]*\])', abctext) # split on every V-field (V-fields included in split result list)
582
+ if len (xs) == 1: raise ValueError ('bugs ...')
583
+ else:
584
+ pm = re.findall (r'\[P:.\]', xs[0]) # all P:-marks after K: but before first V:
585
+ if pm: xs[2] = ''.join (pm) + xs[2] # prepend P:-marks to the text of the first voice
586
+ header += re.sub (r'\[P:.\]', '', xs[0]) # clear all P:-marks from text between K: and first V: and put text in the header
587
+ i = 1
588
+ while i < len (xs): # xs = ['', V-field, voice abc, V-field, voice abc, ...]
589
+ vce, abc = xs[i:i+2]
590
+ id = r1.search (vce).group (1) # get voice ID from V-field
591
+ if not id: id, vce = '1', '[V:1]' # voice def has no ID
592
+ vmap[id] = vmap.get (id, []) + [vce, abc] # collect abc-text for each voice id (include V-fields)
593
+ if id not in vorder: vorder [id] = i # store document order of first occurrence of voice id
594
+ i += 2
595
+ voices = []
596
+ ixs = sorted ([(i, id) for id, i in vorder.items ()]) # restore document order of voices
597
+ for i, id in ixs:
598
+ voice = ''.join (vmap [id]) # all abc of one voice
599
+ voice = fixSlurs (voice) # put slurs right after the notes
600
+ voices.append ((id, voice))
601
+ return header, voices
602
+
603
+ def mergeMeasure (m1, m2, slur_offset, voice_offset, rOpt, is_grand=0, is_overlay=0):
604
+ slurs = m2.findall ('note/notations/slur')
605
+ for slr in slurs:
606
+ slrnum = int (slr.get ('number')) + slur_offset
607
+ slr.set ('number', str (slrnum)) # make unique slurnums in m2
608
+ vs = m2.findall ('note/voice') # set all voice number elements in m2
609
+ for v in vs: v.text = str (voice_offset + int (v.text))
610
+ ls = m1.findall ('note/lyric') # all lyric elements in m1
611
+ lnum_max = max ([int (l.get ('number')) for l in ls] + [0]) # highest lyric number in m1
612
+ ls = m2.findall ('note/lyric') # update lyric elements in m2
613
+ for el in ls:
614
+ n = int (el.get ('number'))
615
+ el.set ('number', str (n + lnum_max))
616
+ ns = m1.findall ('note') # determine the total duration of m1, subtract all backups
617
+ dur1 = sum (int (n.find ('duration').text) for n in ns
618
+ if n.find ('grace') == None and n.find ('chord') == None)
619
+ dur1 -= sum (int (b.text) for b in m1.findall ('backup/duration'))
620
+ repbar, nns, es = 0, 0, [] # nns = number of real notes in m2
621
+ for e in list (m2): # scan all elements of m2
622
+ if e.tag == 'attributes':
623
+ if not is_grand: continue # no attribute merging for normal voices
624
+ else: nns += 1 # but we do merge (clef) attributes for a grand staff
625
+ if e.tag == 'print': continue
626
+ if e.tag == 'note' and (rOpt or e.find ('rest') == None): nns += 1
627
+ if e.tag == 'barline' and e.find ('repeat') != None: repbar = e;
628
+ es.append (e) # buffer elements to be merged
629
+ if nns > 0: # only merge if m2 contains any real notes
630
+ if dur1 > 0: # only insert backup if duration of m1 > 0
631
+ b = E.Element ('backup')
632
+ addElem (m1, b, level=3)
633
+ addElemT (b, 'duration', str (dur1), level=4)
634
+ for e in es: addElem (m1, e, level=3) # merge buffered elements of m2
635
+ elif is_overlay and repbar: addElem (m1, repbar, level=3) # merge repeat in empty overlay
636
+
637
+ def mergePartList (parts, rOpt, is_grand=0): # merge parts, make grand staff when is_grand true
638
+
639
+ def delAttrs (part): # for the time being we only keep clef attributes
640
+ xs = [(m, e) for m in part.findall ('measure') for e in m.findall ('attributes')]
641
+ for m, e in xs:
642
+ for c in list (e):
643
+ if c.tag == 'clef': continue # keep clef attribute
644
+ if c.tag == 'staff-details': continue # keep staff-details attribute
645
+ e.remove (c) # delete all other attrinutes for higher staff numbers
646
+ if len (list (e)) == 0: m.remove (e) # remove empty attributes element
647
+
648
+ p1 = parts[0]
649
+ for p2 in parts[1:]:
650
+ if is_grand: delAttrs (p2) # delete all attributes except clef
651
+ for i in range (len (p1) + 1, len (p2) + 1): # second part longer than first one
652
+ maat = E.Element ('measure', number = str(i)) # append empty measures
653
+ addElem (p1, maat, 2)
654
+ slurs = p1.findall ('measure/note/notations/slur') # find highest slur num in first part
655
+ slur_max = max ([int (slr.get ('number')) for slr in slurs] + [0])
656
+ vs = p1.findall ('measure/note/voice') # all voice number elements in first part
657
+ vnum_max = max ([int (v.text) for v in vs] + [0]) # highest voice number in first part
658
+ for im, m2 in enumerate (p2.findall ('measure')): # merge all measures of p2 into p1
659
+ mergeMeasure (p1[im], m2, slur_max, vnum_max, rOpt, is_grand) # may change slur numbers in p1
660
+ return p1
661
+
662
+ def mergeParts (parts, vids, staves, rOpt, is_grand=0):
663
+ if not staves: return parts, vids # no voice mapping
664
+ partsnew, vidsnew = [], []
665
+ for voice_ids in staves:
666
+ pixs = []
667
+ for vid in voice_ids:
668
+ if vid in vids: pixs.append (vids.index (vid))
669
+ else: info ('score partname %s does not exist' % vid)
670
+ if pixs:
671
+ xparts = [parts[pix] for pix in pixs]
672
+ if len (xparts) > 1: mergedpart = mergePartList (xparts, rOpt, is_grand)
673
+ else: mergedpart = xparts [0]
674
+ partsnew.append (mergedpart)
675
+ vidsnew.append (vids [pixs[0]])
676
+ return partsnew, vidsnew
677
+
678
+ def mergePartMeasure (part, msre, ovrlaynum, rOpt): # merge msre into last measure of part, only for overlays
679
+ slur_offset = 0; # slur numbers determined by the slurstack size (as in a single voice)
680
+ last_msre = list (part)[-1] # last measure in part
681
+ mergeMeasure (last_msre, msre, slur_offset, ovrlaynum, rOpt, is_overlay=1) # voice offset = s.overlayVNum
682
+
683
+ def pushSlur (boogStapel, stem):
684
+ if stem not in boogStapel: boogStapel [stem] = [] # initialize slurstack for stem
685
+ boognum = sum (map (len, boogStapel.values ())) + 1 # number of open slurs in all (overlay) voices
686
+ boogStapel [stem].append (boognum)
687
+ return boognum
688
+
689
+ def setFristVoiceNameFromGroup (vids, vdefs): # vids = [vid], vdef = {vid -> (name, subname, voicedef)}
690
+ vids = [v for v in vids if v in vdefs] # only consider defined voices
691
+ if not vids: return vdefs
692
+ vid0 = vids [0] # first vid of the group
693
+ _, _, vdef0 = vdefs [vid0] # keep de voice definition (vdef0) when renaming vid0
694
+ for vid in vids:
695
+ nm, snm, vdef = vdefs [vid]
696
+ if nm: # first non empty name encountered will become
697
+ vdefs [vid0] = nm, snm, vdef0 # name of merged group == name of first voice in group (vid0)
698
+ break
699
+ return vdefs
700
+
701
+ def mkGrand (p, vdefs): # transform parse subtree into list needed for s.grands
702
+ xs = []
703
+ for i, x in enumerate (p.objs): # changing p.objs [i] alters the tree. changing x has no effect on the tree.
704
+ if type (x) == pObj:
705
+ us = mkGrand (x, vdefs) # first get transformation results of current pObj
706
+ if x.name == 'grand': # x.objs contains ordered list of nested parse results within x
707
+ vids = [y.objs[0] for y in x.objs[1:]] # the voice ids in the grand staff
708
+ nms = [vdefs [u][0] for u in vids if u in vdefs] # the names of those voices
709
+ accept = sum ([1 for nm in nms if nm]) == 1 # accept as grand staff when only one of the voices has a name
710
+ if accept or us[0] == '{*':
711
+ xs.append (us[1:]) # append voice ids as a list (discard first item '{' or '{*')
712
+ vdefs = setFristVoiceNameFromGroup (vids, vdefs)
713
+ p.objs [i] = x.objs[1] # replace voices by first one in the grand group (this modifies the parse tree)
714
+ else:
715
+ xs.extend (us[1:]) # extend current result with all voice ids of rejected grand staff
716
+ else: xs.extend (us) # extend current result with transformed pObj
717
+ else: xs.append (p.t[0]) # append the non pObj (== voice id string)
718
+ return xs
719
+
720
+ def mkStaves (p, vdefs): # transform parse tree into list needed for s.staves
721
+ xs = []
722
+ for i, x in enumerate (p.objs): # structure and comments identical to mkGrand
723
+ if type (x) == pObj:
724
+ us = mkStaves (x, vdefs)
725
+ if x.name == 'voicegr':
726
+ xs.append (us)
727
+ vids = [y.objs[0] for y in x.objs]
728
+ vdefs = setFristVoiceNameFromGroup (vids, vdefs)
729
+ p.objs [i] = x.objs[0]
730
+ else:
731
+ xs.extend (us)
732
+ else:
733
+ if p.t[0] not in '{*': xs.append (p.t[0])
734
+ return xs
735
+
736
+ def mkGroups (p): # transform parse tree into list needed for s.groups
737
+ xs = []
738
+ for x in p.objs:
739
+ if type (x) == pObj:
740
+ if x.name == 'vid': xs.extend (mkGroups (x))
741
+ elif x.name == 'bracketgr': xs.extend (['['] + mkGroups (x) + [']'])
742
+ elif x.name == 'bracegr': xs.extend (['{'] + mkGroups (x) + ['}'])
743
+ else: xs.extend (mkGroups (x) + ['}']) # x.name == 'grand' == rejected grand staff
744
+ else:
745
+ xs.append (p.t[0])
746
+ return xs
747
+
748
+ def stepTrans (step, soct, clef): # [A-G] (1...8)
749
+ if clef.startswith ('bass'):
750
+ nm7 = 'C,D,E,F,G,A,B'.split (',')
751
+ n = 14 + nm7.index (step) - 12 # two octaves extra to avoid negative numbers
752
+ step, soct = nm7 [n % 7], soct + n // 7 - 2 # subtract two octaves again
753
+ return step, soct
754
+
755
+ def reduceMids (parts, vidsnew, midiInst): # remove redundant instruments from a part
756
+ for pid, part in zip (vidsnew, parts):
757
+ mids, repls, has_perc = {}, {}, 0
758
+ for ipid, ivid, ch, prg, vol, pan in sorted (list (midiInst.values ())):
759
+ if ipid != pid: continue # only instruments from part pid
760
+ if ch == '10': has_perc = 1; continue # only consider non percussion instruments
761
+ instId, inst = 'I%s-%s' % (ipid, ivid), (ch, prg)
762
+ if inst in mids: # midi instrument already defined in this part
763
+ repls [instId] = mids [inst] # remember to replace instId by inst (see below)
764
+ del midiInst [instId] # instId is redundant
765
+ else: mids [inst] = instId # collect unique instruments in this part
766
+ if len (mids) < 2 and not has_perc: # only one instrument used -> no instrument tags needed in notes
767
+ removeElems (part, 'measure/note', 'instrument') # no instrument tag needed for one- or no-instrument parts
768
+ else:
769
+ for e in part.findall ('measure/note/instrument'):
770
+ id = e.get ('id') # replace all redundant instrument Id's
771
+ if id in repls: e.set ('id', repls [id])
772
+
773
+ class stringAlloc:
774
+ def __init__ (s):
775
+ s.snaarVrij = [] # [[(t1, t2) ...] for each string ]
776
+ s.snaarIx = [] # index in snaarVrij for each string
777
+ s.curstaff = -1 # staff being allocated
778
+ def beginZoek (s): # reset snaarIx at start of each voice
779
+ s.snaarIx = []
780
+ for i in range (len (s.snaarVrij)): s.snaarIx.append (0)
781
+ def setlines (s, stflines, stfnum):
782
+ if stfnum != s.curstaff: # initialize for new staff
783
+ s.curstaff = stfnum
784
+ s.snaarVrij = []
785
+ for i in range (stflines): s.snaarVrij.append ([])
786
+ s.beginZoek ()
787
+ def isVrij (s, snaar, t1, t2): # see if string snaar is free between t1 and t2
788
+ xs = s.snaarVrij [snaar]
789
+ for i in range (s.snaarIx [snaar], len (xs)):
790
+ tb, te = xs [i]
791
+ if t1 >= te: continue # te_prev < t1 <= te
792
+ if t1 >= tb: s.snaarIx [snaar] = i; return 0 # tb <= t1 < te
793
+ if t2 > tb: s.snaarIx [snaar] = i; return 0 # t1 < tb < t2
794
+ s.snaarIx [snaar] = i; # remember position for next call
795
+ xs.insert (i, (t1,t2)) # te_prev < t1 < t2 < tb
796
+ return 1
797
+ xs.append ((t1,t2))
798
+ s.snaarIx [snaar] = len (xs) - 1
799
+ return 1
800
+ def bezet (s, snaar, t1, t2): # force allocation of note (t1,t2) on string snaar
801
+ xs = s.snaarVrij [snaar]
802
+ for i, (tb, te) in enumerate (xs):
803
+ if t1 >= te: continue # te_prev < t1 <= te
804
+ xs.insert (i, (t1, t2))
805
+ return
806
+ xs.append ((t1,t2))
807
+
808
+ class MusicXml:
809
+ typeMap = {1:'long', 2:'breve', 4:'whole', 8:'half', 16:'quarter', 32:'eighth', 64:'16th', 128:'32nd', 256:'64th'}
810
+ dynaMap = {'p':1,'pp':1,'ppp':1,'pppp':1,'f':1,'ff':1,'fff':1,'ffff':1,'mp':1,'mf':1,'sfz':1}
811
+ tempoMap = {'larghissimo':40, 'moderato':104, 'adagissimo':44, 'allegretto':112, 'lentissimo':48, 'allegro':120, 'largo':56,
812
+ 'vivace':168, 'adagio':59, 'vivo':180, 'lento':62, 'presto':192, 'larghetto':66, 'allegrissimo':208, 'adagietto':76,
813
+ 'vivacissimo':220, 'andante':88, 'prestissimo':240, 'andantino':96}
814
+ wedgeMap = {'>(':1, '>)':1, '<(':1,'<)':1,'crescendo(':1,'crescendo)':1,'diminuendo(':1,'diminuendo)':1}
815
+ artMap = {'.':'staccato','>':'accent','accent':'accent','wedge':'staccatissimo','tenuto':'tenuto',
816
+ 'breath':'breath-mark','marcato':'strong-accent','^':'strong-accent','slide':'scoop'}
817
+ ornMap = {'trill':'trill-mark','T':'trill-mark','turn':'turn','uppermordent':'inverted-mordent','lowermordent':'mordent',
818
+ 'pralltriller':'inverted-mordent','mordent':'mordent','turn':'turn','invertedturn':'inverted-turn'}
819
+ tecMap = {'upbow':'up-bow', 'downbow':'down-bow', 'plus':'stopped','open':'open-string','snap':'snap-pizzicato',
820
+ 'thumb':'thumb-position'}
821
+ capoMap = {'fine':('Fine','fine','yes'), 'D.S.':('D.S.','dalsegno','segno'), 'D.C.':('D.C.','dacapo','yes'),'dacapo':('D.C.','dacapo','yes'),
822
+ 'dacoda':('To Coda','tocoda','coda'), 'coda':('coda','coda','coda'), 'segno':('segno','segno','segno')}
823
+ sharpness = ['Fb', 'Cb','Gb','Db','Ab','Eb','Bb','F','C','G','D','A', 'E', 'B', 'F#','C#','G#','D#','A#','E#','B#']
824
+ offTab = {'maj':8, 'm':11, 'min':11, 'mix':9, 'dor':10, 'phr':12, 'lyd':7, 'loc':13}
825
+ modTab = {'maj':'major', 'm':'minor', 'min':'minor', 'mix':'mixolydian', 'dor':'dorian', 'phr':'phrygian', 'lyd':'lydian', 'loc':'locrian'}
826
+ clefMap = { 'alto1':('C','1'), 'alto2':('C','2'), 'alto':('C','3'), 'alto4':('C','4'), 'tenor':('C','4'),
827
+ 'bass3':('F','3'), 'bass':('F','4'), 'treble':('G','2'), 'perc':('percussion',''), 'none':('',''), 'tab':('TAB','5')}
828
+ clefLineMap = {'B':'treble', 'G':'alto1', 'E':'alto2', 'C':'alto', 'A':'tenor', 'F':'bass3', 'D':'bass'}
829
+ alterTab = {'=':'0', '_':'-1', '__':'-2', '^':'1', '^^':'2'}
830
+ accTab = {'=':'natural', '_':'flat', '__':'flat-flat', '^':'sharp', '^^':'sharp-sharp'}
831
+ chordTab = compChordTab ()
832
+ uSyms = {'~':'roll', 'H':'fermata','L':'>','M':'lowermordent','O':'coda',
833
+ 'P':'uppermordent','S':'segno','T':'trill','u':'upbow','v':'downbow'}
834
+ pageFmtDef = [0.75,297,210,18,18,10,10] # the abcm2ps page formatting defaults for A4
835
+ metaTab = {'O':'origin', 'A':'area', 'Z':'transcription', 'N':'notes', 'G':'group', 'H':'history', 'R':'rhythm',
836
+ 'B':'book', 'D':'discography', 'F':'fileurl', 'S':'source', 'P':'partmap', 'W':'lyrics'}
837
+ metaMap = {'C':'composer'} # mapping of composer is fixed
838
+ metaTypes = {'composer':1,'lyricist':1,'poet':1,'arranger':1,'translator':1, 'rights':1} # valid MusicXML meta data types
839
+ tuningDef = 'E2,A2,D3,G3,B3,E4'.split (',') # default string tuning (guitar)
840
+
841
+ def __init__ (s):
842
+ s.pageFmtCmd = [] # set by command line option -p
843
+ s.reset ()
844
+ def reset (s, fOpt=False):
845
+ s.divisions = 2520 # xml duration of 1/4 note, 2^3 * 3^2 * 5 * 7 => 5,7,9 tuplets
846
+ s.ties = {} # {abc pitch tuple -> alteration} for all open ties
847
+ s.slurstack = {} # stack of open slur numbers per (overlay) voice
848
+ s.slurbeg = [] # type of slurs to start (when slurs are detected at element-level)
849
+ s.tmnum = 0 # time modification, numerator
850
+ s.tmden = 0 # time modification, denominator
851
+ s.ntup = 0 # number of tuplet notes remaining
852
+ s.trem = 0 # number of bars for tremolo
853
+ s.intrem = 0 # mark tremolo sequence (for duration doubling)
854
+ s.tupnts = [] # all tuplet modifiers with corresp. durations: [(duration, modifier), ...]
855
+ s.irrtup = 0 # 1 if an irregular tuplet
856
+ s.ntype = '' # the normal-type of a tuplet (== duration type of a normal tuplet note)
857
+ s.unitL = (1, 8) # default unit length
858
+ s.unitLcur = (1, 8) # unit length of current voice
859
+ s.keyAlts = {} # alterations implied by key
860
+ s.msreAlts = {} # temporarily alterations
861
+ s.curVolta = '' # open volta bracket
862
+ s.title = '' # title of music
863
+ s.creator = {} # {creator-type -> creator string}
864
+ s.metadata = {} # {metadata-type -> string}
865
+ s.lyrdash = {} # {lyric number -> 1 if dash between syllables}
866
+ s.usrSyms = s.uSyms # user defined symbols
867
+ s.prevNote = None # xml element of previous beamed note to correct beams (start, continue)
868
+ s.prevLyric = {} # xml element of previous lyric to add/correct extend type (start, continue)
869
+ s.grcbbrk = False # remember any bbrk in a grace sequence
870
+ s.linebrk = 0 # 1 if next measure should start with a line break
871
+ s.nextdecos = [] # decorations for the next note
872
+ s.prevmsre = None # the previous measure
873
+ s.supports_tag = 0 # issue supports-tag in xml file when abc uses explicit linebreaks
874
+ s.staveDefs = [] # collected %%staves or %%score instructions from score
875
+ s.staves = [] # staves = [[voice names to be merged into one stave]]
876
+ s.groups = [] # list of merged part names with interspersed {[ and }]
877
+ s.grands = [] # [[vid1, vid2, ..], ...] voiceIds to be merged in a grand staff
878
+ s.gStaffNums = {} # map each voice id in a grand staff to a staff number
879
+ s.gNstaves = {} # map each voice id in a grand staff to total number of staves
880
+ s.pageFmtAbc = [] # formatting from abc directives
881
+ s.mdur = (4,4) # duration of one measure
882
+ s.gtrans = 0 # octave transposition (by clef)
883
+ s.midprg = ['', '', '', ''] # MIDI channel nr, program nr, volume, panning for the current part
884
+ s.vid = '' # abc voice id for the current voice
885
+ s.pid = '' # xml part id for the current voice
886
+ s.gcue_on = 0 # insert <cue/> tag in each note
887
+ s.percVoice = 0 # 1 if percussion enabled
888
+ s.percMap = {} # (part-id, abc_pitch, xml-octave) -> (abc staff step, midi note number, xml notehead)
889
+ s.pMapFound = 0 # at least one I:percmap has been found
890
+ s.vcepid = {} # voice_id -> part_id
891
+ s.midiInst = {} # inst_id -> (part_id, voice_id, channel, midi_number), remember instruments used
892
+ s.capo = 0 # fret position of the capodastro
893
+ s.tunmid = [] # midi numbers of strings
894
+ s.tunTup = [] # ordered midi numbers of strings [(midi_num, string_num), ...] (midi_num from high to low)
895
+ s.fOpt = fOpt # force string/fret allocations for tab staves
896
+ s.orderChords = 0 # order notes in a chord
897
+ s.chordDecos = {} # decos that should be distributed to all chord notes for xml
898
+ ch10 = 'acoustic-bass-drum,35;bass-drum-1,36;side-stick,37;acoustic-snare,38;hand-clap,39;electric-snare,40;low-floor-tom,41;closed-hi-hat,42;high-floor-tom,43;pedal-hi-hat,44;low-tom,45;open-hi-hat,46;low-mid-tom,47;hi-mid-tom,48;crash-cymbal-1,49;high-tom,50;ride-cymbal-1,51;chinese-cymbal,52;ride-bell,53;tambourine,54;splash-cymbal,55;cowbell,56;crash-cymbal-2,57;vibraslap,58;ride-cymbal-2,59;hi-bongo,60;low-bongo,61;mute-hi-conga,62;open-hi-conga,63;low-conga,64;high-timbale,65;low-timbale,66;high-agogo,67;low-agogo,68;cabasa,69;maracas,70;short-whistle,71;long-whistle,72;short-guiro,73;long-guiro,74;claves,75;hi-wood-block,76;low-wood-block,77;mute-cuica,78;open-cuica,79;mute-triangle,80;open-triangle,81'
899
+ s.percsnd = [x.split (',') for x in ch10.split (';')] # {name -> midi number} of standard channel 10 sound names
900
+ s.gTime = (0,0) # (XML begin time, XML end time) in divisions
901
+ s.tabStaff = '' # == pid (part ID) for a tab staff
902
+
903
+ def mkPitch (s, acc, note, oct, lev):
904
+ if s.percVoice: # percussion map switched off by perc=off (see doClef)
905
+ octq = int (oct) + s.gtrans # honour the octave= transposition when querying percmap
906
+ tup = s.percMap.get ((s.pid, acc+note, octq), s.percMap.get (('', acc+note, octq), 0))
907
+ if tup: step, soct, midi, notehead = tup
908
+ else: step, soct = note, octq
909
+ octnum = (4 if step.upper() == step else 5) + int (soct)
910
+ if not tup: # add percussion map for unmapped notes in this part
911
+ midi = str (octnum * 12 + [0,2,4,5,7,9,11]['CDEFGAB'.index (step.upper())] + {'^':1,'_':-1}.get (acc, 0) + 12)
912
+ notehead = {'^':'x', '_':'circle-x'}.get (acc, 'normal')
913
+ if s.pMapFound: info ('no I:percmap for: %s%s in part %s, voice %s' % (acc+note, -oct*',' if oct<0 else oct*"'", s.pid, s.vid))
914
+ s.percMap [(s.pid, acc+note, octq)] = (note, octq, midi, notehead)
915
+ else: # correct step value for clef
916
+ step, octnum = stepTrans (step.upper (), octnum, s.curClef)
917
+ pitch = E.Element ('unpitched')
918
+ addElemT (pitch, 'display-step', step.upper (), lev + 1)
919
+ addElemT (pitch, 'display-octave', str (octnum), lev + 1)
920
+ return pitch, '', midi, notehead
921
+ nUp = note.upper ()
922
+ octnum = (4 if nUp == note else 5) + int (oct) + s.gtrans
923
+ pitch = E.Element ('pitch')
924
+ addElemT (pitch, 'step', nUp, lev + 1)
925
+ alter = ''
926
+ if (note, oct) in s.ties:
927
+ tied_alter, _, vnum, _ = s.ties [(note,oct)] # vnum = overlay voice number when tie started
928
+ if vnum == s.overlayVnum: alter = tied_alter # tied note in the same overlay -> same alteration
929
+ elif acc:
930
+ s.msreAlts [(nUp, octnum)] = s.alterTab [acc]
931
+ alter = s.alterTab [acc] # explicit notated alteration
932
+ elif (nUp, octnum) in s.msreAlts: alter = s.msreAlts [(nUp, octnum)] # temporary alteration
933
+ elif nUp in s.keyAlts: alter = s.keyAlts [nUp] # alteration implied by the key
934
+ if alter: addElemT (pitch, 'alter', alter, lev + 1)
935
+ addElemT (pitch, 'octave', str (octnum), lev + 1)
936
+ return pitch, alter, '', ''
937
+
938
+ def getNoteDecos (s, n):
939
+ decos = s.nextdecos # decorations encountered so far
940
+ ndeco = getattr (n, 'deco', 0) # possible decorations of notes of a chord
941
+ if ndeco: # add decorations, translate used defined symbols
942
+ decos += [s.usrSyms.get (d, d).strip ('!+') for d in ndeco.t]
943
+ s.nextdecos = []
944
+ if s.tabStaff == s.pid and s.fOpt and n.name != 'rest': # force fret/string allocation if explicit string decoration is missing
945
+ if [d for d in decos if d in '0123456789'] == []: decos.append ('0')
946
+ return decos
947
+
948
+ def mkNote (s, n, lev):
949
+ isgrace = getattr (n, 'grace', '')
950
+ ischord = getattr (n, 'chord', '')
951
+ if s.ntup >= 0 and not isgrace and not ischord:
952
+ s.ntup -= 1 # count tuplet notes only on non-chord, non grace notes
953
+ if s.ntup == -1 and s.trem <= 0:
954
+ s.intrem = 0 # tremolo pair ends at first note that is not a new tremolo pair (s.trem > 0)
955
+ nnum, nden = n.dur.t # abc dutation of note
956
+ if s.intrem: nnum += nnum # double duration of tremolo duplets
957
+ if nden == 0: nden = 1 # occurs with illegal ABC like: "A2 1". Now interpreted as A2/1
958
+ num, den = simplify (nnum * s.unitLcur[0], nden * s.unitLcur[1]) # normalised with unit length
959
+ if den > 64: # limit denominator to 64
960
+ num = int (round (64 * float (num) / den)) # scale note to num/64
961
+ num, den = simplify (max ([num, 1]), 64) # smallest num == 1
962
+ info ('duration too small: rounded to %d/%d' % (num, den))
963
+ if n.name == 'rest' and ('Z' in n.t or 'X' in n.t):
964
+ num, den = s.mdur # duration of one measure
965
+ noMsrRest = not (n.name == 'rest' and (num, den) == s.mdur) # not a measure rest
966
+ dvs = (4 * s.divisions * num) // den # divisions is xml-duration of 1/4
967
+ rdvs = dvs # real duration (will be 0 for chord/grace)
968
+ num, den = simplify (num, den * 4) # scale by 1/4 for s.typeMap
969
+ ndot = 0
970
+ if num == 3 and noMsrRest: ndot = 1; den = den // 2 # look for dotted notes
971
+ if num == 7 and noMsrRest: ndot = 2; den = den // 4
972
+ nt = E.Element ('note')
973
+ if isgrace: # a grace note (and possibly a chord note)
974
+ grace = E.Element ('grace')
975
+ if s.acciatura: grace.set ('slash', 'yes'); s.acciatura = 0
976
+ addElem (nt, grace, lev + 1)
977
+ dvs = rdvs = 0 # no (real) duration for a grace note
978
+ if den <= 16: den = 32 # not longer than 1/8 for a grace note
979
+ if s.gcue_on: # insert cue tag
980
+ cue = E.Element ('cue')
981
+ addElem (nt, cue, lev + 1)
982
+ if ischord: # a chord note
983
+ chord = E.Element ('chord')
984
+ addElem (nt, chord, lev + 1)
985
+ rdvs = 0 # chord notes no real duration
986
+ if den not in s.typeMap: # take the nearest smaller legal duration
987
+ info ('illegal duration %d/%d' % (nnum, nden))
988
+ den = min (x for x in s.typeMap.keys () if x > den)
989
+ xmltype = str (s.typeMap [den]) # xml needs the note type in addition to duration
990
+ acc, step, oct = '', 'C', '0' # abc-notated pitch elements (accidental, pitch step, octave)
991
+ alter, midi, notehead = '', '', '' # xml alteration
992
+ if n.name == 'rest':
993
+ if 'x' in n.t or 'X' in n.t: nt.set ('print-object', 'no')
994
+ rest = E.Element ('rest')
995
+ if not noMsrRest: rest.set ('measure', 'yes')
996
+ addElem (nt, rest, lev + 1)
997
+ else:
998
+ p = n.pitch.t # get pitch elements from parsed tokens
999
+ if len (p) == 3: acc, step, oct = p
1000
+ else: step, oct = p
1001
+ pitch, alter, midi, notehead = s.mkPitch (acc, step, oct, lev + 1)
1002
+ if midi: acc = '' # erase accidental for percussion notes
1003
+ addElem (nt, pitch, lev + 1)
1004
+ if s.ntup >= 0: # modify duration for tuplet notes
1005
+ dvs = dvs * s.tmden // s.tmnum
1006
+ if dvs:
1007
+ addElemT (nt, 'duration', str (dvs), lev + 1) # skip when dvs == 0, requirement of musicXML
1008
+ if not ischord: s.gTime = s.gTime [1], s.gTime [1] + dvs
1009
+ ptup = (step, oct) # pitch tuple without alteration to check for ties
1010
+ tstop = ptup in s.ties and s.ties[ptup][2] == s.overlayVnum # open tie on this pitch tuple in this overlay
1011
+ if tstop:
1012
+ tie = E.Element ('tie', type='stop')
1013
+ addElem (nt, tie, lev + 1)
1014
+ if getattr (n, 'tie', 0):
1015
+ tie = E.Element ('tie', type='start')
1016
+ addElem (nt, tie, lev + 1)
1017
+ if (s.midprg != ['', '', '', ''] or midi) and n.name != 'rest': # only add when %%midi was present or percussion
1018
+ instId = 'I%s-%s' % (s.pid, 'X' + midi if midi else s.vid)
1019
+ chan, midi = ('10', midi) if midi else s.midprg [:2]
1020
+ inst = E.Element ('instrument', id=instId) # instrument id for midi
1021
+ addElem (nt, inst, lev + 1)
1022
+ if instId not in s.midiInst: s.midiInst [instId] = (s.pid, s.vid, chan, midi, s.midprg [2], s.midprg [3]) # for instrument list in mkScorePart
1023
+ addElemT (nt, 'voice', '1', lev + 1) # default voice, for merging later
1024
+ if noMsrRest: addElemT (nt, 'type', xmltype, lev + 1) # add note type if not a measure rest
1025
+ for i in range (ndot): # add dots
1026
+ dot = E.Element ('dot')
1027
+ addElem (nt, dot, lev + 1)
1028
+ decos = s.getNoteDecos (n) # get decorations for this note
1029
+ if acc and not tstop: # only add accidental if note not tied
1030
+ e = E.Element ('accidental')
1031
+ if 'courtesy' in decos:
1032
+ e.set ('parentheses', 'yes')
1033
+ decos.remove ('courtesy')
1034
+ e.text = s.accTab [acc]
1035
+ addElem (nt, e, lev + 1)
1036
+ tupnotation = '' # start/stop notation element for tuplets
1037
+ if s.ntup >= 0: # add time modification element for tuplet notes
1038
+ tmod = mkTmod (s.tmnum, s.tmden, lev + 1)
1039
+ addElem (nt, tmod, lev + 1)
1040
+ if s.ntup > 0 and not s.tupnts: tupnotation = 'start'
1041
+ s.tupnts.append ((rdvs, tmod)) # remember all tuplet modifiers with corresp. durations
1042
+ if s.ntup == 0: # last tuplet note (and possible chord notes there after)
1043
+ if rdvs: tupnotation = 'stop' # only insert notation in the real note (rdvs > 0)
1044
+ s.cmpNormType (rdvs, lev + 1) # compute and/or add normal-type elements (-> s.ntype)
1045
+ hasStem = 1
1046
+ if not ischord: s.chordDecos = {} # clear on non chord note
1047
+ if 'stemless' in decos or (s.nostems and n.name != 'rest') or 'stemless' in s.chordDecos:
1048
+ hasStem = 0
1049
+ addElemT (nt, 'stem', 'none', lev + 1)
1050
+ if 'stemless' in decos: decos.remove ('stemless') # do not handle in doNotations
1051
+ if hasattr (n, 'pitches'): s.chordDecos ['stemless'] = 1 # set on first chord note
1052
+ if notehead:
1053
+ nh = addElemT (nt, 'notehead', re.sub (r'[+-]$', '', notehead), lev + 1)
1054
+ if notehead[-1] in '+-': nh.set ('filled', 'yes' if notehead[-1] == '+' else 'no')
1055
+ gstaff = s.gStaffNums.get (s.vid, 0) # staff number of the current voice
1056
+ if gstaff: addElemT (nt, 'staff', str (gstaff), lev + 1)
1057
+ if hasStem: s.doBeams (n, nt, den, lev + 1) # no stems -> no beams in a tab staff
1058
+ s.doNotations (n, decos, ptup, alter, tupnotation, tstop, nt, lev + 1)
1059
+ if n.objs: s.doLyr (n, nt, lev + 1)
1060
+ else: s.prevLyric = {} # clear on note without lyrics
1061
+ return nt
1062
+
1063
+ def cmpNormType (s, rdvs, lev): # compute the normal-type of a tuplet (only needed for Finale)
1064
+ if rdvs: # the last real tuplet note (chord notes can still follow afterwards with rdvs == 0)
1065
+ durs = [dur for dur, tmod in s.tupnts if dur > 0]
1066
+ ndur = sum (durs) // s.tmnum # duration of the normal type
1067
+ s.irrtup = any ((dur != ndur) for dur in durs) # irregular tuplet
1068
+ tix = 16 * s.divisions // ndur # index in typeMap of normal-type duration
1069
+ if tix in s.typeMap:
1070
+ s.ntype = str (s.typeMap [tix]) # the normal-type
1071
+ else: s.irrtup = 0 # give up, no normal type possible
1072
+ if s.irrtup: # only add normal-type for irregular tuplets
1073
+ for dur, tmod in s.tupnts: # add normal-type to all modifiers
1074
+ addElemT (tmod, 'normal-type', s.ntype, lev + 1)
1075
+ s.tupnts = [] # reset the tuplet buffer
1076
+
1077
+ def doNotations (s, n, decos, ptup, alter, tupnotation, tstop, nt, lev):
1078
+ slurs = getattr (n, 'slurs', 0) # slur ends
1079
+ pts = getattr (n, 'pitches', []) # all chord notes available in the first note
1080
+ ov = s.overlayVnum # current overlay voice number (0 for the main voice)
1081
+ if pts: # make list of pitches in chord: [(pitch, octave), ..]
1082
+ if type (pts.pitch) == pObj: pts = [pts.pitch] # chord with one note
1083
+ else: pts = [tuple (p.t[-2:]) for p in pts.pitch] # normal chord
1084
+ for pt, (tie_alter, nts, vnum, ntelm) in sorted (list (s.ties.items ())): # scan all open ties and delete illegal ones
1085
+ if vnum != s.overlayVnum: continue # tie belongs to different overlay
1086
+ if pts and pt in pts: continue # pitch tuple of tie exists in chord
1087
+ if getattr (n, 'chord', 0): continue # skip chord notes
1088
+ if pt == ptup: continue # skip correct single note tie
1089
+ if getattr (n, 'grace', 0): continue # skip grace notes
1090
+ info ('tie between different pitches: %s%s converted to slur' % pt)
1091
+ del s.ties [pt] # remove the note from pending ties
1092
+ e = [t for t in ntelm.findall ('tie') if t.get ('type') == 'start'][0] # get the tie start element
1093
+ ntelm.remove (e) # delete start tie element
1094
+ e = [t for t in nts.findall ('tied') if t.get ('type') == 'start'][0] # get the tied start element
1095
+ e.tag = 'slur' # convert tie into slur
1096
+ slurnum = pushSlur (s.slurstack, ov)
1097
+ e.set ('number', str (slurnum))
1098
+ if slurs: slurs.t.append (')') # close slur on this note
1099
+ else: slurs = pObj ('slurs', [')'])
1100
+ tstart = getattr (n, 'tie', 0) # start a new tie
1101
+ if not (tstop or tstart or decos or slurs or s.slurbeg or tupnotation or s.trem): return nt
1102
+ nots = E.Element ('notations') # notation element needed
1103
+ if s.trem: # +/- => tuple tremolo sequence / single note tremolo
1104
+ if s.trem < 0: tupnotation = 'single'; s.trem = -s.trem
1105
+ if not tupnotation: return # only add notation at first or last note of a tremolo sequence
1106
+ orn = E.Element ('ornaments')
1107
+ trm = E.Element ('tremolo', type=tupnotation) # type = start, stop or single
1108
+ trm.text = str (s.trem) # the number of bars in a tremolo note
1109
+ addElem (nots, orn, lev + 1)
1110
+ addElem (orn, trm, lev + 2)
1111
+ if tupnotation == 'stop' or tupnotation == 'single': s.trem = 0
1112
+ elif tupnotation: # add tuplet type
1113
+ tup = E.Element ('tuplet', type=tupnotation)
1114
+ if tupnotation == 'start': tup.set ('bracket', 'yes')
1115
+ addElem (nots, tup, lev + 1)
1116
+ if tstop: # stop tie
1117
+ del s.ties[ptup] # remove flag
1118
+ tie = E.Element ('tied', type='stop')
1119
+ addElem (nots, tie, lev + 1)
1120
+ if tstart: # start a tie
1121
+ s.ties[ptup] = (alter, nots, s.overlayVnum, nt) # remember pitch tuple to stop tie and apply same alteration
1122
+ tie = E.Element ('tied', type='start')
1123
+ if tstart.t[0] == '.-': tie.set ('line-type', 'dotted')
1124
+ addElem (nots, tie, lev + 1)
1125
+ if decos: # look for slurs and decorations
1126
+ slurMap = { '(':1, '.(':1, '(,':1, "('":1, '.(,':1, ".('":1 }
1127
+ arts = [] # collect articulations
1128
+ for d in decos: # do all slurs and decos
1129
+ if d in slurMap: s.slurbeg.append (d); continue # slurs made in while loop at the end
1130
+ elif d == 'fermata' or d == 'H':
1131
+ ntn = E.Element ('fermata', type='upright')
1132
+ elif d == 'arpeggio':
1133
+ ntn = E.Element ('arpeggiate', number='1')
1134
+ elif d in ['~(', '~)']:
1135
+ if d[1] == '(': tp = 'start'; s.glisnum += 1; gn = s.glisnum
1136
+ else: tp = 'stop'; gn = s.glisnum; s.glisnum -= 1
1137
+ if s.glisnum < 0: s.glisnum = 0; continue # stop without previous start
1138
+ ntn = E.Element ('glissando', {'line-type':'wavy', 'number':'%d' % gn, 'type':tp})
1139
+ elif d in ['-(', '-)']:
1140
+ if d[1] == '(': tp = 'start'; s.slidenum += 1; gn = s.slidenum
1141
+ else: tp = 'stop'; gn = s.slidenum; s.slidenum -= 1
1142
+ if s.slidenum < 0: s.slidenum = 0; continue # stop without previous start
1143
+ ntn = E.Element ('slide', {'line-type':'solid', 'number':'%d' % gn, 'type':tp})
1144
+ else: arts.append (d); continue
1145
+ addElem (nots, ntn, lev + 1)
1146
+ if arts: # do only note articulations and collect staff annotations in xmldecos
1147
+ rest = s.doArticulations (nt, nots, arts, lev + 1)
1148
+ if rest: info ('unhandled note decorations: %s' % rest)
1149
+ if slurs: # these are only slur endings
1150
+ for d in slurs.t: # slurs to be closed on this note
1151
+ if not s.slurstack.get (ov, 0): break # no more open old slurs for this (overlay) voice
1152
+ slurnum = s.slurstack [ov].pop ()
1153
+ slur = E.Element ('slur', number='%d' % slurnum, type='stop')
1154
+ addElem (nots, slur, lev + 1)
1155
+ while s.slurbeg: # create slurs beginning on this note
1156
+ stp = s.slurbeg.pop (0)
1157
+ slurnum = pushSlur (s.slurstack, ov)
1158
+ ntn = E.Element ('slur', number='%d' % slurnum, type='start')
1159
+ if '.' in stp: ntn.set ('line-type', 'dotted')
1160
+ if ',' in stp: ntn.set ('placement', 'below')
1161
+ if "'" in stp: ntn.set ('placement', 'above')
1162
+ addElem (nots, ntn, lev + 1)
1163
+ if list (nots) != []: # only add notations if not empty
1164
+ addElem (nt, nots, lev)
1165
+
1166
+ def doArticulations (s, nt, nots, arts, lev):
1167
+ decos = []
1168
+ for a in arts:
1169
+ if a in s.artMap:
1170
+ art = E.Element ('articulations')
1171
+ addElem (nots, art, lev)
1172
+ addElem (art, E.Element (s.artMap[a]), lev + 1)
1173
+ elif a in s.ornMap:
1174
+ orn = E.Element ('ornaments')
1175
+ addElem (nots, orn, lev)
1176
+ addElem (orn, E.Element (s.ornMap[a]), lev + 1)
1177
+ elif a in ['trill(','trill)']:
1178
+ orn = E.Element ('ornaments')
1179
+ addElem (nots, orn, lev)
1180
+ type = 'start' if a.endswith ('(') else 'stop'
1181
+ if type == 'start': addElem (orn, E.Element ('trill-mark'), lev + 1)
1182
+ addElem (orn, E.Element ('wavy-line', type=type), lev + 1)
1183
+ elif a in s.tecMap:
1184
+ tec = E.Element ('technical')
1185
+ addElem (nots, tec, lev)
1186
+ addElem (tec, E.Element (s.tecMap[a]), lev + 1)
1187
+ elif a in '0123456':
1188
+ tec = E.Element ('technical')
1189
+ addElem (nots, tec, lev)
1190
+ if s.tabStaff == s.pid: # current voice belongs to a tabStaff
1191
+ alt = int (nt.findtext ('pitch/alter') or 0) # find midi number of current note
1192
+ step = nt.findtext ('pitch/step')
1193
+ oct = int (nt.findtext ('pitch/octave'))
1194
+ midi = oct * 12 + [0,2,4,5,7,9,11]['CDEFGAB'.index (step)] + alt + 12
1195
+ if a == '0': # no string annotation: find one
1196
+ firstFit = ''
1197
+ for smid, istr in s.tunTup: # midi numbers of open strings from high to low
1198
+ if midi >= smid: # highest open string where this note can be played
1199
+ isvrij = s.strAlloc.isVrij (istr - 1, s.gTime [0], s.gTime [1])
1200
+ a = str (istr) # string number
1201
+ if not firstFit: firstFit = a
1202
+ if isvrij: break
1203
+ if not isvrij: # no free string, take the first fit (lowest fret)
1204
+ a = firstFit
1205
+ s.strAlloc.bezet (int (a) - 1, s.gTime [0], s.gTime [1])
1206
+ else: # force annotated string number
1207
+ s.strAlloc.bezet (int (a) - 1, s.gTime [0], s.gTime [1])
1208
+ bmidi = s.tunmid [int (a) - 1] # midi number of allocated string (with capodastro)
1209
+ fret = midi - bmidi # fret position (respecting capodastro)
1210
+ if fret < 25 and fret >= 0:
1211
+ addElemT (tec, 'fret', str (fret), lev + 1)
1212
+ else:
1213
+ altp = 'b' if alt == -1 else '#' if alt == 1 else ''
1214
+ info ('fret %d out of range, note %s%d on string %s' % (fret, step+altp, oct, a))
1215
+ addElemT (tec, 'string', a, lev + 1)
1216
+ else:
1217
+ addElemT (tec, 'fingering', a, lev + 1)
1218
+ else: decos.append (a) # return staff annotations
1219
+ return decos
1220
+
1221
+ def doLyr (s, n, nt, lev):
1222
+ for i, lyrobj in enumerate (n.objs):
1223
+ lyrel = E.Element ('lyric', number = str (i + 1))
1224
+ if lyrobj.name == 'syl':
1225
+ dash = len (lyrobj.t) == 2
1226
+ if dash:
1227
+ if i in s.lyrdash: type = 'middle'
1228
+ else: type = 'begin'; s.lyrdash [i] = 1
1229
+ else:
1230
+ if i in s.lyrdash: type = 'end'; del s.lyrdash [i]
1231
+ else: type = 'single'
1232
+ addElemT (lyrel, 'syllabic', type, lev + 1)
1233
+ txt = lyrobj.t[0] # the syllabe
1234
+ txt = re.sub (r'(?<!\\)~', ' ', txt) # replace ~ by space when not escaped (preceded by \)
1235
+ txt = re.sub (r'\\(.)', r'\1', txt) # replace all escaped characters by themselves (for the time being)
1236
+ addElemT (lyrel, 'text', txt, lev + 1)
1237
+ elif lyrobj.name == 'ext' and i in s.prevLyric:
1238
+ pext = s.prevLyric [i].find ('extend') # identify previous extend
1239
+ if pext == None:
1240
+ ext = E.Element ('extend', type = 'start')
1241
+ addElem (s.prevLyric [i], ext, lev + 1)
1242
+ elif pext.get('type') == 'stop': # subsequent extend: stop -> continue
1243
+ pext.set ('type', 'continue')
1244
+ ext = E.Element ('extend', type = 'stop') # always stop on current extend
1245
+ addElem (lyrel, ext, lev + 1)
1246
+ elif lyrobj.name == 'ext': info ('lyric extend error'); continue
1247
+ else: continue # skip other lyric elements or errors
1248
+ addElem (nt, lyrel, lev)
1249
+ s.prevLyric [i] = lyrel # for extension (melisma) on the next note
1250
+
1251
+ def doBeams (s, n, nt, den, lev):
1252
+ if hasattr (n, 'chord') or hasattr (n, 'grace'):
1253
+ s.grcbbrk = s.grcbbrk or n.bbrk.t[0] # remember if there was any bbrk in or before a grace sequence
1254
+ return
1255
+ bbrk = s.grcbbrk or n.bbrk.t[0] or den < 32
1256
+ s.grcbbrk = False
1257
+ if not s.prevNote: pbm = None
1258
+ else: pbm = s.prevNote.find ('beam')
1259
+ bm = E.Element ('beam', number='1')
1260
+ bm.text = 'begin'
1261
+ if pbm != None:
1262
+ if bbrk:
1263
+ if pbm.text == 'begin':
1264
+ s.prevNote.remove (pbm)
1265
+ elif pbm.text == 'continue':
1266
+ pbm.text = 'end'
1267
+ s.prevNote = None
1268
+ else: bm.text = 'continue'
1269
+ if den >= 32 and n.name != 'rest':
1270
+ addElem (nt, bm, lev)
1271
+ s.prevNote = nt
1272
+
1273
+ def stopBeams (s):
1274
+ if not s.prevNote: return
1275
+ pbm = s.prevNote.find ('beam')
1276
+ if pbm != None:
1277
+ if pbm.text == 'begin':
1278
+ s.prevNote.remove (pbm)
1279
+ elif pbm.text == 'continue':
1280
+ pbm.text = 'end'
1281
+ s.prevNote = None
1282
+
1283
+ def staffDecos (s, decos, maat, lev):
1284
+ gstaff = s.gStaffNums.get (s.vid, 0) # staff number of the current voice
1285
+ for d in decos:
1286
+ d = s.usrSyms.get (d, d).strip ('!+') # try to replace user defined symbol
1287
+ if d in s.dynaMap:
1288
+ dynel = E.Element ('dynamics')
1289
+ addDirection (maat, dynel, lev, gstaff, [E.Element (d)], 'below', s.gcue_on)
1290
+ elif d in s.wedgeMap: # wedge
1291
+ if ')' in d: type = 'stop'
1292
+ else: type = 'crescendo' if '<' in d or 'crescendo' in d else 'diminuendo'
1293
+ addDirection (maat, E.Element ('wedge', type=type), lev, gstaff)
1294
+ elif d.startswith ('8v'):
1295
+ if 'a' in d: type, plce = 'down', 'above'
1296
+ else: type, plce = 'up', 'below'
1297
+ if ')' in d: type = 'stop'
1298
+ addDirection (maat, E.Element ('octave-shift', type=type, size='8'), lev, gstaff, placement=plce)
1299
+ elif d in (['ped','ped-up']):
1300
+ type = 'stop' if d.endswith ('up') else 'start'
1301
+ addDirection (maat, E.Element ('pedal', type=type), lev, gstaff)
1302
+ elif d in ['coda', 'segno']:
1303
+ text, attr, val = s.capoMap [d]
1304
+ dir = addDirection (maat, E.Element (text), lev, gstaff, placement='above')
1305
+ sound = E.Element ('sound'); sound.set (attr, val)
1306
+ addElem (dir, sound, lev + 1)
1307
+ elif d in s.capoMap:
1308
+ text, attr, val = s.capoMap [d]
1309
+ words = E.Element ('words'); words.text = text
1310
+ dir = addDirection (maat, words, lev, gstaff, placement='above')
1311
+ sound = E.Element ('sound'); sound.set (attr, val)
1312
+ addElem (dir, sound, lev + 1)
1313
+ elif d == '(' or d == '.(': s.slurbeg.append (d) # start slur on next note
1314
+ elif d in ['/-','//-','///-','////-']: # duplet tremolo sequence
1315
+ s.tmnum, s.tmden, s.ntup, s.trem, s.intrem = 2, 1, 2, len (d) - 1, 1
1316
+ elif d in ['/','//','///']: s.trem = - len (d) # single note tremolo
1317
+ else: s.nextdecos.append (d) # keep annotation for the next note
1318
+
1319
+ def doFields (s, maat, fieldmap, lev):
1320
+ def instDir (midelm, midnum, dirtxt):
1321
+ instId = 'I%s-%s' % (s.pid, s.vid)
1322
+ words = E.Element ('words'); words.text = dirtxt % midnum
1323
+ snd = E.Element ('sound')
1324
+ mi = E.Element ('midi-instrument', id=instId)
1325
+ dir = addDirection (maat, words, lev, gstaff, placement='above')
1326
+ addElem (dir, snd, lev + 1)
1327
+ addElem (snd, mi, lev + 2)
1328
+ addElemT (mi, midelm, midnum, lev + 3)
1329
+ def addTrans (n):
1330
+ e = E.Element ('transpose')
1331
+ addElemT (e, 'chromatic', n, lev + 2) # n == signed number string given after transpose
1332
+ atts.append ((9, e))
1333
+ def doClef (field):
1334
+ if re.search (r'perc|map', field): # percussion clef or new style perc=on or map=perc
1335
+ r = re.search (r'(perc|map)\s*=\s*(\S*)', field)
1336
+ s.percVoice = 0 if r and r.group (2) not in ['on','true','perc'] else 1
1337
+ field = re.sub (r'(perc|map)\s*=\s*(\S*)', '', field) # erase the perc= for proper clef matching
1338
+ clef, gtrans = 0, 0
1339
+ clefn = re.search (r'alto1|alto2|alto4|alto|tenor|bass3|bass|treble|perc|none|tab', field)
1340
+ clefm = re.search (r"(?:^m=| m=|middle=)([A-Ga-g])([,']*)", field)
1341
+ trans_oct2 = re.search (r'octave=([-+]?\d)', field)
1342
+ trans = re.search (r'(?:^t=| t=|transpose=)(-?[\d]+)', field)
1343
+ trans_oct = re.search (r'([+-^_])(8|15)', field)
1344
+ cue_onoff = re.search (r'cue=(on|off)', field)
1345
+ strings = re.search (r"strings=(\S+)", field)
1346
+ stafflines = re.search (r'stafflines=\s*(\d)', field)
1347
+ capo = re.search (r'capo=(\d+)', field)
1348
+ if clefn:
1349
+ clef = clefn.group ()
1350
+ if clefm:
1351
+ note, octstr = clefm.groups ()
1352
+ nUp = note.upper ()
1353
+ octnum = (4 if nUp == note else 5) + (len (octstr) if "'" in octstr else -len (octstr))
1354
+ gtrans = (3 if nUp in 'AFD' else 4) - octnum
1355
+ if clef not in ['perc', 'none']: clef = s.clefLineMap [nUp]
1356
+ if clef:
1357
+ s.gtrans = gtrans # only change global tranposition when a clef is really defined
1358
+ if clef != 'none': s.curClef = clef # keep track of current abc clef (for percmap)
1359
+ sign, line = s.clefMap [clef]
1360
+ if not sign: return
1361
+ c = E.Element ('clef')
1362
+ if gstaff: c.set ('number', str (gstaff)) # only add staff number when defined
1363
+ addElemT (c, 'sign', sign, lev + 2)
1364
+ if line: addElemT (c, 'line', line, lev + 2)
1365
+ if trans_oct:
1366
+ n = trans_oct.group (1) in '-_' and -1 or 1
1367
+ if trans_oct.group (2) == '15': n *= 2 # 8 => 1 octave, 15 => 2 octaves
1368
+ addElemT (c, 'clef-octave-change', str (n), lev + 2) # transpose print out
1369
+ if trans_oct.group (1) in '+-': s.gtrans += n # also transpose all pitches with one octave
1370
+ atts.append ((7, c))
1371
+ if trans_oct2: # octave= can also be in a K: field
1372
+ n = int (trans_oct2.group (1))
1373
+ s.gtrans = gtrans + n
1374
+ if trans != None: # add transposition in semitones
1375
+ e = E.Element ('transpose')
1376
+ addElemT (e, 'chromatic', str (trans.group (1)), lev + 3)
1377
+ atts.append ((9, e))
1378
+ if cue_onoff: s.gcue_on = cue_onoff.group (1) == 'on'
1379
+ nlines = 0
1380
+ if clef == 'tab':
1381
+ s.tabStaff = s.pid
1382
+ if capo: s.capo = int (capo.group (1))
1383
+ if strings: s.tuning = strings.group (1).split (',')
1384
+ s.tunmid = [int (boct) * 12 + [0,2,4,5,7,9,11]['CDEFGAB'.index (bstep)] + 12 + s.capo for bstep, boct in s.tuning]
1385
+ s.tunTup = sorted (zip (s.tunmid, range (len (s.tunmid), 0, -1)), reverse=1)
1386
+ s.tunmid.reverse ()
1387
+ nlines = str (len (s.tuning))
1388
+ s.strAlloc.setlines (len (s.tuning), s.pid)
1389
+ s.nostems = 'nostems' in field # tab clef without stems
1390
+ s.diafret = 'diafret' in field # tab with diatonic fretting
1391
+ if stafflines or nlines:
1392
+ e = E.Element ('staff-details')
1393
+ if gstaff: e.set ('number', str (gstaff)) # only add staff number when defined
1394
+ if not nlines: nlines = stafflines.group (1)
1395
+ addElemT (e, 'staff-lines', nlines, lev + 2)
1396
+ if clef == 'tab':
1397
+ for line, t in enumerate (s.tuning):
1398
+ st = E.Element ('staff-tuning', line=str(line+1))
1399
+ addElemT (st, 'tuning-step', t[0], lev + 3)
1400
+ addElemT (st, 'tuning-octave', t[1], lev + 3)
1401
+ addElem (e, st, lev + 2)
1402
+ if s.capo: addElemT (e, 'capo', str (s.capo), lev + 2)
1403
+ atts.append ((8, e))
1404
+ s.diafret = 0 # chromatic fretting is default
1405
+ atts = [] # collect xml attribute elements [(order-number, xml-element), ..]
1406
+ gstaff = s.gStaffNums.get (s.vid, 0) # staff number of the current voice
1407
+ for ftype, field in fieldmap.items ():
1408
+ if not field: # skip empty fields
1409
+ continue
1410
+ if ftype == 'Div': # not an abc field, but handled as if
1411
+ d = E.Element ('divisions')
1412
+ d.text = field
1413
+ atts.append ((1, d))
1414
+ elif ftype == 'gstaff': # make grand staff
1415
+ e = E.Element ('staves')
1416
+ e.text = str (field)
1417
+ atts.append ((4, e))
1418
+ elif ftype == 'M':
1419
+ if field == 'none': continue
1420
+ if field == 'C': field = '4/4'
1421
+ elif field == 'C|': field = '2/2'
1422
+ t = E.Element ('time')
1423
+ if '/' not in field:
1424
+ info ('M:%s not recognized, 4/4 assumed' % field)
1425
+ field = '4/4'
1426
+ beats, btype = field.split ('/')[:2]
1427
+ try: s.mdur = simplify (eval (beats), int (btype)) # measure duration for Z and X rests (eval allows M:2+3/4)
1428
+ except:
1429
+ info ('error in M:%s, 4/4 assumed' % field)
1430
+ s.mdur = (4,4)
1431
+ beats, btype = '4','4'
1432
+ addElemT (t, 'beats', beats, lev + 2)
1433
+ addElemT (t, 'beat-type', btype, lev + 2)
1434
+ atts.append ((3, t))
1435
+ elif ftype == 'K':
1436
+ accs = ['F','C','G','D','A','E','B'] # == s.sharpness [7:14]
1437
+ mode = ''
1438
+ key = re.match (r'\s*([A-G][#b]?)\s*([a-zA-Z]*)', field)
1439
+ alts = re.search (r'\s((\s?[=^_][A-Ga-g])+)', ' ' + field) # avoid matching middle=G and m=G
1440
+ if key:
1441
+ key, mode = key.groups ()
1442
+ mode = mode.lower ()[:3] # only first three chars, no case
1443
+ if mode not in s.offTab: mode = 'maj'
1444
+ fifths = s.sharpness.index (key) - s.offTab [mode]
1445
+ if fifths >= 0: s.keyAlts = dict (zip (accs[:fifths], fifths * ['1']))
1446
+ else: s.keyAlts = dict (zip (accs[fifths:], -fifths * ['-1']))
1447
+ elif field.startswith ('none') or field == '': # the default key
1448
+ fifths = 0
1449
+ mode = 'maj'
1450
+ if alts:
1451
+ alts = re.findall (r'[=^_][A-Ga-g]', alts.group(1)) # list of explicit alterations
1452
+ alts = [(x[1], s.alterTab [x[0]]) for x in alts] # [step, alter]
1453
+ for step, alter in alts: # correct permanent alterations for this key
1454
+ s.keyAlts [step.upper ()] = alter
1455
+ k = E.Element ('key')
1456
+ koctave = []
1457
+ lowerCaseSteps = [step.upper () for step, alter in alts if step.islower ()]
1458
+ for step, alter in sorted (list (s.keyAlts.items ())):
1459
+ if alter == '0': # skip neutrals
1460
+ del s.keyAlts [step.upper ()] # otherwise you get neutral signs on normal notes
1461
+ continue
1462
+ addElemT (k, 'key-step', step.upper (), lev + 2)
1463
+ addElemT (k, 'key-alter', alter, lev + 2)
1464
+ koctave.append ('5' if step in lowerCaseSteps else '4')
1465
+ if koctave: # only key signature if not empty
1466
+ for oct in koctave:
1467
+ e = E.Element ('key-octave', number=oct)
1468
+ addElem (k, e, lev + 2)
1469
+ atts.append ((2, k))
1470
+ elif mode:
1471
+ k = E.Element ('key')
1472
+ addElemT (k, 'fifths', str (fifths), lev + 2)
1473
+ addElemT (k, 'mode', s.modTab [mode], lev + 2)
1474
+ atts.append ((2, k))
1475
+ doClef (field)
1476
+ elif ftype == 'L':
1477
+ try: s.unitLcur = lmap (int, field.split ('/'))
1478
+ except: s.unitLcur = (1,8)
1479
+ if len (s.unitLcur) == 1 or s.unitLcur[1] not in s.typeMap:
1480
+ info ('L:%s is not allowed, 1/8 assumed' % field)
1481
+ s.unitLcur = 1,8
1482
+ elif ftype == 'V':
1483
+ doClef (field)
1484
+ elif ftype == 'I':
1485
+ s.doField_I (ftype, field, instDir, addTrans)
1486
+ elif ftype == 'Q':
1487
+ s.doTempo (maat, field, lev)
1488
+ elif ftype == 'P': # ad hoc translation of P: into a staff text direction
1489
+ words = E.Element ('rehearsal')
1490
+ words.set ('font-weight', 'bold')
1491
+ words.text = field
1492
+ addDirection (maat, words, lev, gstaff, placement='above')
1493
+ elif ftype in 'TCOAZNGHRBDFSU':
1494
+ info ('**illegal header field in body: %s, content: %s' % (ftype, field))
1495
+ else:
1496
+ info ('unhandled field: %s, content: %s' % (ftype, field))
1497
+
1498
+ if atts:
1499
+ att = E.Element ('attributes') # insert sub elements in the order required by musicXML
1500
+ addElem (maat, att, lev)
1501
+ for _, att_elem in sorted (atts, key=lambda x: x[0]): # ordering !
1502
+ addElem (att, att_elem, lev + 1)
1503
+ if s.diafret:
1504
+ other = E.Element ('other-direction'); other.text = 'diatonic fretting'
1505
+ addDirection (maat, other, lev, 0)
1506
+
1507
+ def doTempo (s, maat, field, lev):
1508
+ gstaff = s.gStaffNums.get (s.vid, 0) # staff number of the current voice
1509
+ t = re.search (r'(\d)/(\d\d?)\s*=\s*(\d[.\d]*)|(\d[.\d]*)', field)
1510
+ rtxt = re.search (r'"([^"]*)"', field) # look for text in Q: field
1511
+ if not t and not rtxt: return
1512
+ elems = [] # [(element, sub-elements)] will be added as direction-types
1513
+ if rtxt:
1514
+ num, den, upm = 1, 4, s.tempoMap.get (rtxt.group (1).lower ().strip (), 120)
1515
+ words = E.Element ('words'); words.text = rtxt.group (1)
1516
+ elems.append ((words, []))
1517
+ if t:
1518
+ try:
1519
+ if t.group (4): num, den, upm = 1, s.unitLcur[1] , float (t.group (4)) # old syntax Q:120
1520
+ else: num, den, upm = int (t.group (1)), int (t.group (2)), float (t.group (3))
1521
+ except: info ('conversion error: %s' % field); return
1522
+ num, den = simplify (num, den);
1523
+ dotted, den_not = (1, den // 2) if num == 3 else (0, den)
1524
+ metro = E.Element ('metronome')
1525
+ u = E.Element ('beat-unit'); u.text = s.typeMap.get (4 * den_not, 'quarter')
1526
+ pm = E.Element ('per-minute'); pm.text = ('%.2f' % upm).rstrip ('0').rstrip ('.')
1527
+ subelms = [u, E.Element ('beat-unit-dot'), pm] if dotted else [u, pm]
1528
+ elems.append ((metro, subelms))
1529
+ dir = addDirection (maat, elems, lev, gstaff, [], placement='above')
1530
+ if num != 1 and num != 3: info ('in Q: numerator in %d/%d not supported' % (num, den))
1531
+ qpm = 4. * num * upm / den
1532
+ sound = E.Element ('sound'); sound.set ('tempo', '%.2f' % qpm)
1533
+ addElem (dir, sound, lev + 1)
1534
+
1535
+ def mkBarline (s, maat, loc, lev, style='', dir='', ending=''):
1536
+ b = E.Element ('barline', location=loc)
1537
+ if style:
1538
+ addElemT (b, 'bar-style', style, lev + 1)
1539
+ if s.curVolta: # first stop a current volta
1540
+ end = E.Element ('ending', number=s.curVolta, type='stop')
1541
+ s.curVolta = ''
1542
+ if loc == 'left': # stop should always go to a right barline
1543
+ bp = E.Element ('barline', location='right')
1544
+ addElem (bp, end, lev + 1)
1545
+ addElem (s.prevmsre, bp, lev) # prevmsre has no right barline! (ending would have stopped there)
1546
+ else:
1547
+ addElem (b, end, lev + 1)
1548
+ if ending:
1549
+ ending = ending.replace ('-',',') # MusicXML only accepts comma's
1550
+ endtxt = ''
1551
+ if ending.startswith ('"'): # ending is a quoted string
1552
+ endtxt = ending.strip ('"')
1553
+ ending = '33' # any number that is not likely to occur elsewhere
1554
+ end = E.Element ('ending', number=ending, type='start')
1555
+ if endtxt: end.text = endtxt # text appears in score in stead of number attribute
1556
+ addElem (b, end, lev + 1)
1557
+ s.curVolta = ending
1558
+ if dir:
1559
+ r = E.Element ('repeat', direction=dir)
1560
+ addElem (b, r, lev + 1)
1561
+ addElem (maat, b, lev)
1562
+
1563
+ def doChordSym (s, maat, sym, lev):
1564
+ alterMap = {'#':'1','=':'0','b':'-1'}
1565
+ rnt = sym.root.t
1566
+ chord = E.Element ('harmony')
1567
+ addElem (maat, chord, lev)
1568
+ root = E.Element ('root')
1569
+ addElem (chord, root, lev + 1)
1570
+ addElemT (root, 'root-step', rnt[0], lev + 2)
1571
+ if len (rnt) == 2: addElemT (root, 'root-alter', alterMap [rnt[1]], lev + 2)
1572
+ kind = s.chordTab.get (sym.kind.t[0], 'major') if sym.kind.t else 'major'
1573
+ addElemT (chord, 'kind', kind, lev + 1)
1574
+ if hasattr (sym, 'bass'):
1575
+ bnt = sym.bass.t
1576
+ bass = E.Element ('bass')
1577
+ addElem (chord, bass, lev + 1)
1578
+ addElemT (bass, 'bass-step', bnt[0], lev + 2)
1579
+ if len (bnt) == 2: addElemT (bass, 'bass-alter', alterMap [bnt[1]], lev + 2)
1580
+ degs = getattr (sym, 'degree', '')
1581
+ if degs:
1582
+ if type (degs) != list_type: degs = [degs]
1583
+ for deg in degs:
1584
+ deg = deg.t[0]
1585
+ if deg[0] == '#': alter = '1'; deg = deg[1:]
1586
+ elif deg[0] == 'b': alter = '-1'; deg = deg[1:]
1587
+ else: alter = '0'; deg = deg
1588
+ degree = E.Element ('degree')
1589
+ addElem (chord, degree, lev + 1)
1590
+ addElemT (degree, 'degree-value', deg, lev + 2)
1591
+ addElemT (degree, 'degree-alter', alter, lev + 2)
1592
+ addElemT (degree, 'degree-type', 'add', lev + 2)
1593
+
1594
+ def mkMeasure (s, i, t, lev, fieldmap={}):
1595
+ s.msreAlts = {}
1596
+ s.ntup, s.trem, s.intrem = -1, 0, 0
1597
+ s.acciatura = 0 # next grace element gets acciatura attribute
1598
+ overlay = 0
1599
+ maat = E.Element ('measure', number = str(i))
1600
+ if fieldmap: s.doFields (maat, fieldmap, lev + 1)
1601
+ if s.linebrk: # there was a line break in the previous measure
1602
+ e = E.Element ('print')
1603
+ e.set ('new-system', 'yes')
1604
+ addElem (maat, e, lev + 1)
1605
+ s.linebrk = 0
1606
+ for it, x in enumerate (t):
1607
+ if x.name == 'note' or x.name == 'rest':
1608
+ if x.dur.t[0] == 0: # a leading zero was used for stemmless in abcm2ps, we only support !stemless!
1609
+ x.dur.t = tuple ([1, x.dur.t[1]])
1610
+ note = s.mkNote (x, lev + 1)
1611
+ addElem (maat, note, lev + 1)
1612
+ elif x.name == 'lbar':
1613
+ bar = x.t[0]
1614
+ if bar == '|' or bar == '[|': pass # skip redundant bar
1615
+ elif ':' in bar: # forward repeat
1616
+ volta = x.t[1] if len (x.t) == 2 else ''
1617
+ s.mkBarline (maat, 'left', lev + 1, style='heavy-light', dir='forward', ending=volta)
1618
+ else: # bar must be a volta number
1619
+ s.mkBarline (maat, 'left', lev + 1, ending=bar)
1620
+ elif x.name == 'rbar':
1621
+ bar = x.t[0]
1622
+ if bar == '.|':
1623
+ s.mkBarline (maat, 'right', lev + 1, style='dotted')
1624
+ elif ':' in bar: # backward repeat
1625
+ s.mkBarline (maat, 'right', lev + 1, style='light-heavy', dir='backward')
1626
+ elif bar == '||':
1627
+ s.mkBarline (maat, 'right', lev + 1, style='light-light')
1628
+ elif bar == '[|]' or bar == '[]':
1629
+ s.mkBarline (maat, 'right', lev + 1, style='none')
1630
+ elif '[' in bar or ']' in bar:
1631
+ s.mkBarline (maat, 'right', lev + 1, style='light-heavy')
1632
+ elif bar[0] == '&': overlay = 1
1633
+ elif x.name == 'tup':
1634
+ if len (x.t) == 3: n, into, nts = x.t
1635
+ elif len (x.t) == 2: n, into, nts = x.t + [0]
1636
+ else: n, into, nts = x.t[0], 0, 0
1637
+ if into == 0: into = 3 if n in [2,4,8] else 2
1638
+ if nts == 0: nts = n
1639
+ s.tmnum, s.tmden, s.ntup = n, into, nts
1640
+ elif x.name == 'deco':
1641
+ s.staffDecos (x.t, maat, lev + 1) # output staff decos, postpone note decos to next note
1642
+ elif x.name == 'text':
1643
+ pos, text = x.t[:2]
1644
+ place = 'above' if pos == '^' else 'below'
1645
+ words = E.Element ('words')
1646
+ words.text = text
1647
+ gstaff = s.gStaffNums.get (s.vid, 0) # staff number of the current voice
1648
+ addDirection (maat, words, lev + 1, gstaff, placement=place)
1649
+ elif x.name == 'inline':
1650
+ fieldtype, fieldval = x.t[0], ' '.join (x.t[1:])
1651
+ s.doFields (maat, {fieldtype:fieldval}, lev + 1)
1652
+ elif x.name == 'accia': s.acciatura = 1
1653
+ elif x.name == 'linebrk':
1654
+ s.supports_tag = 1
1655
+ if it > 0 and t[it -1].name == 'lbar': # we are at start of measure
1656
+ e = E.Element ('print') # output linebreak now
1657
+ e.set ('new-system', 'yes')
1658
+ addElem (maat, e, lev + 1)
1659
+ else:
1660
+ s.linebrk = 1 # output linebreak at start of next measure
1661
+ elif x.name == 'chordsym':
1662
+ s.doChordSym (maat, x, lev + 1)
1663
+ s.stopBeams ()
1664
+ s.prevmsre = maat
1665
+ return maat, overlay
1666
+
1667
+ def mkPart (s, maten, id, lev, attrs, nstaves, rOpt):
1668
+ s.slurstack = {}
1669
+ s.glisnum = 0; # xml number attribute for glissandos
1670
+ s.slidenum = 0; # xml number attribute for slides
1671
+ s.unitLcur = s.unitL # set the default unit length at begin of each voice
1672
+ s.curVolta = ''
1673
+ s.lyrdash = {}
1674
+ s.linebrk = 0
1675
+ s.midprg = ['', '', '', ''] # MIDI channel nr, program nr, volume, panning for the current part
1676
+ s.gcue_on = 0 # reset cue note marker for each new voice
1677
+ s.gtrans = 0 # reset octave transposition (by clef)
1678
+ s.percVoice = 0 # 1 if percussion clef encountered
1679
+ s.curClef = '' # current abc clef (for percmap)
1680
+ s.nostems = 0 # for the tab clef
1681
+ s.tuning = s.tuningDef # reset string tuning to default
1682
+ part = E.Element ('part', id=id)
1683
+ s.overlayVnum = 0 # overlay voice number to relate ties that extend from one overlayed measure to the next
1684
+ gstaff = s.gStaffNums.get (s.vid, 0) # staff number of the current voice
1685
+ attrs_cpy = attrs.copy () # don't change attrs itself in next line
1686
+ if gstaff == 1: attrs_cpy ['gstaff'] = nstaves # make a grand staff
1687
+ if 'perc' in attrs_cpy.get ('V', ''): del attrs_cpy ['K'] # remove key from percussion voice
1688
+ msre, overlay = s.mkMeasure (1, maten[0], lev + 1, attrs_cpy)
1689
+ addElem (part, msre, lev + 1)
1690
+ for i, maat in enumerate (maten[1:]):
1691
+ s.overlayVnum = s.overlayVnum + 1 if overlay else 0
1692
+ msre, next_overlay = s.mkMeasure (i+2, maat, lev + 1)
1693
+ if overlay: mergePartMeasure (part, msre, s.overlayVnum, rOpt)
1694
+ else: addElem (part, msre, lev + 1)
1695
+ overlay = next_overlay
1696
+ return part
1697
+
1698
+ def mkScorePart (s, id, vids_p, partAttr, lev):
1699
+ def mkInst (instId, vid, midchan, midprog, midnot, vol, pan, lev):
1700
+ si = E.Element ('score-instrument', id=instId)
1701
+ pnm = partAttr.get (vid, [''])[0] # part name if present
1702
+ addElemT (si, 'instrument-name', pnm or 'dummy', lev + 2) # MuseScore needs a name
1703
+ mi = E.Element ('midi-instrument', id=instId)
1704
+ if midchan: addElemT (mi, 'midi-channel', midchan, lev + 2)
1705
+ if midprog: addElemT (mi, 'midi-program', str (int (midprog) + 1), lev + 2) # compatible with abc2midi
1706
+ if midnot: addElemT (mi, 'midi-unpitched', str (int (midnot) + 1), lev + 2)
1707
+ if vol: addElemT (mi, 'volume', '%.2f' % (int (vol) / 1.27), lev + 2)
1708
+ if pan: addElemT (mi, 'pan', '%.2f' % (int (pan) / 127. * 180 - 90), lev + 2)
1709
+ return (si, mi)
1710
+ naam, subnm, midprg = partAttr [id]
1711
+ sp = E.Element ('score-part', id='P'+id)
1712
+ nm = E.Element ('part-name')
1713
+ nm.text = naam
1714
+ addElem (sp, nm, lev + 1)
1715
+ snm = E.Element ('part-abbreviation')
1716
+ snm.text = subnm
1717
+ if subnm: addElem (sp, snm, lev + 1) # only add if subname was given
1718
+ inst = []
1719
+ for instId, (pid, vid, chan, midprg, vol, pan) in sorted (s.midiInst.items ()):
1720
+ midprg, midnot = ('0', midprg) if chan == '10' else (midprg, '')
1721
+ if pid == id: inst.append (mkInst (instId, vid, chan, midprg, midnot, vol, pan, lev))
1722
+ for si, mi in inst: addElem (sp, si, lev + 1)
1723
+ for si, mi in inst: addElem (sp, mi, lev + 1)
1724
+ return sp
1725
+
1726
+ def mkPartlist (s, vids, partAttr, lev):
1727
+ def addPartGroup (sym, num):
1728
+ pg = E.Element ('part-group', number=str (num), type='start')
1729
+ addElem (partlist, pg, lev + 1)
1730
+ addElemT (pg, 'group-symbol', sym, lev + 2)
1731
+ addElemT (pg, 'group-barline', 'yes', lev + 2)
1732
+ partlist = E.Element ('part-list')
1733
+ g_num = 0 # xml group number
1734
+ for g in (s.groups or vids): # brace/bracket or abc_voice_id
1735
+ if g == '[': g_num += 1; addPartGroup ('bracket', g_num)
1736
+ elif g == '{': g_num += 1; addPartGroup ('brace', g_num)
1737
+ elif g in '}]':
1738
+ pg = E.Element ('part-group', number=str (g_num), type='stop')
1739
+ addElem (partlist, pg, lev + 1)
1740
+ g_num -= 1
1741
+ else: # g = abc_voice_id
1742
+ if g not in vids: continue # error in %%score
1743
+ sp = s.mkScorePart (g, vids, partAttr, lev + 1)
1744
+ addElem (partlist, sp, lev + 1)
1745
+ return partlist
1746
+
1747
+ def doField_I (s, type, x, instDir, addTrans):
1748
+ def instChange (midchan, midprog): # instDir -> doFields
1749
+ if midchan and midchan != s.midprg [0]: instDir ('midi-channel', midchan, 'chan: %s')
1750
+ if midprog and midprog != s.midprg [1]: instDir ('midi-program', str (int (midprog) + 1), 'prog: %s')
1751
+ def readPfmt (x, n): # read ABC page formatting constant
1752
+ if not s.pageFmtAbc: s.pageFmtAbc = s.pageFmtDef # set the default values on first change
1753
+ ro = re.search (r'[^.\d]*([\d.]+)\s*(cm|in|pt)?', x) # float followed by unit
1754
+ if ro:
1755
+ x, unit = ro.groups () # unit == None when not present
1756
+ u = {'cm':10., 'in':25.4, 'pt':25.4/72} [unit] if unit else 1.
1757
+ s.pageFmtAbc [n] = float (x) * u # convert ABC values to millimeters
1758
+ else: info ('error in page format: %s' % x)
1759
+ def readPercMap (x): # parse I:percmap <abc_note> <step> <MIDI> <notehead>
1760
+ def getMidNum (sndnm): # find midi number of GM drum sound name
1761
+ pnms = sndnm.split ('-') # sound name parts (from I:percmap)
1762
+ ps = s.percsnd [:] # copy of the instruments
1763
+ _f = lambda ip, xs, pnm: ip < len (xs) and xs[ip].find (pnm) > -1 # part xs[ip] and pnm match
1764
+ for ip, pnm in enumerate (pnms): # match all percmap sound name parts
1765
+ ps = [(nm, mnum) for nm, mnum in ps if _f (ip, nm.split ('-'), pnm) ] # filter instruments
1766
+ if len (ps) <= 1: break # no match or one instrument left
1767
+ if len (ps) == 0: info ('drum sound: %s not found' % sndnm); return '38'
1768
+ return ps [0][1] # midi number of (first) instrument found
1769
+ def midiVal (acc, step, oct): # abc note -> midi note number
1770
+ oct = (4 if step.upper() == step else 5) + int (oct)
1771
+ return oct * 12 + [0,2,4,5,7,9,11]['CDEFGAB'.index (step.upper())] + {'^':1,'_':-1,'=':0}.get (acc, 0) + 12
1772
+ p0, p1, p2, p3, p4 = abc_percmap.parseString (x).asList () # percmap, abc-note, display-step, midi, note-head
1773
+ acc, astep, aoct = p1
1774
+ nstep, noct = (astep, aoct) if p2 == '*' else p2
1775
+ if p3 == '*': midi = str (midiVal (acc, astep, aoct))
1776
+ elif isinstance (p3, list_type): midi = str (midiVal (p3[0], p3[1], p3[2]))
1777
+ elif isinstance (p3, int_type): midi = str (p3)
1778
+ else: midi = getMidNum (p3.lower ())
1779
+ head = re.sub (r'(.)-([^x])', r'\1 \2', p4) # convert abc note head names to xml
1780
+ s.percMap [(s.pid, acc + astep, aoct)] = (nstep, noct, midi, head)
1781
+ if x.startswith ('score') or x.startswith ('staves'):
1782
+ s.staveDefs += [x] # collect all voice mappings
1783
+ elif x.startswith ('staffwidth'): info ('skipped I-field: %s' % x)
1784
+ elif x.startswith ('staff'): # set new staff number of the current voice
1785
+ r1 = re.search (r'staff *([+-]?)(\d)', x)
1786
+ if r1:
1787
+ sign = r1.group (1)
1788
+ num = int (r1.group (2))
1789
+ gstaff = s.gStaffNums.get (s.vid, 0) # staff number of the current voice
1790
+ if sign: # relative staff number
1791
+ num = (sign == '-') and gstaff - num or gstaff + num
1792
+ else: # absolute abc staff number
1793
+ try: vabc = s.staves [num - 1][0] # vid of (first voice of) abc-staff num
1794
+ except: vabc = 0; info ('abc staff %s does not exist' % num)
1795
+ num = s.gStaffNumsOrg.get (vabc, 0) # xml staff number of abc-staff num
1796
+ if gstaff and num > 0 and num <= s.gNstaves [s.vid]:
1797
+ s.gStaffNums [s.vid] = num
1798
+ else: info ('could not relocate to staff: %s' % r1.group ())
1799
+ else: info ('not a valid staff redirection: %s' % x)
1800
+ elif x.startswith ('scale'): readPfmt (x, 0)
1801
+ elif x.startswith ('pageheight'): readPfmt (x, 1)
1802
+ elif x.startswith ('pagewidth'): readPfmt (x, 2)
1803
+ elif x.startswith ('leftmargin'): readPfmt (x, 3)
1804
+ elif x.startswith ('rightmargin'): readPfmt (x, 4)
1805
+ elif x.startswith ('topmargin'): readPfmt (x, 5)
1806
+ elif x.startswith ('botmargin'): readPfmt (x, 6)
1807
+ elif x.startswith ('MIDI') or x.startswith ('midi'):
1808
+ r1 = re.search (r'program *(\d*) +(\d+)', x)
1809
+ r2 = re.search (r'channel *(\d+)', x)
1810
+ r3 = re.search (r"drummap\s+([_=^]*)([A-Ga-g])([,']*)\s+(\d+)", x)
1811
+ r4 = re.search (r'control *(\d+) +(\d+)', x)
1812
+ ch_nw, prg_nw, vol_nw, pan_nw = '', '', '', ''
1813
+ if r1: ch_nw, prg_nw = r1.groups () # channel nr or '', program nr
1814
+ if r2: ch_nw = r2.group (1) # channel nr only
1815
+ if r4:
1816
+ cnum, cval = r4.groups () # controller number, controller value
1817
+ if cnum == '7': vol_nw = cval
1818
+ if cnum == '10': pan_nw = cval
1819
+ if r1 or r2 or r4:
1820
+ ch = ch_nw or s.midprg [0]
1821
+ prg = prg_nw or s.midprg [1]
1822
+ vol = vol_nw or s.midprg [2]
1823
+ pan = pan_nw or s.midprg [3]
1824
+ instId = 'I%s-%s' % (s.pid, s.vid) # only look for real instruments, no percussion
1825
+ if instId in s.midiInst: instChange (ch, prg) # instChance -> doFields
1826
+ s.midprg = [ch, prg, vol, pan] # mknote: new instrument -> s.midiInst
1827
+ if r3: # translate drummap to percmap
1828
+ acc, step, oct, midi = r3.groups ()
1829
+ oct = -len (oct) if ',' in x else len (oct)
1830
+ notehead = 'x' if acc == '^' else 'circle-x' if acc == '_' else 'normal'
1831
+ s.percMap [(s.pid, acc + step, oct)] = (step, oct, midi, notehead)
1832
+ r = re.search (r'transpose[^-\d]*(-?\d+)', x)
1833
+ if r: addTrans (r.group (1)) # addTrans -> doFields
1834
+ elif x.startswith ('percmap'): readPercMap (x); s.pMapFound = 1
1835
+ else: info ('skipped I-field: %s' % x)
1836
+
1837
+ def parseStaveDef (s, vdefs):
1838
+ for vid in vdefs: s.vcepid [vid] = vid # default: each voice becomes an xml part
1839
+ if not s.staveDefs: return vdefs
1840
+ for x in s.staveDefs [1:]: info ('%%%%%s dropped, multiple stave mappings not supported' % x)
1841
+ x = s.staveDefs [0] # only the first %%score is honoured
1842
+ score = abc_scoredef.parseString (x) [0]
1843
+ f = lambda x: type (x) == uni_type and [x] or x
1844
+ s.staves = lmap (f, mkStaves (score, vdefs)) # [[vid] for each staff]
1845
+ s.grands = lmap (f, mkGrand (score, vdefs)) # [staff-id], staff-id == [vid][0]
1846
+ s.groups = mkGroups (score)
1847
+ vce_groups = [vids for vids in s.staves if len (vids) > 1] # all voice groups
1848
+ d = {} # for each voice group: map first voice id -> all merged voice ids
1849
+ for vgr in vce_groups: d [vgr[0]] = vgr
1850
+ for gstaff in s.grands: # for all grand staves
1851
+ if len (gstaff) == 1: continue # skip single parts
1852
+ for v, stf_num in zip (gstaff, range (1, len (gstaff) + 1)):
1853
+ for vx in d.get (v, [v]): # allocate staff numbers
1854
+ s.gStaffNums [vx] = stf_num # to all constituant voices
1855
+ s.gNstaves [vx] = len (gstaff) # also remember total number of staves
1856
+ s.gStaffNumsOrg = s.gStaffNums.copy () # keep original allocation for abc -> xml staff map
1857
+ for xmlpart in s.grands:
1858
+ pid = xmlpart [0] # part id == first staff id == first voice id
1859
+ vces = [v for stf in xmlpart for v in d.get (stf, [stf])]
1860
+ for v in vces: s.vcepid [v] = pid
1861
+ return vdefs
1862
+
1863
+ def voiceNamesAndMaps (s, ps): # get voice names and mappings
1864
+ vdefs = {}
1865
+ for vid, vcedef, vce in ps: # vcedef == emtpy or first pObj == voice definition
1866
+ pname, psubnm = '', '' # part name and abbreviation
1867
+ if not vcedef: # simple abc without voice definitions
1868
+ vdefs [vid] = pname, psubnm, ''
1869
+ else: # abc with voice definitions
1870
+ if vid != vcedef.t[1]: info ('voice ids unequal: %s (reg-ex) != %s (grammar)' % (vid, vcedef.t[1]))
1871
+ rn = re.search (r'(?:name|nm)="([^"]*)"', vcedef.t[2])
1872
+ if rn: pname = rn.group (1)
1873
+ rn = re.search (r'(?:subname|snm|sname)="([^"]*)"', vcedef.t[2])
1874
+ if rn: psubnm = rn.group (1)
1875
+ vcedef.t[2] = vcedef.t[2].replace ('"%s"' % pname, '""').replace ('"%s"' % psubnm, '""') # clear voice name to avoid false clef matches later on
1876
+ vdefs [vid] = pname, psubnm, vcedef.t[2]
1877
+ xs = [pObj.t[1] for maat in vce for pObj in maat if pObj.name == 'inline'] # all inline statements in vce
1878
+ s.staveDefs += [x.replace ('%5d',']') for x in xs if x.startswith ('score') or x.startswith ('staves')] # filter %%score and %%staves
1879
+ return vdefs
1880
+
1881
+ def doHeaderField (s, fld, attrmap):
1882
+ type, value = fld.t[0], fld.t[1].replace ('%5d',']') # restore closing brackets (see splitHeaderVoices)
1883
+ if not value: # skip empty field
1884
+ return
1885
+ if type == 'M':
1886
+ attrmap [type] = value
1887
+ elif type == 'L':
1888
+ try: s.unitL = lmap (int, fld.t[1].split ('/'))
1889
+ except:
1890
+ info ('illegal unit length:%s, 1/8 assumed' % fld.t[1])
1891
+ s.unitL = 1,8
1892
+ if len (s.unitL) == 1 or s.unitL[1] not in s.typeMap:
1893
+ info ('L:%s is not allowed, 1/8 assumed' % fld.t[1])
1894
+ s.unitL = 1,8
1895
+ elif type == 'K':
1896
+ attrmap[type] = value
1897
+ elif type == 'T':
1898
+ s.title = s.title + '\n' + value if s.title else value
1899
+ elif type == 'U':
1900
+ sym = fld.t[2].strip ('!+')
1901
+ s.usrSyms [value] = sym
1902
+ elif type == 'I':
1903
+ s.doField_I (type, value, lambda x,y,z:0, lambda x:0)
1904
+ elif type == 'Q':
1905
+ attrmap[type] = value
1906
+ elif type in 'CRZNOAGHBDFSP': # part maps are treated as meta data
1907
+ type = s.metaMap.get (type, type) # respect the (user defined --meta) mapping of various ABC fields to XML meta data types
1908
+ c = s.metadata.get (type, '')
1909
+ s.metadata [type] = c + '\n' + value if c else value # concatenate multiple info fields with new line as separator
1910
+ else:
1911
+ info ('skipped header: %s' % fld)
1912
+
1913
+ def mkIdentification (s, score, lev):
1914
+ if s.title:
1915
+ xs = s.title.split ('\n') # the first T: line goes to work-title
1916
+ ys = '\n'.join (xs [1:]) # place subsequent T: lines into work-number
1917
+ w = E.Element ('work')
1918
+ addElem (score, w, lev + 1)
1919
+ if ys: addElemT (w, 'work-number', ys, lev + 2)
1920
+ addElemT (w, 'work-title', xs[0], lev + 2)
1921
+ ident = E.Element ('identification')
1922
+ addElem (score, ident, lev + 1)
1923
+ for mtype, mval in s.metadata.items ():
1924
+ if mtype in s.metaTypes and mtype != 'rights': # all metaTypes are MusicXML creator types
1925
+ c = E.Element ('creator', type=mtype)
1926
+ c.text = mval
1927
+ addElem (ident, c, lev + 2)
1928
+ if 'rights' in s.metadata:
1929
+ c = addElemT (ident, 'rights', s.metadata ['rights'], lev + 2)
1930
+ encoding = E.Element ('encoding')
1931
+ addElem (ident, encoding, lev + 2)
1932
+ encoder = E.Element ('encoder')
1933
+ encoder.text = 'abc2xml version %d' % VERSION
1934
+ addElem (encoding, encoder, lev + 3)
1935
+ if s.supports_tag: # avoids interference of auto-flowing and explicit linebreaks
1936
+ suports = E.Element ('supports', attribute="new-system", element="print", type="yes", value="yes")
1937
+ addElem (encoding, suports, lev + 3)
1938
+ encodingDate = E.Element ('encoding-date')
1939
+ encodingDate.text = str (datetime.date.today ())
1940
+ addElem (encoding, encodingDate, lev + 3)
1941
+ s.addMeta (ident, lev + 2)
1942
+
1943
+ def mkDefaults (s, score, lev):
1944
+ if s.pageFmtCmd: s.pageFmtAbc = s.pageFmtCmd
1945
+ if not s.pageFmtAbc: return # do not output the defaults if none is desired
1946
+ abcScale, h, w, l, r, t, b = s.pageFmtAbc
1947
+ space = abcScale * 2.117 # 2.117 = 6pt = space between staff lines for scale = 1.0 in abcm2ps
1948
+ mils = 4 * space # staff height in millimeters
1949
+ scale = 40. / mils # tenth's per millimeter
1950
+ dflts = E.Element ('defaults')
1951
+ addElem (score, dflts, lev)
1952
+ scaling = E.Element ('scaling')
1953
+ addElem (dflts, scaling, lev + 1)
1954
+ addElemT (scaling, 'millimeters', '%g' % mils, lev + 2)
1955
+ addElemT (scaling, 'tenths', '40', lev + 2)
1956
+ layout = E.Element ('page-layout')
1957
+ addElem (dflts, layout, lev + 1)
1958
+ addElemT (layout, 'page-height', '%g' % (h * scale), lev + 2)
1959
+ addElemT (layout, 'page-width', '%g' % (w * scale), lev + 2)
1960
+ margins = E.Element ('page-margins', type='both')
1961
+ addElem (layout, margins, lev + 2)
1962
+ addElemT (margins, 'left-margin', '%g' % (l * scale), lev + 3)
1963
+ addElemT (margins, 'right-margin', '%g' % (r * scale), lev + 3)
1964
+ addElemT (margins, 'top-margin', '%g' % (t * scale), lev + 3)
1965
+ addElemT (margins, 'bottom-margin', '%g' % (b * scale), lev + 3)
1966
+
1967
+ def addMeta (s, parent, lev):
1968
+ misc = E.Element ('miscellaneous')
1969
+ mf = 0
1970
+ for mtype, mval in sorted (s.metadata.items ()):
1971
+ if mtype == 'S':
1972
+ addElemT (parent, 'source', mval, lev)
1973
+ elif mtype in s.metaTypes: continue # mapped meta data has already been output (in creator elements)
1974
+ else:
1975
+ mf = E.Element ('miscellaneous-field', name=s.metaTab [mtype])
1976
+ mf.text = mval
1977
+ addElem (misc, mf, lev + 1)
1978
+ if mf != 0: addElem (parent, misc, lev)
1979
+
1980
+ def parse (s, abc_string, rOpt=False, bOpt=False, fOpt=False):
1981
+ abctext = abc_string.replace ('[I:staff ','[I:staff') # avoid false beam breaks
1982
+ s.reset (fOpt)
1983
+ header, voices = splitHeaderVoices (abctext)
1984
+ ps = []
1985
+ try:
1986
+ lbrk_insert = 0 if re.search (r'I:linebreak\s*([!$]|none)|I:continueall\s*(1|true)', header) else bOpt
1987
+ hs = abc_header.parseString (header) if header else ''
1988
+ for id, voice in voices:
1989
+ if lbrk_insert: # insert linebreak at EOL
1990
+ r1 = re.compile (r'\[[wA-Z]:[^]]*\]') # inline field
1991
+ has_abc = lambda x: r1.sub ('', x).strip () # empty if line only contains inline fields
1992
+ voice = '\n'.join ([balk.rstrip ('$!') + '$' if has_abc (balk) else balk for balk in voice.splitlines ()])
1993
+ prevLeftBar = None # previous voice ended with a left-bar symbol (double repeat)
1994
+ s.orderChords = s.fOpt and ('tab' in voice [:200] or [x for x in hs if x.t[0] == 'K' and 'tab' in x.t[1]])
1995
+ vce = abc_voice.parseString (voice).asList ()
1996
+ lyr_notes = [] # remember notes between lyric blocks
1997
+ for m in vce: # all measures
1998
+ for e in m: # all abc-elements
1999
+ if e.name == 'lyr_blk': # -> e.objs is list of lyric lines
2000
+ lyr = [line.objs for line in e.objs] # line.objs is listof syllables
2001
+ alignLyr (lyr_notes, lyr) # put all syllables into corresponding notes
2002
+ lyr_notes = []
2003
+ else:
2004
+ lyr_notes.append (e)
2005
+ if not vce: # empty voice, insert an inline field that will be rejected
2006
+ vce = [[pObj ('inline', ['I', 'empty voice'])]]
2007
+ if prevLeftBar:
2008
+ vce[0].insert (0, prevLeftBar) # insert at begin of first measure
2009
+ prevLeftBar = None
2010
+ if vce[-1] and vce[-1][-1].name == 'lbar': # last measure ends with an lbar
2011
+ prevLeftBar = vce[-1][-1]
2012
+ if len (vce) > 1: # vce should not become empty (-> exception when taking vcelyr [0][0])
2013
+ del vce[-1] # lbar was the only element in measure vce[-1]
2014
+ vcelyr = vce
2015
+ elem1 = vcelyr [0][0] # the first element of the first measure
2016
+ if elem1.name == 'inline'and elem1.t[0] == 'V': # is a voice definition
2017
+ voicedef = elem1
2018
+ del vcelyr [0][0] # do not read voicedef twice
2019
+ else:
2020
+ voicedef = ''
2021
+ ps.append ((id, voicedef, vcelyr))
2022
+ except ParseException as err:
2023
+ if err.loc > 40: # limit length of error message, compatible with markInputline
2024
+ err.pstr = err.pstr [err.loc - 40: err.loc + 40]
2025
+ err.loc = 40
2026
+ xs = err.line[err.col-1:]
2027
+ info (err.line, warn=0)
2028
+ info ((err.col-1) * '-' + '^', warn=0)
2029
+ if re.search (r'\[U:', xs):
2030
+ info ('Error: illegal user defined symbol: %s' % xs[1:], warn=0)
2031
+ elif re.search (r'\[[OAPZNGHRBDFSXTCIU]:', xs):
2032
+ info ('Error: header-only field %s appears after K:' % xs[1:], warn=0)
2033
+ else:
2034
+ info ('Syntax error at column %d' % err.col, warn=0)
2035
+ raise
2036
+
2037
+ score = E.Element ('score-partwise')
2038
+ attrmap = {'Div': str (s.divisions), 'K':'C treble', 'M':'4/4'}
2039
+ for res in hs:
2040
+ if res.name == 'field':
2041
+ s.doHeaderField (res, attrmap)
2042
+ else:
2043
+ info ('unexpected header item: %s' % res)
2044
+
2045
+ vdefs = s.voiceNamesAndMaps (ps)
2046
+ vdefs = s.parseStaveDef (vdefs)
2047
+
2048
+ lev = 0
2049
+ vids, parts, partAttr = [], [], {}
2050
+ s.strAlloc = stringAlloc ()
2051
+ for vid, _, vce in ps: # voice id, voice parse tree
2052
+ pname, psubnm, voicedef = vdefs [vid] # part name
2053
+ attrmap ['V'] = voicedef # abc text of first voice definition (after V:vid) or empty
2054
+ pid = 'P%s' % vid # let part id start with an alpha
2055
+ s.vid = vid # avoid parameter passing, needed in mkNote for instrument id
2056
+ s.pid = s.vcepid [s.vid] # xml part-id for the current voice
2057
+ s.gTime = (0, 0) # reset time
2058
+ s.strAlloc.beginZoek () # reset search index
2059
+ part = s.mkPart (vce, pid, lev + 1, attrmap, s.gNstaves.get (vid, 0), rOpt)
2060
+ if 'Q' in attrmap: del attrmap ['Q'] # header tempo only in first part
2061
+ parts.append (part)
2062
+ vids.append (vid)
2063
+ partAttr [vid] = (pname, psubnm, s.midprg)
2064
+ if s.midprg != ['', '', '', ''] and not s.percVoice: # when a part has only rests
2065
+ instId = 'I%s-%s' % (s.pid, s.vid)
2066
+ if instId not in s.midiInst: s.midiInst [instId] = (s.pid, s.vid, s.midprg [0], s.midprg [1], s.midprg [2], s.midprg [3])
2067
+ parts, vidsnew = mergeParts (parts, vids, s.staves, rOpt) # merge parts into staves as indicated by %%score
2068
+ parts, vidsnew = mergeParts (parts, vidsnew, s.grands, rOpt, 1) # merge grand staves
2069
+ reduceMids (parts, vidsnew, s.midiInst)
2070
+
2071
+ s.mkIdentification (score, lev)
2072
+ s.mkDefaults (score, lev + 1)
2073
+
2074
+ partlist = s.mkPartlist (vids, partAttr, lev + 1)
2075
+ addElem (score, partlist, lev + 1)
2076
+ for ip, part in enumerate (parts): addElem (score, part, lev + 1)
2077
+
2078
+ return score
2079
+
2080
+
2081
+ def decodeInput (data_string):
2082
+ try: enc = 'utf-8'; unicode_string = data_string.decode (enc)
2083
+ except:
2084
+ try: enc = 'latin-1'; unicode_string = data_string.decode (enc)
2085
+ except: raise ValueError ('data not encoded in utf-8 nor in latin-1')
2086
+ info ('decoded from %s' % enc)
2087
+ return unicode_string
2088
+
2089
+ def ggd (a, b): # greatest common divisor
2090
+ return a if b == 0 else ggd (b, a % b)
2091
+
2092
+ xmlVersion = "<?xml version='1.0' encoding='utf-8'?>"
2093
+ def fixDoctype (elem):
2094
+ if python3: xs = E.tostring (elem, encoding='unicode') # writing to file will auto-encode to utf-8
2095
+ else: xs = E.tostring (elem, encoding='utf-8') # keep the string utf-8 encoded for writing to file
2096
+ ys = xs.split ('\n')
2097
+ ys.insert (0, xmlVersion) # crooked logic of ElementTree lib
2098
+ ys.insert (1, '<!DOCTYPE score-partwise PUBLIC "-//Recordare//DTD MusicXML 3.0 Partwise//EN" "http://www.musicxml.org/dtds/partwise.dtd">')
2099
+ return '\n'.join (ys)
2100
+
2101
+ def xml2mxl (pad, fnm, data): # write xml data to compressed .mxl file
2102
+ from zipfile import ZipFile, ZIP_DEFLATED
2103
+ fnmext = fnm + '.xml' # file name with extension, relative to the root within the archive
2104
+ outfile = os.path.join (pad, fnm + '.mxl')
2105
+ meta = '%s\n<container><rootfiles>\n' % xmlVersion
2106
+ meta += '<rootfile full-path="%s" media-type="application/vnd.recordare.musicxml+xml"/>\n' % fnmext
2107
+ meta += '</rootfiles></container>'
2108
+ f = ZipFile (outfile, 'w', ZIP_DEFLATED)
2109
+ f.writestr ('META-INF/container.xml', meta)
2110
+ f.writestr (fnmext, data)
2111
+ f.close ()
2112
+ info ('%s written' % outfile, warn=0)
2113
+
2114
+ def convert (pad, fnm, abc_string, mxl, rOpt=False, tOpt=False, bOpt=False, fOpt=False): # not used, backwards compatibility
2115
+ score = mxm.parse (abc_string, rOpt, bOpt, fOpt)
2116
+ writefile (pad, fnm, '', score, mxl, tOpt)
2117
+
2118
+ def writefile (pad, fnm, fnmNum, xmldoc, mxlOpt, tOpt=False):
2119
+ ipad, ifnm = os.path.split (fnm) # base name of input path is
2120
+ if tOpt:
2121
+ x = xmldoc.findtext ('work/work-title', 'no_title')
2122
+ ifnm = x.replace (',','_').replace ("'",'_').replace ('?','_')
2123
+ else:
2124
+ ifnm += fnmNum
2125
+ xmlstr = fixDoctype (xmldoc)
2126
+ if pad:
2127
+ if not mxlOpt or mxlOpt in ['a', 'add']:
2128
+ outfnm = os.path.join (pad, ifnm + '.xml') # joined with path from -o option
2129
+ outfile = open (outfnm, 'w')
2130
+ outfile.write (xmlstr)
2131
+ outfile.close ()
2132
+ info ('%s written' % outfnm, warn=0)
2133
+ if mxlOpt: xml2mxl (pad, ifnm, xmlstr) # also write a compressed version
2134
+ else:
2135
+ outfile = sys.stdout
2136
+ outfile.write (xmlstr)
2137
+ outfile.write ('\n')
2138
+
2139
+ def readfile (fnmext, errmsg='read error: '):
2140
+ try:
2141
+ if fnmext == '-.abc': fobj = stdin # see python2/3 differences
2142
+ else: fobj = open (fnmext, 'rb')
2143
+ encoded_data = fobj.read ()
2144
+ fobj.close ()
2145
+ return encoded_data if type (encoded_data) == uni_type else decodeInput (encoded_data)
2146
+ except Exception as e:
2147
+ info (errmsg + repr (e) + ' ' + fnmext)
2148
+ return None
2149
+
2150
+ def expand_abc_include (abctxt):
2151
+ ys = []
2152
+ for x in abctxt.splitlines ():
2153
+ if x.startswith ('%%abc-include') or x.startswith ('I:abc-include'):
2154
+ x = readfile (x[13:].strip (), 'include error: ')
2155
+ if x != None: ys.append (x)
2156
+ return '\n'.join (ys)
2157
+
2158
+ abc_header, abc_voice, abc_scoredef, abc_percmap = abc_grammar () # compute grammars only once
2159
+ mxm = MusicXml () # same for instance of MusicXml
2160
+
2161
+ def getXmlScores (abc_string, skip=0, num=1, rOpt=False, bOpt=False, fOpt=False): # not used, backwards compatibility
2162
+ return [fixDoctype (xml_doc) for xml_doc in
2163
+ getXmlDocs (abc_string, skip=0, num=1, rOpt=False, bOpt=False, fOpt=False)]
2164
+
2165
+ def getXmlDocs (abc_string, skip=0, num=1, rOpt=False, bOpt=False, fOpt=False): # added by David Randolph
2166
+ xml_docs = []
2167
+ abctext = expand_abc_include (abc_string)
2168
+ fragments = re.split ('^\s*X:', abctext, flags=re.M)
2169
+ preamble = fragments [0] # tunes can be preceeded by formatting instructions
2170
+ tunes = fragments[1:]
2171
+ if not tunes and preamble: tunes, preamble = ['1\n' + preamble], '' # tune without X:
2172
+ for itune, tune in enumerate (tunes):
2173
+ if itune < skip: continue # skip tunes, then read at most num tunes
2174
+ if itune >= skip + num: break
2175
+ tune = preamble + 'X:' + tune # restore preamble before each tune
2176
+ try: # convert string abctext -> file pad/fnmNum.xml
2177
+ score = mxm.parse (tune, rOpt, bOpt, fOpt)
2178
+ ds = list (score.iter ('duration')) # need to iterate twice
2179
+ ss = [int (d.text) for d in ds]
2180
+ deler = reduce (ggd, ss + [21]) # greatest common divisor of all durations
2181
+ for i, d in enumerate (ds): d.text = str (ss [i] // deler)
2182
+ for d in score.iter ('divisions'): d.text = str (int (d.text) // deler)
2183
+ xml_docs.append (score)
2184
+ except ParseException:
2185
+ pass # output already printed
2186
+ except Exception as err:
2187
+ info ('an exception occurred.\n%s' % err)
2188
+ return xml_docs
2189
+
2190
+ #----------------
2191
+ # Main Program
2192
+ #----------------
2193
+ if __name__ == '__main__':
2194
+ from optparse import OptionParser
2195
+ from glob import glob
2196
+ import time
2197
+
2198
+ parser = OptionParser (usage='%prog [-h] [-r] [-t] [-b] [-m SKIP NUM] [-o DIR] [-p PFMT] [-z MODE] [--meta MAP] <file1> [<file2> ...]', version='version %d' % VERSION)
2199
+ parser.add_option ("-o", action="store", help="store xml files in DIR", default='', metavar='DIR')
2200
+ parser.add_option ("-m", action="store", help="skip SKIP (0) tunes, then read at most NUM (1) tunes", nargs=2, type='int', default=(0,1), metavar='SKIP NUM')
2201
+ parser.add_option ("-p", action="store", help="pageformat PFMT (mm) = scale (0.75), pageheight (297), pagewidth (210), leftmargin (18), rightmargin (18), topmargin (10), botmargin (10)", default='', metavar='PFMT')
2202
+ parser.add_option ("-z", "--mxl", dest="mxl", help="store as compressed mxl, MODE = a(dd) or r(eplace)", default='', metavar='MODE')
2203
+ parser.add_option ("-r", action="store_true", help="show whole measure rests in merged staffs", default=False)
2204
+ parser.add_option ("-t", action="store_true", help="use tune title as file name", default=False)
2205
+ parser.add_option ("-b", action="store_true", help="line break at EOL", default=False)
2206
+ parser.add_option ("--meta", action="store", help="map infofields to XML metadata, MAP = R:poet,Z:lyricist,N:...", default='', metavar='MAP')
2207
+ parser.add_option ("-f", action="store_true", help="force string/fret allocations for tab staves", default=False)
2208
+ options, args = parser.parse_args ()
2209
+ if len (args) == 0: parser.error ('no input file given')
2210
+ pad = options.o
2211
+ if options.mxl and options.mxl not in ['a','add', 'r', 'replace']:
2212
+ parser.error ('MODE should be a(dd) or r(eplace), not: %s' % options.mxl)
2213
+ if pad:
2214
+ if not os.path.exists (pad): os.mkdir (pad)
2215
+ if not os.path.isdir (pad): parser.error ('%s is not a directory' % pad)
2216
+ if options.p: # set page formatting values
2217
+ try: # space, page-height, -width, margin-left, -right, -top, -bottom
2218
+ mxm.pageFmtCmd = lmap (float, options.p.split (','))
2219
+ if len (mxm.pageFmtCmd) != 7: raise ValueError ('-p needs 7 values')
2220
+ except Exception as err: parser.error (err)
2221
+ for x in options.meta.split (','):
2222
+ if not x: continue
2223
+ try: field, tag = x.split (':')
2224
+ except: parser.error ('--meta: %s cannot be split on colon' % x)
2225
+ if field not in 'OAZNGHRBDFSPW': parser.error ('--meta: field %s is no valid ABC field' % field)
2226
+ if tag not in mxm.metaTypes: parser.error ('--meta: tag %s is no valid XML creator type' % tag)
2227
+ mxm.metaMap [field] = tag
2228
+ fnmext_list = []
2229
+ for i in args:
2230
+ if i == '-': fnmext_list.append ('-.abc') # represents standard input
2231
+ else: fnmext_list += glob (i)
2232
+ if not fnmext_list: parser.error ('none of the input files exist')
2233
+ t_start = time.time ()
2234
+ for fnmext in fnmext_list:
2235
+ fnm, ext = os.path.splitext (fnmext)
2236
+ if ext.lower () not in ('.abc'):
2237
+ info ('skipped input file %s, it should have extension .abc' % fnmext)
2238
+ continue
2239
+ if os.path.isdir (fnmext):
2240
+ info ('skipped directory %s. Only files are accepted' % fnmext)
2241
+ continue
2242
+ abctext = readfile (fnmext)
2243
+ skip, num = options.m
2244
+ xml_docs = getXmlDocs (abctext, skip, num, options.r, options.b, options.f)
2245
+ for itune, xmldoc in enumerate (xml_docs):
2246
+ fnmNum = '%02d' % (itune + 1) if len (xml_docs) > 1 else ''
2247
+ writefile (pad, fnm, fnmNum, xmldoc, options.mxl, options.t)
2248
+ info ('done in %.2f secs' % (time.time () - t_start))