forked from jwdj/EasyABC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheasy_abc.py
8803 lines (7579 loc) · 392 KB
/
easy_abc.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
program_version = '1.3.8.7'
program_name = 'EasyABC ' + program_version
# Copyright (C) 2011-2014 Nils Liberg (mail: kotorinl at yahoo.co.uk)
# Copyright (C) 2015-2021 Seymour Shlien (mail: [email protected]), Jan Wybren de Jong (jw_de_jong at yahoo dot com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
# # for finding memory leaks uncomment following two lines
# import gc
# gc.set_debug(gc.DEBUG_LEAK)
#
# # for finding segmentation fault or bus error (pip install faulthandler)
# try:
# import faulthandler # pip install faulthandler
# faulthandler.enable()
# except ImportError:
# print('faulthandler not installed. Try: pip install faulthandler')
# pass
import sys
PY3 = sys.version_info >= (3,0,0)
if not PY3:
print("Python 2 is no longer supported. Please use:")
print(" python3 easy_abc.py")
exit()
abcm2ps_default_encoding = 'utf-8' ## 'latin-1'
import codecs
utf8_byte_order_mark = codecs.BOM_UTF8 # chr(0xef) + chr(0xbb) + chr(0xbf) #'\xef\xbb\xbf'
if PY3:
unichr = chr
xrange = range
def unicode(s):
return s
max_int = sys.maxsize
basestring = str
else:
max_int = sys.maxint
import os, os.path
import wx
WX4 = wx.version().startswith('4')
from utils import *
application_path = get_application_path()
cwd = os.getenv('EASYABCDIR')
if not cwd:
cwd = application_path
sys.path.append(cwd)
import re
import subprocess
import hashlib
if sys.version_info >= (3,0,0):
import pickle as pickle # py3
else:
import cPickle as pickle # py2
import threading
import shutil
import platform
import webbrowser
import time
import traceback
# import xml.etree.cElementTree as ET # 1.3.7.4 [JWdJ] 2016-06-30
import zipfile
from datetime import datetime
from collections import deque, namedtuple, defaultdict
from io import StringIO
from wx.lib.scrolledpanel import ScrolledPanel
import wx.html
import wx.stc as stc
import wx.lib.agw.aui as aui
import wx.lib.rcsizer as rcs
# import wx.lib.filebrowsebutton as filebrowse # 1.3.6.3 [JWdJ] 2015-04-22
import wx.lib.platebtn as platebtn
import wx.lib.mixins.listctrl as listmix
import wx.lib.agw.hypertreelist as htl
from wx.lib.embeddedimage import PyEmbeddedImage
# from wx.lib.expando import ExpandoTextCtrl, EVT_ETC_LAYOUT_NEEDED # 1.3.7.3 [JWdJ] 2016-04-09
from wx import GetTranslation as _
from wxhelper import *
# from midiplayer import *
try:
from fluidsynthplayer import *
fluidsynth_available = True
except ImportError:
sys.stderr.write('Warning: FluidSynth library not found. Playing using a SoundFont (.sf2) is disabled.')
# sys.stderr.write(traceback.format_exc())
fluidsynth_available = False
from xml2abc_interface import xml_to_abc, abc_to_xml
from midi2abc import midi_to_abc, Note, duration2abc
from generalmidi import general_midi_instruments
from abc_styler import ABCStyler
from abc_character_encoding import decode_abc, abc_text_to_unicode, get_encoding_abc
from abc_search import abc_matches_iter
from fractions import Fraction
from music_score_panel import MusicScorePanel
from svgrenderer import SvgRenderer
import itertools
from aligner import align_lines, extract_incipit, bar_sep, bar_sep_without_space, get_bar_length, bar_and_voice_overlay_sep
if sys.version_info >= (3,0,0):
from queue import Queue # 1.3.6.2 [JWdJ] 2015-02
else:
from Queue import Queue # 1.3.6.2 [JWdJ] 2015-02
application_running = True
if wx.Platform == "__WXMSW__":
if sys.stdout is None:
sys.stdout = open(os.devnull, 'w')
if sys.stderr is None:
sys.stderr = open(os.devnull, 'w')
import win32api
import win32process
try:
old_stdout = sys.stdout
sys.stdout = open(os.devnull, 'w')
if wx.Platform == "__WXMAC__":
import pygame.midi as pypm
pypm.init()
else:
import pygame
import pygame.pypm as pypm
pypm.Initialize()
except ImportError:
try:
import pypm
except ImportError:
sys.stderr.write('Warning: pygame/pypm module not found. Recording midi will not work')
finally:
sys.stdout = old_stdout
def str2fraction(s):
parts = [int(x.strip()) for x in s.split('/')]
return Fraction(parts[0], parts[1])
Tune = namedtuple('Tune', 'xnum title rythm offset_start offset_end abc header num_header_lines')
MidiNote = namedtuple('MidiNote', 'start stop indices page svg_row')
class AbortException(Exception): pass
class Abcm2psException(Exception): pass
class NWCConversionException(Exception): pass
from abc_tune import *
dialog_background_colour = wx.Colour(245, 244, 235)
default_note_highlight_color = '#FF7F3F'
control_margin = 6
default_midi_volume = 96
default_midi_pan = 64
default_midi_instrument = 0
# 1.3.6.3 [JWdJ] 2015-04-22
class MidiTune(object):
""" Container for abc2midi-generated .midi files """
def __init__(self, abc_tune, midi_file=None, error=None):
self.error = error
self.midi_file = midi_file
self.abc_tune = abc_tune
def cleanup(self):
if self.midi_file:
if os.path.isfile(self.midi_file):
os.remove(self.midi_file)
self.midi_file = None
# 1.3.6.2 [JWdJ]
class SvgTune(object):
""" Container for abcm2ps-generated .svg files """
def __init__(self, abc_tune, svg_files, error=None):
self.error = error
self.svg_files = svg_files
self.pages = {}
self.abc_tune = abc_tune
def render_page(self, page_index, renderer):
if 0 <= page_index < self.page_count:
page = self.pages.get(page_index, None)
if page is None:
page = renderer.svg_to_page(open(self.svg_files[page_index], 'rb').read())
page.index = page_index
self.pages[page_index] = page
else:
page = renderer.empty_page
return page
def cleanup(self):
for f in self.svg_files:
if os.path.isfile(f):
os.remove(f)
self.svg_files = ()
def is_equal(self, svg_tune):
if not isinstance(svg_tune, SvgTune):
return False
return self.abc_tune and self.abc_tune.is_equal(svg_tune.abc_tune)
@property
def page_count(self):
return len(self.svg_files)
@property
def first_note_line_index(self):
if self.abc_tune:
return self.abc_tune.first_note_line_index
return -1
@property
def tune_header_start_line_index(self):
if self.abc_tune:
return self.abc_tune.tune_header_start_line_index
return -1
@property
def x_number(self):
if self.abc_tune:
return self.abc_tune.x_number
return -1
# 1.3.6.3 [JWdJ] 2015-04-22
class AbcTunes(object):
""" A holder for created tunes. Takes care of proper cleanup. """
def __init__(self, cache_size=1):
self.__tunes = {}
self.cache_size = cache_size
self.cached_tune_ids = deque()
def get(self, tune_id):
tune = self.__tunes.get(tune_id, None)
return tune
def add(self, tune):
if tune.abc_tune and self.cache_size > 0:
tune_id = tune.abc_tune.tune_id
#if tune_id in self.__tunes:
# print 'tune already cached'
while len(self.cached_tune_ids) >= self.cache_size:
old_tune_id = self.cached_tune_ids.pop()
self.remove(old_tune_id)
self.__tunes[tune_id] = tune
self.cached_tune_ids.append(tune_id)
def cleanup(self):
for tune_id in list(self.__tunes):
self.remove(tune_id)
self.__tunes = {}
def remove(self, tune_id):
tune = self.__tunes[tune_id]
if tune is not None:
tune.cleanup()
del self.__tunes[tune_id]
#global variables
all_notes = "C,, D,, E,, F,, G,, A,, B,, C, D, E, F, G, A, B, C D E F G A B c d e f g a b c' d' e' f' g' a' b' c'' d'' e'' f'' g'' a'' b''".split()
doremi_prefixes = 'DRMFSLTdrmfslt' # 'd' corresponds to "do", 'r' to "re" and so on, DO vs. do is like C vs. c in ABC
doremi_suffixes = 'oeiaoaioOEIAOAIOlLhH'
execmessages = u''
visible_abc_code = u''
line_end_re = re.compile('\r\n|\r|\n')
tune_index_re = re.compile(r'^X:\s*(\d+)')
def note_to_index(abc_note):
try:
return all_notes.index(abc_note)
except ValueError:
return None
def text_to_lines(text):
return line_end_re.split(text)
def read_abc_file(path):
file_as_bytes = read_entire_file(path)
encoding = get_encoding_abc(file_as_bytes)
if encoding and encoding != 'utf-8':
try:
return file_as_bytes.decode(encoding)
except UnicodeError:
pass
try:
return file_as_bytes.decode('utf-8')
except UnicodeError:
return file_as_bytes.decode('latin-1')
# 1.3.6.3 [JWDJ] one function to determine font size
def get_normal_fontsize():
if wx.Platform == "__WXMSW__":
font_size = 10
else:
font_size = 14
return font_size
def frac_mod(fractional_number, modulo):
return fractional_number - modulo * int(fractional_number / modulo)
def start_process(cmd):
""" Starts a process
:param cmd: tuple containing executable and command line parameter
:return: nothing
"""
global execmessages # 1.3.6.4 [SS] 2015-05-27
# 1.3.6.4 [SS] 2015-05-01
if wx.Platform == "__WXMSW__":
creationflags = win32process.DETACHED_PROCESS
else:
creationflags = 0
# 1.3.6.4 [SS] 2015-05-27
#process = subprocess.Popen(cmd,shell=False,stdin=None,stdout=subprocess.PIPE,stderr=subprocess.PIPE,close_fds=True,creationflags=creationflags)
process = subprocess.Popen(cmd, shell=False, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags=creationflags)
stdout_value, stderr_value = process.communicate()
execmessages += '\n'+stderr_value + stdout_value
return
def get_output_from_process(cmd, input=None, creationflags=None, cwd=None, bufsize=0, encoding='utf-8', errors='strict', output_encoding=None):
stdin_pipe = None
if input is not None:
stdin_pipe = subprocess.PIPE
if isinstance(input, basestring):
input = input.encode(encoding, errors)
if creationflags is None:
if wx.Platform == "__WXMSW__":
creationflags = win32process.CREATE_NO_WINDOW
else:
creationflags = 0
process = subprocess.Popen(cmd, stdin=stdin_pipe, stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags=creationflags, cwd=cwd, bufsize=bufsize)
stdout_value, stderr_value = process.communicate(input)
returncode = process.returncode
if output_encoding is None:
output_encoding = encoding
stdout_value, stderr_value = stdout_value.decode(output_encoding, errors), stderr_value.decode(output_encoding, errors)
return stdout_value, stderr_value, returncode
def show_in_browser(url):
handle = webbrowser.get()
handle.open(url)
def get_default_path_for_executable(name):
if wx.Platform == "__WXMSW__":
exe_name = '{0}.exe'.format(name)
else:
exe_name = name
path = os.path.join(cwd, 'bin', exe_name)
if wx.Platform == "__WXGTK__":
if not os.path.exists(path):
path = '/usr/local/bin/{0}'.format(name)
if not os.path.exists(path):
path = '/usr/bin/{0}'.format(name)
return path
# p09 2014-10-14 [SS]
def get_ghostscript_path():
''' Fetches the ghostscript path from the windows registry and returns it.
This function may not see the 64-bit ghostscript installations, especially
if Python was compiled as a 32-bit application.
'''
if sys.version_info >= (3,0,0):
import winreg
else:
import _winreg as winreg
available_versions = []
for reg_key_name in [r"SOFTWARE\\GPL Ghostscript", r"SOFTWARE\\GNU Ghostscript"]:
try:
aReg = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
aKey = winreg.OpenKey(aReg, reg_key_name)
for i in range(100):
try:
version = winreg.EnumKey(aKey, i)
bKey = winreg.OpenKey(aReg, reg_key_name + "\\%s" % version)
value, _ = winreg.QueryValueEx(bKey, 'GS_DLL')
winreg.CloseKey(bKey)
path = os.path.join(os.path.dirname(value), 'gswin32c.exe')
if os.path.exists(path):
available_versions.append((version, path))
path = os.path.join(os.path.dirname(value), 'gswin64c.exe')
if os.path.exists(path):
available_versions.append((version, path))
except EnvironmentError:
break
winreg.CloseKey(aKey)
except:
pass
if available_versions:
return sorted(available_versions)[-1][1] # path to the latest version
else:
return None
# browser = None
# def upload_tune(tune, author):
# ''' upload the tune to the site ABC WIKI site folkwiki.se (this UI option is only visible if the OS language is Swedish) '''
# global browser
# import mechanize
# import tempfile
# tune = tune.replace('\r\n', '\n')
# text = '(:music:)\n%s\n(:musicend:)\n' % tune.strip()
# if not browser:
# browser = mechanize.Browser()
# response = browser.open('https://www.folkwiki.se/Meta/Nyl%c3%a5t?n=Meta.Nyl%c3%a5t&base=Musik.Musik&action=newnumbered')
# response = response.read()
# import pdb; pdb.set_trace()
# m = re.search(r"img src='(.*?action=captchaimage.*?)'", response)
# if m:
# captcha_url = m.group(1).encode('utf-8')
# f = tempfile.NamedTemporaryFile(delete=False)
# img_data = urlopen(captcha_url).read()
# urlretrieve(urlunparse(parsed), outpath)
# f.write(img_data)
# f.close()
# return ''
# browser.select_form(nr=1)
# browser['text'] = text.encode('utf-8')
# browser['author'] = author.encode('utf-8')
# response = browser.submit()
# url = response.geturl()
# url = url.split('?')[0] # remove the part after the first '?'
# return url
def launch_file(filepath):
''' open the given document using its associated program '''
if wx.Platform == "__WXMSW__":
os.startfile(filepath)
elif wx.Platform == "__WXMAC__":
subprocess.call(('open', filepath))
elif os.name == 'posix':
subprocess.call(('xdg-open', filepath))
return True
def remove_non_note_fragments(abc, exclude_grace_notes=False):
''' remove parts of the ABC which is not notes or bar symbols by replacing them by spaces (in order to preserve offsets) '''
repl_by_spaces = lambda m: ' ' * len(m.group(0))
# replace non-note fragments of the text by replacing them by spaces (thereby preserving offsets), but keep also bar and repeat symbols
abc = abc.replace('\r', '\n')
abc = re.sub(r'(?s)%%beginps.+?%%endps', repl_by_spaces, abc) # remove embedded postscript
abc = re.sub(r'(?s)%%begintext.+?%%endtext', repl_by_spaces, abc) # remove text
abc = re.sub(comment_pattern, repl_by_spaces, abc) # remove comments
abc = re.sub(r'\[\w:.*?\]', repl_by_spaces, abc) # remove embedded fields
abc = re.sub(r'(?m)^\w:.*?$', repl_by_spaces, abc) # remove normal fields
abc = re.sub(r'\\"', repl_by_spaces, abc) # remove escaped quote characters
abc = re.sub(r'".*?"', repl_by_spaces, abc) # remove strings
abc = re.sub(r'!.+?!', repl_by_spaces, abc) # remove ornaments like eg. !pralltriller!
abc = re.sub(r'\+.+?\+', repl_by_spaces, abc) # remove ornaments like eg. +pralltriller+
if exclude_grace_notes:
abc = re.sub(r'\{.*?\}', repl_by_spaces, abc) # remove grace notes
return abc
def get_notes_from_abc(abc, exclude_grace_notes=False):
''' returns a list of (start-offset, end-offset, abc-note-text) tuples for ABC notes/rests '''
if not isinstance(abc, str):
abc = abc.encode()
abc = remove_non_note_fragments(abc, exclude_grace_notes)
# find and return ABC notes (including the text ranges)
# 1.3.6.3 [JWDJ] 2015-3 made regex case sensitive again, because after typing Z and <space> a bar did not appear
return [(note.start(0), note.end(0), note.group(0)) for note in
re.finditer(r"([_=^]?[A-Ga-gz](,+|'+)?\d{0,2}(/\d{1,2}|/+)?)[><-]?", abc)]
def copy_bar_symbols_from_first_voice(abc):
# normalize line endings (necessary for ^ in regexp) and extract the header and the two voices
abc = re.sub(r'\r\n|\r', '\n', abc)
m = re.match(r'(?sm)(.*?K:[^\n]+\s+)^V: *1(.*?)^V: *2\s*(.*)', abc)
header, V1, V2 = m.groups()
# replace strings and other parts with spaces and locate all bar symbols
V1_clean = remove_non_note_fragments(V1)
V2_clean = remove_non_note_fragments(V2)
bar_seps1 = bar_sep_without_space.findall(V1_clean)
bar_seps2 = bar_sep_without_space.findall(V2_clean)
# abort, if the number of par symbols in the first and second voice doesn't match.
if len(bar_seps1) != len(bar_seps2):
print('warning: number of bar separators does not match (cannot complete operation)')
return abc
offset = 0
for m in bar_sep_without_space.finditer(V2_clean):
bar_symbol = bar_seps1.pop(0)
bar_symbol = ' %s ' % bar_symbol.strip()
start, end = m.start(0)+offset, m.end(0)+offset
if bar_symbol != V2[start:end]:
V2 = V2[:start] + bar_symbol + V2[end:]
offset += len(bar_symbol) - (end-start)
abc = header + 'V:1' + V1 + 'V:2\nI:repbra 0\n' + V2.lstrip()
abc = abc.replace('\n', os.linesep)
return abc
def process_MCM(abc):
""" Processes sticky rhythm feature of mcmusiceditor https://www.mcmusiceditor.com/download/sticky-rhythm.pdf
:param abc: abc possibly containing sticky rhythm
:return: abc-compliant
"""
abc, n = re.subn(r'(?m)^(L:\s*mcm_default)', r'L:1/8', abc)
if n:
# erase non-note fragments of the text by replacing them by spaces (thereby preserving offsets)
repl_by_spaces = lambda m: ' ' * len(m.group(0))
s = abc.replace('\r', '\n')
s = re.sub(r'(?s)%%begin(ps|text).+?%%end(ps|text)', repl_by_spaces, s) # remove embedded text/postscript
s = re.sub(r'(?m)^\w:.*?$|%.*$', repl_by_spaces, s) # remove non-embedded fields and comments
s = re.sub(r'".*?"|!.+?!|\+\w+?\+|\[\w:.*?\]', repl_by_spaces, s) # remove strings, ornaments and embedded fields
fragments = []
last_fragment_end = 0
for m in re.finditer(r"(?P<note>([_=^]?[A-Ga-gxz](,+|'+)?))(?P<len>\d{0,2})(?P<dot>\.?)", s):
if m.group('len') == '':
length = 0
else:
length = Fraction(8, int(m.group('len')))
if m.group('dot'):
length = length * 3 / 2
start, end = m.start(0), m.end(0)
fragments.append((False, abc[last_fragment_end:start]))
fragments.append((True, m.group('note') + str(length)))
last_fragment_end = end
fragments.append((False, abc[last_fragment_end:]))
abc = ''.join((text for is_note, text in fragments))
return abc
def get_hash_code(*args):
hash = hashlib.md5()
for arg in args:
if PY3 or type(arg) is unicode:
arg = arg.encode('utf-8', 'ignore')
hash.update(arg)
if PY3:
hash.update(program_name.encode('utf-8', 'ignore'))
else:
hash.update(program_name)
return hash.hexdigest()[:10]
def change_abc_tempo(abc_code, tempo_multiplier):
''' multiples all Q: fields in the abc code by the given multiplier and returns the modified abc code '''
def subfunc(m, multiplier):
try:
if '=' in m.group(0):
parts = m.group(0).split('=')
parts[1] = str(int(int(parts[1])*multiplier))
return '='.join(parts)
q = int(int(m.group(1))*multiplier)
if '[' in m.group(0):
return '[Q: %d]' % q
else:
return 'Q: %d' % q
except:
return m.group(0)
abc_code, n1 = re.subn(r'(?m)^Q: *(.+)', lambda m, mul=tempo_multiplier: subfunc(m, mul), abc_code)
abc_code, _ = re.subn(r'\[Q: *(.+)\]', lambda m, mul=tempo_multiplier: subfunc(m, mul), abc_code)
# if no Q: field that is not inline add a new Q: field after the X: line
# (it seems to be ignored by abcmidi if added earlier in the code)
if n1 == 0:
default_tempo = 120
extra_line = 'Q:%d' % int(default_tempo * tempo_multiplier)
lines = text_to_lines(abc_code)
for i in range(len(lines)):
if lines[i].startswith('X:'):
lines.insert(i+1, extra_line)
break
abc_code = os.linesep.join(lines)
return abc_code
def add_table_of_contents_to_postscript_file(filepath):
def to_ps_string(s): # handle unicode strings
if any(c for c in s if ord(c) > 127):
return '<FEFF%s>' % ''.join('%.4x' % ord(c) for c in s) # encode unicode
else:
return '(%s)' % s.replace('(', r'\(').replace(')', r'\)') # escape any parenthesis
lines = list(codecs.open(filepath, 'rU', 'utf-8'))
for line in lines:
if 'pdfmark' in line:
return # pdfmarks have already been added
new_lines = []
new_tune_state = False
tunes = []
for line in lines:
new_lines.append(line)
m = re.match(r'% --- (\d+) \((.*?)\) ---', line)
if m:
new_tune_state = True
tune_index, tune_title = m.group(1), m.group(2)
tunes.append((tune_index, tune_title))
if new_tune_state and (line.rstrip().endswith('showc') or
line.rstrip().endswith('showr') or
line.rstrip().endswith('show')):
ps_title = to_ps_string(decode_abc(tune_title))
new_lines.append('[ /Dest /NamedDest%s /View [ /XYZ null null null ] /DEST pdfmark' % tune_index)
new_lines.append('[ /Action /GoTo /Dest /NamedDest%s /Title %s /OUT pdfmark' % (tune_index, ps_title))
new_tune_state = False # now this tune has been handled, wait for next one....
codecs.open(filepath, 'wb', 'utf-8').write(os.linesep.join(new_lines))
def sort_abc_tunes(abc_code, sort_fields, keep_free_text=True):
lines = text_to_lines(abc_code)
tunes = []
file_header = []
preceeding_lines = []
Tune = namedtuple('Tune', 'lines header preceeding_lines')
cur_tune = None
for line in lines:
if line.startswith('X:'):
tune = Tune([], {}, [])
if tunes:
tune.preceeding_lines.extend(preceeding_lines)
else:
file_header = preceeding_lines
preceeding_lines = []
cur_tune = tune
tunes.append(cur_tune)
if cur_tune:
cur_tune.lines.append(line)
if re.match('[a-zA-Z]:', line):
field = line[0]
text = line[2:].strip().lower()
if field == 'X':
try:
text = int(text)
except:
pass
if field in cur_tune.header:
cur_tune.header[field] += '\n' + text
else:
cur_tune.header[field] = text
elif not line.strip():
cur_tune = None
preceeding_lines = [line]
else:
preceeding_lines.append(line)
def get_sort_key_for_tune(tune, sort_fields):
return tuple([tune.header.get(f, '').lower() for f in sort_fields])
tunes = [(get_sort_key_for_tune(t, sort_fields), t) for t in tunes]
tunes.sort()
result = file_header
for _, tune in tunes:
if result and result[-1].strip() != '':
result.append('')
if keep_free_text:
result.extend([l for l in tune.preceeding_lines if l.strip()])
L = tune.lines[:]
while L and not L[-1].strip():
del L[-1]
result.extend(L)
return os.linesep.join(result)
# 1.3.6 [SS] 2014-12-17
def process_abc_code(settings, abc_code, header, minimal_processing=False, tempo_multiplier=None, landscape=False):
''' adds file header and possibly some extra fields, and may also change the Q: field '''
#print traceback.extract_stack(None, 3)
extra_lines = \
'%%leftmargin 0.5cm\n' \
'%%rightmargin 0.5cm\n' \
'%%botmargin 0cm\n' \
'%%topmargin 0cm\n'
if minimal_processing or settings['abcm2ps_clean']:
extra_lines = ''
if settings['abcm2ps_number_bars']:
extra_lines += '%%barnumbers 1\n'
if settings['abcm2ps_no_lyrics']:
extra_lines += '%%musiconly 1\n'
if settings['abcm2ps_refnumbers']:
extra_lines += '%%withxrefs 1\n'
if settings['abcm2ps_ignore_ends']:
extra_lines += '%%continueall 1\n'
if settings['abcm2ps_clean'] == False and settings['abcm2ps_defaults'] == False:
extra_lines += '%%leftmargin ' + settings['abcm2ps_leftmargin'] + 'cm \n'
extra_lines += '%%rightmargin ' + settings['abcm2ps_rightmargin'] + 'cm \n'
extra_lines += '%%topmargin ' + settings['abcm2ps_topmargin'] + 'cm \n'
extra_lines += '%%botmargin ' + settings['abcm2ps_botmargin'] + 'cm \n'
extra_lines += '%%pagewidth ' + settings['abcm2ps_pagewidth'] + 'cm \n'
extra_lines += '%%pageheight ' + settings['abcm2ps_pageheight'] + 'cm \n'
extra_lines += '%%scale ' + settings['abcm2ps_scale'] + ' \n'
parts = []
if landscape and not minimal_processing:
parts.append('%%landscape 1\n')
if header:
parts.append(header.rstrip() + os.linesep)
if extra_lines:
parts.append(extra_lines)
parts.append(abc_code)
abc_code = ''.join(parts)
abc_code = re.sub(r'\[\[(.*/)(.+?)\]\]', r'\2', abc_code) # strip PmWiki links and just include the link text
if tempo_multiplier:
abc_code = change_abc_tempo(abc_code, tempo_multiplier)
abc_code = process_MCM(abc_code)
# 1.3.6.3 [JWdJ] 2015-04-22 fixing newlines to part of process_abc_code
abc_code = re.sub(r'\r\n|\r', '\n', abc_code) ## TEST
return abc_code
def AbcToPS(abc_code, cache_dir, extra_params='', abcm2ps_path=None, abcm2ps_format_path=None):
''' converts from abc to postscript. Returns (ps_file, error_message) tuple, where ps_file is None if the creation was not successful '''
global execmessages
# hash_code = get_hash_code(abc_code, read_text_if_file_exists(abcm2ps_format_path))
ps_file = os.path.abspath(os.path.join(cache_dir, 'temp.ps'))
# determine parameters
cmd1 = [abcm2ps_path, '-', '-O', '%s' % ps_file]
if extra_params:
# split extra_params on spaces, but treat quoted strings as one element even if they contain spaces
cmd1 = cmd1 + [x or y for (x, y) in re.findall(r'"(.+?)"|(\S+)', extra_params)]
if abcm2ps_format_path and not '-F' in cmd1:
# strip .fmt file ending
if abcm2ps_format_path.lower().endswith('.fmt'):
abcm2ps_format_path = abcm2ps_format_path[:-4]
cmd1 = cmd1 + ['-F', abcm2ps_format_path]
if os.path.exists(ps_file):
os.remove(ps_file)
input_abc = abc_code + os.linesep * 2
stdout_value, stderr_value, returncode = get_output_from_process(cmd1, input=input_abc, encoding=abcm2ps_default_encoding)
stderr_value = os.linesep.join([x for x in stderr_value.split('\n')
if not x.startswith('abcm2ps-') and not x.startswith('File ') and not x.startswith('Output written on ')])
stderr_value = stderr_value.strip()
execmessages += '\nAbcToPs\n' + " ".join(cmd1) + '\n' + stdout_value + stderr_value
if not os.path.exists(ps_file):
ps_file = None
return (ps_file, stderr_value)
def GetSvgFileList(first_page_file_path):
''' given 'file001.svg' this function will return all existing files in the series, eg. ['file001.svg', 'file002.svg'] '''
result = []
for i in range(1, 1000):
fn = first_page_file_path.replace('001.svg', '%.3d.svg' % i)
if os.path.exists(fn):
result.append(fn)
else:
break
return result
# 1.3.6 [SS] 2014-12-02 2014-12-07
def AbcToSvg(abc_code, header, cache_dir, settings, target_file_name=None, with_annotations=True, minimal_processing=False, landscape=False, one_file_per_page=True):
global visible_abc_code
# 1.3.6 [SS] 2014-12-17
abc_code = process_abc_code(settings, abc_code, header, minimal_processing=minimal_processing, landscape=landscape)
#hash = get_hash_code(abc_code, read_text_if_file_exists(abcm2ps_format_path), str(with_annotations)) # 1.3.6 [SS] 2014-11-13
visible_abc_code = abc_code
return abc_to_svg(abc_code, cache_dir, settings, target_file_name, with_annotations, one_file_per_page)
# 1.3.6.3 [JWDJ] 2015-04-21 splitted AbcToSvg up into 2 functions (abc_to_svg does not do preprocessing)
def abc_to_svg(abc_code, cache_dir, settings, target_file_name=None, with_annotations=True, one_file_per_page=True):
""" converts from abc to postscript. Returns (svg_files, error_message) tuple, where svg_files is an empty list if the creation was not successful """
global execmessages
# 1.3.6.3 [SS] 2015-05-01
global visible_abc_code
abcm2ps_path = settings.get('abcm2ps_path', '')
abcm2ps_format_path = settings.get('abcm2ps_format_path', '')
extra_params = settings.get('abcm2ps_extra_params', '')
# 1.3.6.3 [SS] 2015-05-01
visible_abc_code = abc_code
if target_file_name:
svg_file = target_file_name
svg_file_first = svg_file.replace('.svg', '001.svg')
else:
#grab svg file from cache if it exists
#svg_file = os.path.abspath(os.path.join(cache_dir, 'temp_%s.svg' % hash)) # 1.3.6 [SS] 2014-11-13
svg_file = os.path.abspath(os.path.join(cache_dir, 'temp.svg')) # 1.3.6 [SS] 2014-11-13
svg_file_first = svg_file.replace('.svg', '001.svg')
#if os.path.exists(svg_file_first): p09 disable cache
#return (GetSvgFileList(svg_file_first), '')
# 1.3.6 [SS] 2014-11-16
# clear out all 001.svg, 002.svg and etc. so the old files
# do not appear accidently
files_to_be_deleted = GetSvgFileList(svg_file_first)
for f in files_to_be_deleted:
os.remove(f)
# determine parameters
cmd1 = [abcm2ps_path, '-', '-O', '%s' % os.path.basename(svg_file)]
if one_file_per_page:
cmd1 = cmd1 + ['-v']
else:
cmd1 = cmd1 + ['-g']
if with_annotations:
cmd1 = cmd1 + ['-A']
if extra_params:
# split extra_params on spaces, but treat quoted strings as one element even if they contain spaces
cmd1 = cmd1 + [x or y for (x, y) in re.findall(r'"(.+?)"|(\S+)', extra_params)]
if abcm2ps_format_path and not '-F' in cmd1:
# strip .fmt file ending
if abcm2ps_format_path.lower().endswith('.fmt'):
abcm2ps_format_path = abcm2ps_format_path[:-4]
cmd1 = cmd1 + ['-F', abcm2ps_format_path]
if os.path.exists(svg_file_first):
os.remove(svg_file_first)
#fse = sys.getfilesystemencoding()
#cmd1 = [arg.encode(fse) if isinstance(arg,unicode) else arg for arg in cmd1]
# clear execmessages any time the music panel is refreshed
execmessages = u'\nAbcToSvg\n' + " ".join(cmd1)
input_abc = abc_code + os.linesep * 2
stdout_value, stderr_value, returncode = get_output_from_process(cmd1, input=input_abc, encoding=abcm2ps_default_encoding, bufsize=-1, cwd=os.path.dirname(svg_file))
execmessages += '\n' + stdout_value + stderr_value
if returncode < 0:
execmessages += '\n' + _('%(program)s exited abnormally (errorcode %(error)#8x)') % {'program': 'Abcm2ps', 'error': returncode & 0xffffffff}
raise Abcm2psException('Unknown error - abcm2ps may have crashed')
stderr_value = os.linesep.join([x for x in stderr_value.splitlines()
if not x.startswith('abcm2ps-') and not x.startswith('File ') and not x.startswith('Output written on ')])
stderr_value = stderr_value.strip()
if os.path.exists(svg_file_first):
return (GetSvgFileList(svg_file_first), stderr_value)
else:
return ([], stderr_value)
def AbcToAbc(abc_code, cache_dir, params, abc2abc_path=None):
' converts from abc to abc. Returns (abc_code, error_message) tuple, where abc_code is None if abc2abc was not successful'
global execmessages
abc_code = re.sub(r'\\"', '', abc_code) # remove escaped quote characters, since abc2abc cannot handle them
# determine parameters
cmd1 = [abc2abc_path, '-', '-r', '-b', '-e'] + params
execmessages += '\nAbcToAbc\n' + " ".join(cmd1)
input_abc = abc_code + os.linesep * 2
stdout_value, stderr_value, returncode = get_output_from_process(cmd1, bufsize=-1, input=input_abc, encoding=abcm2ps_default_encoding)
execmessages += '\n' + stderr_value
if returncode < 0:
execmessages += '\n' + _('%(program)s exited abnormally (errorcode %(error)#8x)') % {'program': 'Abc2abc', 'error': returncode & 0xffffffff}
stderr_value = stderr_value.strip()
stdout_value = stdout_value
if returncode == 0:
return stdout_value, stderr_value
else:
return None, stderr_value
# 1.3.6.4 [SS] 2015-06-22
def MidiToMftext(midi2abc_path, midifile):
' dissasemble midi file to text using midi2abc'
global execmessages
cmd1 = [midi2abc_path, midifile, '-mftext']
execmessages += '\nMidiToMftext\n' + " ".join(cmd1)
if os.path.exists(midi2abc_path):
stdout_value, stderr_value, returncode = get_output_from_process(cmd1, bufsize=-1)
midiframe = MyMidiTextTree(_('Disassembled Midi File'))
midiframe.Show(True)
midi_data = stdout_value
midi_lines = midi_data.splitlines()
midiframe.LoadMidiData(midi_lines)
else:
wx.MessageBox(_("Cannot find the executable midi2abc. Be sure it is in your bin folder and its path is defined in ABC Setup/File Settings."), _("Error"), wx.ICON_ERROR | wx.OK)
def get_midi_structure_as_text(midi2abc_path, midi_file):
result = u''
if os.path.exists(midi2abc_path):
cmd = [midi2abc_path, midi_file, '-mftext']
result, stderr_value, returncode = get_output_from_process(cmd, bufsize=-1)
return result
# p09 2014-10-14 2014-12-17 2015-01-28 [SS]
def AbcToPDF(settings, abc_code, header, cache_dir, extra_params='', abcm2ps_path=None, gs_path=None, abcm2ps_format_path=None, generate_toc=False):
global execmessages, visible_abc_code # 1.3.6.1 [SS] 2015-01-13
pdf_file = os.path.abspath(os.path.join(cache_dir, 'temp.pdf'))
# 1.3.6 [SS] 2014-12-17
abc_code = process_abc_code(settings, abc_code, header, minimal_processing=True)
(ps_file, error) = AbcToPS(abc_code, cache_dir, extra_params, abcm2ps_path, abcm2ps_format_path)
if not ps_file:
return None
#if generate_toc:
# add_table_of_contents_to_postscript_file(ps_file)
gs_path = unicode(gs_path)
# convert ps to pdf
# p09 we already checked for gs_path in restore_settings() 2014-10-14
cmd2 = [gs_path, '-sDEVICE=pdfwrite', '-sOutputFile=%s' % pdf_file, '-dBATCH', '-dNOPAUSE', ps_file]
# [SS] 2015-04-08
if wx.Platform == "__WXMAC__":
cmd2 = [gs_path, ps_file, '-o', pdf_file]
if os.path.exists(pdf_file):
os.remove(pdf_file)
# 1.3.6.1 [SS] 2015-01-13
execmessages += '\nAbcToPDF\n' + " ".join(cmd2)
stdout_value, stderr_value, returncode = get_output_from_process(cmd2)
# 1.3.6.1 [SS] 2015-01-13
execmessages += '\n' + stderr_value
if os.path.exists(pdf_file):
return pdf_file
# 1.3.6.4 [SS] 2015-07-10
gchordpat = re.compile('\"[^\"]+\"')
keypat = re.compile('([A-G]|[a-g]|)(#|b?)')
def test_for_guitar_chords(abccode):
''' The function returns False if there are no guitar chords
in the tune abccode; otherwise it returns True. It is
not sufficient to just find a token with enclosed by
double quotes. The token must begin with a letter between
A-G or a-g. We try up to 5 times in case, the token is
used to present other information above the staff.
The function is used to create a cleaner processed file
for MIDI by eliminating unnecessary %%MIDI commands.
'''
i = 0
k = 0
found = False
while k < 5:
m = gchordpat.search(abccode, i)
if m:
token = m.group(0)
i = m.end() + 1
if keypat.match(token[1:-1]):
found = True
break
else:
break
k = k + 1
return found
# 1.3.6.4 [SS] 2015-07-03
def list_voices_in(abccode):
''' The function scans the entire abccode searching for V:
and extracts the voice identifier (assuming it is not
too long). A list of all the unique identifiers are
returned.
'''
voices = []
[voices.append(v) for v in [m.group('voice_id') or m.group('inline_voice_id') for m in voice_re.finditer(abccode)] if v not in voices]
return voices
# 1.3.6.4 [SS] 2015-07-03
def grab_time_signature(abccode):
''' The function detects the first time signature M: n/m in
abccode and returns [n, m].
'''