-
Notifications
You must be signed in to change notification settings - Fork 2
/
MarkMelGen.py
4750 lines (4079 loc) · 214 KB
/
MarkMelGen.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
# free and open-source software, Paul Wardley Davies, see MarkMelGen/license.txt
# Using Markov Chains to Generate New Music
# See https://groups.google.com/g/music21list/c/WndF4uvp6_8/m/EkVLeLtlBQAJ
#
# To create Markov chain melodies:
# Choose a corpus of melodies.
# Iterate through the notes each melody, keeping track of the frequency that n notes moves to note x
# with a dictionary. So, the end result for a trigram should be something like
# Markov_dict = {('B', 'C'): {'A': .01, 'F': .02, 'B': .0 }, ('B', 'D'): {'A': .02, 'B': .01}, and so on...}.
# This gives you the transition probabilities.
# To compose, choose starting notes, then append further notes given the transitional probabilities.
import argparse
import ast
import configparser
import contextlib
import copy
import datetime
import json
import math
import music21
import pyparsing
import os
import random
import re
import sys
from enum import Enum, auto
from fractions import Fraction
from music21 import *
from music21.musicxml.archiveTools import compressXML
from music21.stream.makeNotation import consolidateCompletedTuplets
from music21.stream.makeNotation import splitElementsToCompleteTuplets
from numpy.random import choice
MARKMELGEN_VERSION = '1.0.0'
_section_name_matches = ['intro', 'verse', 'prechorus', 'chorus', 'solo', 'bridge', 'outro']
class Section(Enum):
INTRO = 0
VERSE = 1
PRECHORUS = 2
CHORUS = 3
SOLO = 4
BRIDGE = 5
OUTRO = 6
class Config_Song_Section(Enum):
song_intro = 0
song_verse = 1
song_prechorus = 2
song_chorus = 3
song_solo = 4
song_bridge = 5
song_outro = 6
CADENCE_ALTERNATE_PHRASE_END = False
# CADENCE_ALTERNATE_PHRASE_END = True
CADENCE_DUR_MIN = 1.0
# CADENCE_SECTION_END = False
CADENCE_SECTION_END = True
CADENCE_TONE_FREQUENCY = ''
CADENCE_TONE_PROBABILITY = ''
CADENCE_TONE_SAMPLES = ''
CALL_COUNT_MAX = 100
CONF_FILENAME = ''
DURATION_EQ = ''
DURATION_SET = []
DUR_RATIONAL = False
DUR_TUPLET = False
DUR_LEAST = 0
# DUR_LEAST = 0.25
# DUR_LEAST = Fraction(1, 12)
DUR_LONGEST = 0
# DUR_LONGEST = 0.25
# DUR_LONGEST = Fraction(1, 6)
DUR_PREV_DIFF = 0 # where 0, do not compare with previous duration, 2 is duration is >= 1/2 previous and <= 2 x previous etc
# DUR_PREV_DIFF = 0.5 # not valid so ignored
# DUR_PREV_DIFF = 1 # not valid so ignored
# DUR_PREV_DIFF = 1.1
# DUR_PREV_DIFF = 2
DURATION_MIN_MUSIC21 = 0.0005 # actually 1/2048th
here = os.path.dirname(os.path.abspath(__file__)) + '/'
INPUT_LYRICS_PATH = here
INPUT_MUSIC_PATH = here
INPUT_LYRICS_FILENAME = ''
INPUT_LYRICS_FULLY_QUALIFIED = ''
INPUT_MUSIC_FILENAME = ''
INPUT_MUSIC_FULLY_QUALIFIED = ''
INSTRUMENT = 'Piano'
MAX_PHRASE_REST = 8.0
OUTPUT_PATH = here
DISPLAY_GRAPHS = True
DISPLAY_SCORE = True
# lists of key values that control the durations and pitches for each section (Intro ... Outro)
# The final value is the default value for all sections.
PER_SECTION_LIST_LENGTH = 8
PER_SECTION_DURATION_SET = [None]*PER_SECTION_LIST_LENGTH
PER_SECTION_DUR_LEAST = [None]*PER_SECTION_LIST_LENGTH
PER_SECTION_DUR_LONGEST = [None]*PER_SECTION_LIST_LENGTH
PER_SECTION_DUR_PREV_DIFF = [None]*PER_SECTION_LIST_LENGTH
PER_SECTION_DUR_RATIONAL = [None]*PER_SECTION_LIST_LENGTH
PER_SECTION_DUR_TUPLET = [None]*PER_SECTION_LIST_LENGTH
PER_SECTION_REST_NOTE_LINE_OFFSET = [None]*PER_SECTION_LIST_LENGTH
PER_SECTION_TONES_ON_KEY = [None]*PER_SECTION_LIST_LENGTH
PER_SECTION_TONE_PREV_INTERVAL = [None]*PER_SECTION_LIST_LENGTH
PER_SECTION_TONE_RANGE_BOTTOM = [None]*PER_SECTION_LIST_LENGTH
PER_SECTION_TONE_RANGE_TOP = [None]*PER_SECTION_LIST_LENGTH
PER_SECTION_TONE_SCALE_SET = [None]*PER_SECTION_LIST_LENGTH
REST_NOTE_LINE_OFFSET = None
TEMPO_BPM = 0.0
TIME_SIG_WANTED = None
# TIME_SIG_WANTED = '3/4'
# TIME_SIG_WANTED = '4/4'
# Tone filters
TONE_ASCENT = False # Turn off TONE_ASCENT
TONE_ASCENT_COUNT = 0 # not a configuration paramenter, just a global variable
# TONE_ASCENT_MIN_INTERVAL = 1 # gives infinite loop on valid_note
TONE_ASCENT_MIN_INTERVAL = 2 # gives runs down scale
# TONE_ASCENT_MIN_INTERVAL = 3 # gives descent leaps
# TONE_ASCENT_MIN_INTERVAL = 4 # gives descent chord arpeggio
# TONE_ASCENT_TRIGGER = None
TONE_ASCENT_TRIGGER = 'C3'
TONE_ASCENT_TRIGGERED = False # not a configuration paramenter, just a global variable
TONE_ASCENT_TRIGGER_COUNT = 0 # not a configuration paramenter, just a global variable
TONE_ASCENT_TRIGGER_EVERY_N_TIMES = 1
TONE_DESCENT = False # Turn off TONE_DESCENT
TONE_DESCENT_COUNT = 0 # not a configuration paramenter, just a global variable
# TONE_DESCENT_MAX_INTERVAL = 1 # gives infinite loop on valid_note
TONE_DESCENT_MAX_INTERVAL = 2 # gives runs down scale
# TONE_DESCENT_MAX_INTERVAL = 3 # gives descent leaps
# TONE_DESCENT_MAX_INTERVAL = 4 # gives descent chord arpeggio
# TONE_DESCENT_TRIGGER = None
TONE_DESCENT_TRIGGER = 'C5'
TONE_DESCENT_TRIGGERED = False # not a configuration paramenter, just a global variable
TONE_DESCENT_TRIGGER_COUNT = 0 # not a configuration paramenter, just a global variable
TONE_DESCENT_TRIGGER_EVERY_N_TIMES = 4
TONE_EQ = ''
TONES_ON_KEY = False
# TONES_ON_KEY = True
TONES_OFF_KEY = False
# TONES_OFF_KEY = True
TONE_PREV_INTERVAL = 0 # maximum number of semitones between notes. 0 = Off
# TONE_PREV_INTERVAL = 1 # caused hang together with TONE_SCALE_SET
# TONE_PREV_INTERVAL = 2 # very limited melodic movement
# TONE_PREV_INTERVAL = 3 # very limited melodic movement
# TONE_PREV_INTERVAL = 4 # limited melodic movement
# TONE_PREV_INTERVAL = 5 # slightly limited melodic movement
# TONE_PREV_INTERVAL = 6 # slightly limited melodic movement
# TONE_PREV_INTERVAL = 7 # normal melodic movement
# TONE_PREV_INTERVAL = 8 # slightly jumpy melodic movement
# TONE_PREV_INTERVAL = 9 # slightly jumpy melodic movement
# TONE_PREV_INTERVAL = 10 # jumpy melodic movement
# TONE_PREV_INTERVAL = 11 # jumpy melodic movement
# TONE_PREV_INTERVAL = 12 # jumpy melodic movement
TONE_RANGE_MID = 'C4'
TONE_RANGE_BOTTOM = 'C3'
TONE_RANGE_TOP = 'C5'
TONE_SCALE_ANHEMITONIC = [1, 2, 4, 5,
6] # anhemitonic (without semitones; e.g., c–d–f–g–a–c′), pentatonic scale without semitones, 1 2 4 5 6 (AKA Japanese mode)
TONE_SCALE_HEMITONIC = [1, 3, 4, 5,
7] # hemitonic form (with semitones; e.g., c–e–f–g–b–c′) pentatonic scale with semitones 1 3 4 5 7
# TONE_SCALE_NEW = [2, 3, 4, 6, 7] # user defined scale
TONE_SCALE_SET = ['A', 'C', 'D', 'D#', 'E', 'G']
TONE_SCALE_ON_ANHEMITONIC = False
TONE_SCALE_ON_HEMITONIC = False
# ------------ FUNCTIONS -------------------------------------------
def add_new_lyrics_to_old_phrase(sect, section_name_text, section_line_num, lyric_line, stream_line):
"""
function that takes a stream of notes, wipes any old lyrics, adds new lyrics
and returns the new stream
"""
# print('add_new_lyrics_to_old_phrase')
# print('lyric_line', lyric_line)
# stream_line.show('text')
new_stream = music21.stream.Stream()
new_stream.append(stream_line)
# new_stream.show('text')
# split and count new lyric syllables
syllable_line = split_hyphens(lyric_line)
# print('syllable_line', syllable_line)
syllable_list = syllable_line.split() # Split `a_string` by whitespace.
# print('syllable_list', syllable_list)
number_of_syllables = len(syllable_list) ## counts he-llo as one syllable not two
# print('number_of_syllables', number_of_syllables)
note_num = 0
# wipe any old lyrics and add new lyrics
for n in new_stream.flat:
if type(n) == music21.note.Note:
# print('note', n, n.duration.quarterLength, n.lyric)
# print('n.lyrics', n.lyrics)
n.lyric = None
if note_num < number_of_syllables: # only set lyric when enough new syllables
n.lyric = syllable_list[note_num]
else:
print('Warning:Lyric-First', sect, 'line', section_line_num, 'has a lyric at note', (note_num + 1), 'but later', section_name_text, 'has no lyric there.')
note_num = note_num + 1
# if there are more new lyric syllables than old notes, add them to the next note/rest.
# if note_num <= number_of_syllables:
if note_num < number_of_syllables:
# e.g. Warning:Lyric-First Section.VERSE line 1 has 7 notes, but later Verse 2 has 8 syllables. 1 too many.
print('Warning:Lyric-First', sect, 'line', section_line_num, 'has', note_num,'notes, but later', section_name_text, 'has', number_of_syllables,
'syllables.', (number_of_syllables - note_num) , 'too many.' )
if (number_of_syllables - note_num) == 1:
n.lyric = ' ' + syllable_list[note_num]
if (number_of_syllables - note_num) == 2:
n.lyric = ' ' + syllable_list[note_num] + ' ' + syllable_list[note_num + 1]
if (number_of_syllables - note_num) == 3:
n.lyric = ' ' + syllable_list[note_num] + ' ' + syllable_list[note_num + 1] + ' ' + syllable_list[
note_num + 2]
if (number_of_syllables - note_num) == 4:
n.lyric = ' ' + syllable_list[note_num] + ' ' + syllable_list[note_num + 1] + ' ' + syllable_list[
note_num + 2] + ' ' + syllable_list[note_num + 3]
if (number_of_syllables - note_num) == 5:
n.lyric = ' ' + syllable_list[note_num] + ' ' + syllable_list[note_num + 1] + ' ' + syllable_list[
note_num + 2] + ' ' + syllable_list[note_num + 3] + ' ' + syllable_list[note_num + 4]
return new_stream
def remove_lyrics_from_phrase(stream_line):
"""
function that takes a stream of notes and rests, wipes any old lyrics
and returns the new stream
"""
new_stream = music21.stream.Stream()
new_stream.append(stream_line)
# wipe any old lyrics
for n in new_stream.flat:
if type(n) == music21.note.Note or type(n) == music21.note.Rest:
n.lyric = None
return new_stream
def get_semitone_interval(tone_prev, tone):
"""
function that takes two notes (with octave set)
and returns the semitone interval between them
"""
if tone_prev == 0 or tone == 0 or type(tone_prev) == music21.note.Rest:
return 0
if tone_prev.octave == None:
print('exit: Error get_semitone_interval tone_prev.octave == None ')
sys.exit()
if tone.octave == None:
print('exit: Error get_semitone_interval tone.octave == None ')
sys.exit()
# calculate interval
aInterval = interval.Interval(tone_prev, tone)
AIntSemi = abs(aInterval.semitones)
return AIntSemi
def calc_the_note_range(song):
"""
function that takes a song stream
and returns min_note.nameWithOctave and max_note.nameWithOctave
"""
min_note = note.Note()
max_note = note.Note()
min_note.nameWithOctave = 'C9'
max_note.nameWithOctave = 'A0'
for n in song.flat.notes:
if type(n) == music21.note.Note:
if note.Note(n.nameWithOctave) < note.Note(min_note.nameWithOctave):
min_note = n
# print('min_note.nameWithOctave', min_note.nameWithOctave)
if note.Note(n.nameWithOctave) > note.Note(max_note.nameWithOctave):
max_note = n
# print('max_note.nameWithOctave', max_note.nameWithOctave)
return min_note.nameWithOctave, max_note.nameWithOctave
def get_random_octave():
"""
function that uses
globals to
returns a valid random octave
"""
low_oct = int(TONE_RANGE_BOTTOM.strip()[-1])
high_oct = int(TONE_RANGE_TOP.strip()[-1])
the_valid_tone_octave = random.randint(low_oct, high_oct)
# print('get_random_octave: TONE_RANGE_BOTTOM',TONE_RANGE_BOTTOM,'TONE_RANGE_TOP',TONE_RANGE_TOP, 'low_oct', low_oct,'high_oct', high_oct , 'the_valid_tone_octave', the_valid_tone_octave )
the_valid_tone_octave = validated_octave(the_valid_tone_octave)
# print('get_random_octave: after validated_octave, the_valid_tone_octave', the_valid_tone_octave )
return the_valid_tone_octave
def get_valid_tone_octave(tone_prev, tone, desired_octave):
"""
function that takes a tone octave,
if not valid then choose a valid tone octave,
and return the valid tone octave
if tone in range: des oct
else:
if tp 0/None: random oct
else:
if tone with tone_prev.octave in range: use tp oct
else: if tone with tone_prev.octave+1 in range: use tp oct+1
else: if tone with tone_prev.octave-1 in range: use tp oct-1
else: random oct
N.B. it's generally better to set the name and octave separately
lowA = pitch.Pitch()
>>> lowA.name = 'A'
>>> lowA.octave = -1
>>> lowA.nameWithOctave
'A-1'
"""
# assume good but validate
# the_input_tone_octave = desired_octave
desired_octave = validated_octave(desired_octave)
the_valid_tone_octave = desired_octave
# a_valid_tone = False
tone.octave = desired_octave
# validate tone octave
if note.Note(TONE_RANGE_BOTTOM) <= note.Note(tone.nameWithOctave) <= note.Note(TONE_RANGE_TOP):
# a_valid_tone = True
# print('a valid tone octave', tone.nameWithOctave)
pass
else: # tone out of range
# if tone_prev == 0 or tone_prev.octave == None: # invalid prev_tone
if tone_prev == 0 or type(tone_prev) == music21.note.Rest: # invalid prev_tone
while True:
the_valid_tone_octave = get_random_octave()
print('invalid tone_prev 0 or None', tone_prev , ' new random octave', the_valid_tone_octave)
tone.octave = the_valid_tone_octave
# if note.Note(TONE_RANGE_BOTTOM) <= note.Note(tone.nameWithOctave) <= note.Note(TONE_RANGE_TOP):
if note.Note(TONE_RANGE_BOTTOM).octave <= note.Note(tone.nameWithOctave).octave <= note.Note(TONE_RANGE_TOP).octave:
break
else: # have a prev_tone octave
tone.octave = tone_prev.octave
if note.Note(TONE_RANGE_BOTTOM) <= note.Note(tone.nameWithOctave) <= note.Note(TONE_RANGE_TOP):
the_valid_tone_octave = tone.octave
# print('tone with tone_prev.octave in range: use tp oct, the_valid_tone_octave', the_valid_tone_octave)
else:
tone.octave = tone_prev.octave + 1
if note.Note(TONE_RANGE_BOTTOM) <= note.Note(tone.nameWithOctave) <= note.Note(TONE_RANGE_TOP):
the_valid_tone_octave = tone.octave
# print('tone with tone_prev.octave+1 in range: use tp oct, the_valid_tone_octave', the_valid_tone_octave)
else:
tone.octave = tone_prev.octave - 1
if note.Note(TONE_RANGE_BOTTOM) <= note.Note(tone.nameWithOctave) <= note.Note(TONE_RANGE_TOP):
the_valid_tone_octave = tone.octave
# print('tone with tone_prev.octave-1 in range: use tp oct, the_valid_tone_octave',
# the_valid_tone_octave)
else:
the_valid_tone_octave = get_random_octave()
# print('invalid tone_prev octave', note.Note(tone_prev.nameWithOctave), ' new random octave', the_valid_tone_octave)
the_valid_tone_octave = validated_octave(the_valid_tone_octave)
# print('get_valid_tone_octave(tone_prev ', tone_prev,' tone ', tone.nameWithOctave ,' desired_octave ', desired_octave, ' returns ', the_valid_tone_octave )
return the_valid_tone_octave
def get_tone_octave(tone_prev, tone, note_num ):
"""
function that takes the previous note and a note,
and the number of the note in the stream starting at 0
and returns the octave of the note
"""
if note_num == 0:
the_tone_octave = get_random_octave()
else:
if tone_prev == 0 or type(tone_prev) == music21.note.Rest:
mid_oct = get_random_octave()
else:
mid_oct = tone_prev.octave
low_oct = mid_oct - 1
high_oct = mid_oct + 1
tone.octave = mid_oct
mid_semis = get_semitone_interval(tone_prev, tone)
tone.octave = low_oct
low_semis = get_semitone_interval(tone_prev, tone)
tone.octave = high_oct
high_semis = get_semitone_interval(tone_prev, tone)
if low_semis <= mid_semis and mid_semis <= high_semis:
smallest_interval_octave = low_oct
largest_interval_octave = mid_oct
if low_semis <= high_semis and high_semis <= mid_semis:
smallest_interval_octave = low_oct
largest_interval_octave = high_oct
if mid_semis <= low_semis and low_semis <= high_semis:
smallest_interval_octave = mid_oct
largest_interval_octave = low_oct
if mid_semis <= high_semis and high_semis <= low_semis:
smallest_interval_octave = mid_oct
largest_interval_octave = high_oct
if high_semis <= low_semis and low_semis <= mid_semis:
smallest_interval_octave = high_oct
largest_interval_octave = low_oct
if high_semis <= mid_semis and mid_semis <= low_semis:
smallest_interval_octave = high_oct
largest_interval_octave = mid_oct
if TONE_INTERVAL == 'smallest':
# if new note = prev then use same octave as prev
if tone_prev == tone:
the_tone_octave = tone_prev.octave
else:
the_tone_octave = smallest_interval_octave
if TONE_INTERVAL == 'largest':
# if new note = prev then use same octave as prev
if tone_prev == tone:
the_tone_octave = tone_prev.octave + 1
else:
the_tone_octave = largest_interval_octave
if TONE_INTERVAL == 'random':
flip = random.randint(0, 1)
if flip == 0:
the_tone_octave = smallest_interval_octave
else:
the_tone_octave = largest_interval_octave
the_tone_octave = get_valid_tone_octave(tone_prev, tone, the_tone_octave)
# print('get_tone_octave(tone_prev', tone_prev,' tone ', tone.nameWithOctave, 'note_num in stream', note_num, ' returns ', the_tone_octave)
return the_tone_octave
###
def get_dur_to_next_measure_in_stream(stream_offset, beat_count):
"""
function that takes a stream_offset and beats to the bar count and
returns the duration to the next measure in the stream
"""
# prev_measure_offset = int('%.0f' % (stream_offset / beat_count)) # does not truncate, it rounds and truncates
prev_measure_offset = math.trunc(stream_offset / beat_count)
next_measure_offset = beat_count * (prev_measure_offset + 1)
dur_to_next_measure = next_measure_offset - stream_offset
return dur_to_next_measure
def truncate(f, n):
"""
function that takes a float f and the number of decimal places n
and truncates without rounding and
returns the truncated float
e.g.
>>> truncate(3.9, 0)
3.0
>>> truncate(4.0, 0)
4.0
>>> truncate(4.1, 0)
4.0
>>> truncate(4.11, 1)
4.1
>>> truncate(4.19, 1)
4.1
"""
return math.floor(f * 10 ** n) / 10 ** n
# def get_next_measure_end(the_offset, beat_count):
# """
# function that takes an offset and the number of beats in the bar and
# returns the offset of the next measure
# e.g. beat_count = 4
# offset 0 3.9 4.0 7.9 8.0
# return 4 4 8 8 12
# """
# # if the_offset == 0:
# # offset_end_bar = beat_count
# # else:
# # does not wotk for 4.0 , 4 returns 4, expect 8
# # bar_last_note_end = int(math.ceil(the_offset / beat_count))
# # # e.g. 3 = int(math.ceil(8.416666666666668 / 4))
# # offset_end_bar = bar_last_note_end * beat_count
# # # e.g. e.g. 12 = 3 * 4
# bar_of_offset = (int(truncate(the_offset,0) / beat_count)) + 1
# next_measure_end_offset = bar_of_offset * beat_count
#
# return next_measure_end_offset
def countKeySignatureByType(slist):
# Rachel Stroud https://core.ac.uk/download/pdf/386736181.pdf
# Function which counts all the key signatures in slist
# Function counts key signatures by type and movement
# Note that this function counts by the number of shaps and flats not the major/minor key
# Uses the first part ([0] in Python) to do this - all parts shouldhave same time signature!
p = 0 # part p = 0
# Possible key signatures range from -7 (7 flats: flat = -1) to +7 (7 sharps: sharp = +1)
# This scoring system of sharps = +1, flats = -1 is the same in the music21 key signature
# property .sharps
# Create list of possible key values ("keylist")
keylist = [-7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7]
# Initialise an empty count list structure: m movement lists of i key signature types
count = [[0] * len(keylist) for m in range(len(slist))]
# Loop through each movement in slist (m)
for m in range(0, len(slist)):
# Loop through key signatures in movement m, part p using music getElementsByClass recurse() function(el)
for el in slist[m].parts[p].recurse().getElementsByClass('KeySignature'):
# Loop through the known key signatures keylist (i) to search for a match for key signature el
for i in range(0, len(keylist)):
# If the el-th key signature matches the ith key signature value in key list,
# then we have found the position (i) of this key signature el in the keylist;
# add 1 to the relevant position in the count list structure
# (m-th movement, i-th type of key signature)
if el.sharps == keylist[i]:
count[m][i] = count[m][i] + 1
# Print results so easy to copy into e.g. Excel
# print('countKeySignatureByType results: key signatures in each movement separated by type')
# print('--> Key signature type')
# print('v Movement in slist')
# print('Key signature sharp (+1) and flats (-1):')
# print(keylist)
# print2DList(count) # See print functions below
return [keylist, count]
def print2DList(list2D):
# Function which prints out a list within a list as a table
# Loop through the outer list (i)
for i in range(0, len(list2D)):
# Create empty message string "msg"
msg = str()
# Loop through the list (j) at position i in the outer list
# Append the information at each position to the message msg (with a space inbetween each list item)
for j in range(0, len(list2D[i])):
msg = msg + str(list2D[i][j]) + ' '
# Print the message at the end of the inner loop
print(msg)
def get_keys(transition):
"""
given a transition
return the keys
"""
keys = [' '.join(map(str, i)) for i in list(transition.keys())]
return keys
def get_random_key(keys):
"""
given keys e.g. keys: ['C D', 'D E', 'E F', 'F G', 'G A', 'A B']
return a random key e.g. key: ('F', 'G')
"""
draw = choice(keys)
key = tuple(draw.split())
return key
# def get_cadence_note(key, cad_transition, dkey, cad_dtransition, lyric_syllable):
# """
# function that given the keys for the previous 2 notes and the cadence note and duration transitons and lyric
# returns the cadence note
# """
#
# print('get_cadence_note(key, dkey, lyric_syllable', key, dkey, lyric_syllable)
#
# # if there is a cadence note key transition for the previous 2 notes use that
# # if tone_prev_2 != None and tone_prev != None and ((tone_prev_2.name, tone_prev.name) in cad_transition):
# if tone_prev_2 != 0 and tone_prev != 0 and ((tone_prev_2.name, tone_prev.name) in cad_transition):
# cad_key = (tone_prev_2.name, tone_prev.name)
# # else get a random key cadence
# else:
# cad_keys = [' '.join(map(str, i)) for i in list(cad_transition.keys())]
# cad_key = get_random_key(cad_keys)
#
# # draw and create the note
# # cad_draw = choice(list(cad_transition[cad_key].keys()), 1, list(cad_transition[cad_key].values()))
# # n = music21.note.Note(cad_draw[0])
# cad_draw = get_random_draw(cad_key, cad_transition)
# n = music21.note.Note(cad_draw)
#
# # determine the octave for the cadence note
# octave = get_tone_octave(tone_prev, n, 1)
# n.octave = octave
#
# # if there is a cadence duration key transition for the previous 2 notes use that
# # if tone_prev_2 != None and tone_prev != None and ((tone_prev_2.duration.quarterLength, tone_prev.duration.quarterLength) in cad_dtransition):
# # if tone_prev_2 != None and tone_prev != None and ((str(tone_prev_2.duration.quarterLength), str(tone_prev.duration.quarterLength)) in cad_dtransition):
# if tone_prev_2 != 0 and tone_prev != 0 and (
# (str(tone_prev_2.duration.quarterLength), str(tone_prev.duration.quarterLength)) in cad_dtransition):
#
# # cad_dkey = (tone_prev_2.duration.quarterLength, tone_prev.duration.quarterLength)
# cad_dkey = (str(tone_prev_2.duration.quarterLength), str(tone_prev.duration.quarterLength))
#
# # else get a random duration cadence
# else:
# cad_dkeys = [' '.join(map(str, i)) for i in list(cad_dtransition.keys())]
# cad_dkey = get_random_key(cad_dkeys)
# # draw and set the duration
# # cad_ddraw = choice(list(cad_dtransition[cad_dkey].keys()), 1, list(cad_dtransition[cad_dkey].values()))
# # n.duration.quarterLength = cad_ddraw[0]
# cad_ddraw = get_random_draw(cad_dkey, cad_dtransition)
# n.duration.quarterLength = validated_duration(cad_ddraw, cad_dtransition, 1.0)
# # n.duration.quarterLength = cad_ddraw
#
# # add the lyric
# if lyric_syllable != None:
# n.lyric = lyric_syllable
#
# return n
def validated_octave(the_valid_tone_octave):
"""
function that given an octave
returns a validated octave
"""
if the_valid_tone_octave < 0:
print('validated_octave: tone_octave < 0 is ', the_valid_tone_octave, 'set the_valid_tone_octave = 0')
the_valid_tone_octave = 0
if the_valid_tone_octave > 9:
print('validated_octave: tone_octave > 9 is ', the_valid_tone_octave, 'set the_valid_tone_octave = 9')
the_valid_tone_octave = 9
return the_valid_tone_octave
# def validated_note(tone_prev, tone, tone_scale, tone_mode, key, transition, fallback_tone):
# """
# function that given a tone information and a fallback_note
# returns a validated note
# """
# call_count = 0
# while True: # start repeat until valid note or > CALL_COUNT_MAX
# call_count = call_count + 1
# if valid_tone(tone_prev, tone, tone_scale, tone_mode) or call_count > CALL_COUNT_MAX :
# break
# else:
# # keys = get_keys(transition)
# # key = get_random_key(keys)
# tone = get_random_draw(key, transition)
# if call_count > CALL_COUNT_MAX:
# tone = fallback_tone
# print('Warning: in validated_note, call_count > CALL_COUNT_MAX, fallback_tone:', fallback_tone, '\n key:', key)
# return tone
def keys_filter_condition(key, desired_key_ending):
"""
given a key and the desired_key_ending
return the key if it has the desired_key_ending
"""
# return key.endswith('1.0')
return key.endswith(desired_key_ending)
def get_one_state_key(key, transition):
"""
given a key (x,y) and a transition,
use the second value y in the key only to get a random one state key (*,y)
return the random one state key
"""
# print('get_one_state_key: key', key)
keys = get_keys(transition)
count = 0
valid = False
# filter keys on second key
desired_key_ending = key[1]
filtered_keys = [d for d in keys if keys_filter_condition(d, desired_key_ending)]
# print('filtered keys = ',filtered_keys)
if filtered_keys == []:
return key
else:
# random filtered key
filtered_key = get_random_key(filtered_keys)
# print('random filtered key = ',filtered_key)
return filtered_key
def get_note_with_octave(tone_prev, tone_name):
"""
Given a previous note and a tone_name
create a note, give it an octave based on the previous note
return the note
"""
tone = music21.note.Note(tone_name)
# determine the octave for the note
octave = get_tone_octave(tone_prev, tone, 1)
tone.octave = octave
return tone
def get_next_note(n_prev, tone_scale, tone_mode, key, transition, dkey, dtransition, lyric_syllable):
"""
function that given keys, transitions, lyric and scale
returns a note
"""
print('get_next_note(n_prev, tone_scale, tone_mode', n_prev, tone_scale, tone_mode, '\n key', key, '\n dkey', dkey, 'lyric ', lyric_syllable)
valid = False
count = 0
# attempt a valid n with 2 state key
while not valid and count < CALL_COUNT_MAX :
count += 1
if key not in transition:
break
tone_name = get_random_draw(key, transition)
n = get_note_with_octave(n_prev, tone_name)
if valid_pitch(n_prev, n, tone_scale, tone_mode):
valid = True
# print('2 state key valid_pitch(n_prev, n, ...) == True. n_prev=', n_prev, 'n=', n,)
# attempt a valid tone with 1 state key
count = 0
while not valid and count < CALL_COUNT_MAX :
count += 1
new_key = get_one_state_key(key, transition)
if new_key not in transition:
break
tone_name = get_random_draw(new_key, transition)
n = get_note_with_octave(n_prev, tone_name)
if valid_pitch(n_prev, n, tone_scale, tone_mode):
valid = True
print('1 state key valid_pitch(n_prev, n, ...) == True. n_prev=', n_prev, 'n=', n,)
# attempt a valid tone with random key
count = 0
while not valid and count < CALL_COUNT_MAX :
count += 1
keys = get_keys(transition)
new_key = get_random_key(keys)
if new_key not in transition:
continue
tone_name = get_random_draw(new_key, transition)
n = get_note_with_octave(n_prev, tone_name)
if valid_pitch(n_prev, n, tone_scale, tone_mode):
valid = True
print('random key valid_pitch(n_prev, n, ...) == True. n_prev=', n_prev, 'n=', n,)
if not valid:
# use fallback tone
tone_name = 'C'
n = get_note_with_octave(n_prev, tone_name)
print('Warning: in get_next_note: fallback tone used:', tone_name)
# get valid duration
valid = False
count = 0
# attempt a valid duration with 2 state key
while not valid and count < CALL_COUNT_MAX :
count += 1
if dkey not in dtransition:
break
dur = get_random_draw(dkey, dtransition)
if valid_duration(dkey[1], dur):
valid = True
print('2 state key valid_duration(dkey[1], dur) = True','dkey[1]=', dkey[1], 'dur=', dur)
# attempt a valid duration with 1 state key
count = 0
while not valid and count < CALL_COUNT_MAX :
count += 1
new_dkey = get_one_state_key(dkey, dtransition)
if new_dkey not in dtransition:
break
dur = get_random_draw(new_dkey, dtransition)
if valid_duration(dkey[1], dur):
valid = True
# print('1 state key valid_duration(dkey[1], dur) = True','dkey[1]=', dkey[1], 'dur=', dur)
# attempt a valid duration with random key
count = 0
while not valid and count < CALL_COUNT_MAX :
count += 1
dkeys = get_keys(dtransition)
new_dkey = get_random_key(dkeys)
if new_dkey not in dtransition:
continue
dur = get_random_draw(new_dkey, dtransition)
# print('Attempting random key valid_duration(dkey[1], dur) = True', 'dkey[1]=', dkey[1], 'dur=', dur)
if valid_duration(dkey[1], dur):
valid = True
print('random key valid_duration(dkey[1], dur) = True','dkey[1]=', dkey[1], 'dur=', dur)
# attempt a valid duration with DURATION_SET
if DURATION_SET:
count = 0
while not valid and count < CALL_COUNT_MAX :
count += 1
# get a random value from list
dur = random.choice(DURATION_SET)
if valid_duration(0, dur):
valid = True
print('Warning: in get_next_note: fallback dur', dur,'used from DURATION_SET', DURATION_SET)
if not valid:
# use fallback quarterLength duration
dur = 1.0
print('Warning: in get_next_note: fallback quarterLength duration used:', dur)
# add duration to note
n.duration.quarterLength = dur
# add the lyric
if lyric_syllable != None:
n.lyric = lyric_syllable
return n
def get_random_draw(key, transition):
"""
given a key and a transition
return a random draw
"""
draw = random.choices(list(transition[key].keys()), weights=transition[key].values(), k=1)[0]
return draw
def validated_duration(quarterLength, transition, fallback_quarterLength):
"""
given a quarterLength and a duration transition and keys
return a validated rest_note_duration
"""
call_count = 0
while True: # start repeat until valid duration or > CALL_COUNT_MAX
call_count = call_count + 1
if valid_duration(0, quarterLength) or call_count > CALL_COUNT_MAX :
break
else:
keys = get_keys(transition)
key = get_random_key(keys)
quarterLength = get_random_draw(key, transition)
if call_count > CALL_COUNT_MAX:
quarterLength = fallback_quarterLength
print('Warning: in validated_duration, call_count > CALL_COUNT_MAX, fallback_quarterLength used. quarterLength:', quarterLength, '\n transition:', transition, '\n fallback_quarterLength:', fallback_quarterLength)
return quarterLength
def get_nameWithOctave_from_cadence_tones(n_prev):
'''
given the previous note,
get random cadence tone
get the octave using the previous note
return the nameWithOctave
'''
if CADENCE_TONE_FREQUENCY == '':
print('exit: Error get_nameWithOctave_from_cadence_tones called when CADENCE_TONE_FREQUENCY is blank')
sys.exit()
else:
# get random cadence tone
cadence_tone = random.choice(CADENCE_TONE_SAMPLES)
# print('cadence_tone=', cadence_tone)
cadence_note = get_note_with_octave(n_prev, cadence_tone)
print('cadence_note.nameWithOctave=', cadence_note.nameWithOctave)
return cadence_note.nameWithOctave
def generate_markov_phrase_with_lyrics(sect, ts, tone_scale, tone_mode, transition, keys, dtransition, dkeys, cad_transition, cad_dtransition,
rest_note_transition, lyric_line, gmpwl_call_count):
"""
function that uses musical markov chains and a lyric line to
return a melodic stream with a line of lyrics
"""
if gmpwl_call_count == 1:
print(
'generate_markov_phrase_with_lyrics: sect, ts, tone_scale, tone_mode, transition, keys, dtransition, dkeys, cad_transition, cad_dtransition, rest_note_transition, lyric_line =',
sect, ts, tone_scale, tone_mode, '\n---transition---', transition, '\n---keys---', keys, '\n---dtransition---',
dtransition, '\n---dkeys---', dkeys, '\n---cad_transition', cad_transition, '\n---cad_dtransition', cad_dtransition,
'\n---rest_note_transition---', rest_note_transition, '\n---lyric_line---', lyric_line)
p_stream = music21.stream.Stream()
# random rest_note offset, REST_NOTE_LINE_OFFSET == None
rest_note_key = ('0.0', '0.0')
rest_note_draw = get_random_draw(rest_note_key, rest_note_transition)
r = music21.note.Rest()
r.duration.quarterLength = rest_note_draw
if r.duration.quarterLength > 0:
r.duration.quarterLength = validated_duration(r.duration.quarterLength, rest_note_transition, 0.0)
# override offset on the first note of each line
if REST_NOTE_LINE_OFFSET != None:
r.duration.quarterLength = REST_NOTE_LINE_OFFSET
if r.duration.quarterLength > 0:
p_stream.append(r)
show_text_of_note(r, ts)
print('rest_note_draw non-zero == ', r.duration.quarterLength, 'so first note of line will start then.')
else:
print('rest_note_draw == 0.0 so first note of line will start at the beginning of the bar.')
# split and count syllables
syllable_line = split_hyphens(lyric_line)
# print('syllable_line', syllable_line)
syllable_list = syllable_line.split() # Split `a_string` by whitespace.
# print('syllable_list', syllable_list)
number_of_syllables = len(syllable_list) ## counts he-llo as one syllable not two
# print('number_of_syllables', number_of_syllables)
# add initial rest on to duration_note_phrase length
duration_note_phrase = r.duration.quarterLength
# get new key for the new line
# print("initial key",key)
key = get_random_key(keys)
print("new key", key) # e.g. ('A', 'B') / ('B-', 'C') /('B', 'C') / ('C', 'D') / ('D', 'E') / ('E-', 'A')/ ('E', 'F') / ('F', 'G') / ('F#', 'A') / 'G', 'C')
# get new duration key (dkey) for the new line
# print("initial duration key (dkey) ", dkey)
dkey = get_random_key(dkeys)
print("new duration key (dkey)", dkey) # e.g. ('1/12', '0.5') / ('1/6', '0.25') ...
# set up previous note
n_prev = music21.note.Note(key[1])
# determine the octave for the previous note
octave = get_tone_octave(0, n_prev, 1)
n_prev.octave = octave
ddraw = get_random_draw(dkey, dtransition)
n_prev.duration.quarterLength = validated_duration(ddraw, dtransition, 1.0)
# Append a note or a rest to the score
# number of notes in phrase determined by the number_of_syllables
for note_num in range(number_of_syllables): # if range 6 then for 0 .. 5
if note_num == number_of_syllables - 1: # cadence note
print('cadence note: use cad_transition cad_dtransition')
n = get_next_note(n_prev, tone_scale, tone_mode, key, cad_transition, dkey, cad_dtransition, syllable_list[note_num] )
if CADENCE_TONE_FREQUENCY != '': n.nameWithOctave = get_nameWithOctave_from_cadence_tones(n_prev)
p_stream.append(n)
show_text_of_note(n, ts)
else:
# use transition dtransition
n = get_next_note(n_prev, tone_scale, tone_mode, key, transition, dkey, dtransition, syllable_list[note_num])
p_stream.append(n)
show_text_of_note(n, ts)
duration_note_phrase = duration_note_phrase + n.duration.quarterLength
# increment keys
key = (key[1], n.name)