projectlosangeles commited on
Commit
5f1a20c
·
verified ·
1 Parent(s): fcd8933

Upload 4 files

Browse files
Files changed (3) hide show
  1. TMIDIX.py +724 -38
  2. fluidsynth-master.zip +2 -2
  3. monster_search_and_filter.py +6 -6
TMIDIX.py CHANGED
@@ -5,9 +5,8 @@ r'''############################################################################
5
  #
6
  #
7
  # Tegridy MIDI X Module (TMIDI X / tee-midi eks)
8
- # Version 1.0
9
  #
10
- # NOTE: TMIDI X Module starts after the partial MIDI.py module @ line 1437
11
  #
12
  # Based upon MIDI.py module v.6.7. by Peter Billam / pjb.com.au
13
  #
@@ -26,7 +25,7 @@ r'''############################################################################
26
  # you may not use this file except in compliance with the License.
27
  # You may obtain a copy of the License at
28
  #
29
- # http://www.apache.org/licenses/LICENSE-2.0
30
  #
31
  # Unless required by applicable law or agreed to in writing, software
32
  # distributed under the License is distributed on an "AS IS" BASIS,
@@ -47,9 +46,23 @@ r'''############################################################################
47
  # Copyright 2020 Peter Billam
48
  #
49
  ###################################################################################
50
- ###################################################################################'''
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
  import sys, struct, copy
 
53
  Version = '6.7'
54
  VersionDate = '20201120'
55
 
@@ -1439,7 +1452,6 @@ def _encode(events_lol, unknown_callback=None, never_add_eot=False,
1439
  ###################################################################################
1440
  #
1441
  # Tegridy MIDI X Module (TMIDI X / tee-midi eks)
1442
- # Version 1.0
1443
  #
1444
  # Based upon and includes the amazing MIDI.py module v.6.7. by Peter Billam
1445
  # pjb.com.au
@@ -1492,6 +1504,12 @@ import psutil
1492
 
1493
  import json
1494
 
 
 
 
 
 
 
1495
  ###################################################################################
1496
  #
1497
  # Original TMIDI Tegridy helper functions
@@ -3856,7 +3874,7 @@ def fix_monophonic_score_durations(monophonic_score):
3856
  nmt = monophonic_score[i+1][1]
3857
 
3858
  if note[1]+note[2] >= nmt:
3859
- note_dur = nmt-note[1]-1
3860
  else:
3861
  note_dur = note[2]
3862
 
@@ -3874,7 +3892,7 @@ def fix_monophonic_score_durations(monophonic_score):
3874
  nmt = monophonic_score[i+1][0]
3875
 
3876
  if note[0]+note[1] >= nmt:
3877
- note_dur = nmt-note[0]-1
3878
  else:
3879
  note_dur = note[1]
3880
 
@@ -4144,15 +4162,16 @@ def tones_chord_to_pitches(tones_chord, base_pitch=60):
4144
  ###################################################################################
4145
 
4146
  def advanced_score_processor(raw_score,
4147
- patches_to_analyze=list(range(129)),
4148
- return_score_analysis=False,
4149
- return_enhanced_score=False,
4150
- return_enhanced_score_notes=False,
4151
- return_enhanced_monophonic_melody=False,
4152
- return_chordified_enhanced_score=False,
4153
- return_chordified_enhanced_score_with_lyrics=False,
4154
- return_score_tones_chords=False,
4155
- return_text_and_lyric_events=False
 
4156
  ):
4157
 
4158
  '''TMIDIX Advanced Score Processor'''
@@ -4192,6 +4211,9 @@ def advanced_score_processor(raw_score,
4192
  e[2] = e[2] % 16
4193
  e[3] = e[3] % 128
4194
 
 
 
 
4195
  basic_single_track_score.sort(key=lambda x: x[4] if x[0] == 'note' else 128, reverse=True)
4196
  basic_single_track_score.sort(key=lambda x: x[1])
4197
 
@@ -4706,7 +4728,8 @@ def augment_enhanced_score_notes(enhanced_score_notes,
4706
  ceil_timings=False,
4707
  round_timings=False,
4708
  legacy_timings=True,
4709
- sort_drums_last=False
 
4710
  ):
4711
 
4712
  esn = copy.deepcopy(enhanced_score_notes)
@@ -4749,6 +4772,16 @@ def augment_enhanced_score_notes(enhanced_score_notes,
4749
  e[4] = max(1, min(127, e[4] + pitch_shift))
4750
 
4751
  pe = enhanced_score_notes[i]
 
 
 
 
 
 
 
 
 
 
4752
 
4753
  if full_sorting:
4754
 
@@ -6689,12 +6722,23 @@ def find_next_bar(escore_notes, bar_time, start_note_idx, cur_bar):
6689
  def align_escore_notes_to_bars(escore_notes,
6690
  bar_time=4000,
6691
  trim_durations=False,
6692
- split_durations=False
 
6693
  ):
6694
 
6695
  #=============================================================================
 
 
 
 
 
 
 
 
 
 
6696
 
6697
- aligned_escore_notes = copy.deepcopy(escore_notes)
6698
 
6699
  abs_time = 0
6700
  nidx = 0
@@ -6706,13 +6750,13 @@ def align_escore_notes_to_bars(escore_notes,
6706
 
6707
  while next_bar:
6708
 
6709
- next_bar = find_next_bar(escore_notes, bar_time, nidx, bcount)
6710
 
6711
  if next_bar:
6712
-
6713
- gescore_notes = escore_notes[nidx:next_bar[1]]
6714
  else:
6715
- gescore_notes = escore_notes[nidx:]
6716
 
6717
  original_timings = [delta] + [(b[1]-a[1]) for a, b in zip(gescore_notes[:-1], gescore_notes[1:])]
6718
  adj_timings = adjust_numbers_to_sum(original_timings, bar_time)
@@ -6727,7 +6771,8 @@ def align_escore_notes_to_bars(escore_notes,
6727
  nidx += 1
6728
 
6729
  if next_bar:
6730
- delta = escore_notes[next_bar[1]][1]-escore_notes[next_bar[1]-1][1]
 
6731
  bcount += 1
6732
 
6733
  #=============================================================================
@@ -11293,28 +11338,83 @@ def system_memory_utilization(return_dict=False):
11293
 
11294
  ###################################################################################
11295
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11296
  def create_files_list(datasets_paths=['./'],
11297
  files_exts=['.mid', '.midi', '.kar', '.MID', '.MIDI', '.KAR'],
 
 
 
11298
  randomize_files_list=True,
 
 
 
11299
  verbose=True
11300
  ):
 
11301
  if verbose:
11302
  print('=' * 70)
11303
  print('Searching for files...')
11304
  print('This may take a while on a large dataset in particular...')
11305
  print('=' * 70)
11306
 
11307
- filez_set = defaultdict(None)
11308
-
11309
  files_exts = tuple(files_exts)
11310
 
11311
- for dataset_addr in tqdm.tqdm(datasets_paths, disable=not verbose):
11312
- for dirpath, dirnames, filenames in os.walk(dataset_addr):
11313
- for file in filenames:
11314
- if file not in filez_set and file.endswith(files_exts):
11315
- filez_set[os.path.join(dirpath, file)] = None
11316
-
11317
- filez = list(filez_set.keys())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11318
 
11319
  if verbose:
11320
  print('Done!')
@@ -11334,6 +11434,7 @@ def create_files_list(datasets_paths=['./'],
11334
 
11335
  if verbose:
11336
  print('Found', len(filez), 'files.')
 
11337
  print('=' * 70)
11338
 
11339
  else:
@@ -11341,8 +11442,20 @@ def create_files_list(datasets_paths=['./'],
11341
  print('Could not find any files...')
11342
  print('Please check dataset dirs and files extensions...')
11343
  print('=' * 70)
 
 
 
 
11344
 
11345
- return filez
 
 
 
 
 
 
 
 
11346
 
11347
  ###################################################################################
11348
 
@@ -12163,8 +12276,16 @@ def escore_notes_pitches_chords_signature(escore_notes,
12163
  sort_by_counts=False,
12164
  use_full_chords=False
12165
  ):
 
 
 
 
 
 
 
 
12166
 
12167
- escore_notes = [e for e in escore_notes if e[6] <= max_patch % 129]
12168
 
12169
  if escore_notes:
12170
 
@@ -12173,7 +12294,7 @@ def escore_notes_pitches_chords_signature(escore_notes,
12173
  sig = []
12174
  dsig = []
12175
 
12176
- drums_offset = 321 + 128
12177
 
12178
  bad_chords_counter = 0
12179
 
@@ -12190,10 +12311,10 @@ def escore_notes_pitches_chords_signature(escore_notes,
12190
  tones_chord = sorted(set([p % 12 for p in pitches]))
12191
 
12192
  try:
12193
- sig_token = ALL_CHORDS_SORTED.index(tones_chord) + 128
12194
  except:
12195
  checked_tones_chord = check_and_fix_tones_chord(tones_chord, use_full_chords=use_full_chords)
12196
- sig_token = ALL_CHORDS_SORTED.index(checked_tones_chord) + 128
12197
  bad_chords_counter += 1
12198
 
12199
  elif len(pitches) == 1:
@@ -12226,6 +12347,571 @@ def escore_notes_pitches_chords_signature(escore_notes,
12226
  else:
12227
  return []
12228
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12229
  ###################################################################################
12230
  # This is the end of the TMIDI X Python module
12231
  ###################################################################################
 
5
  #
6
  #
7
  # Tegridy MIDI X Module (TMIDI X / tee-midi eks)
 
8
  #
9
+ # NOTE: TMIDI X Module starts after the partial MIDI.py module @ line 1450
10
  #
11
  # Based upon MIDI.py module v.6.7. by Peter Billam / pjb.com.au
12
  #
 
25
  # you may not use this file except in compliance with the License.
26
  # You may obtain a copy of the License at
27
  #
28
+ # http://www.apache.org/licenses/LICENSE-2.0
29
  #
30
  # Unless required by applicable law or agreed to in writing, software
31
  # distributed under the License is distributed on an "AS IS" BASIS,
 
46
  # Copyright 2020 Peter Billam
47
  #
48
  ###################################################################################
49
+ ###################################################################################
50
+ '''
51
+
52
+ ###################################################################################
53
+
54
+ __version__ = "25.4.28"
55
+
56
+ print('=' * 70)
57
+ print('TMIDIX Python module')
58
+ print('Version:', __version__)
59
+ print('=' * 70)
60
+ print('Loading module...')
61
+
62
+ ###################################################################################
63
 
64
  import sys, struct, copy
65
+
66
  Version = '6.7'
67
  VersionDate = '20201120'
68
 
 
1452
  ###################################################################################
1453
  #
1454
  # Tegridy MIDI X Module (TMIDI X / tee-midi eks)
 
1455
  #
1456
  # Based upon and includes the amazing MIDI.py module v.6.7. by Peter Billam
1457
  # pjb.com.au
 
1504
 
1505
  import json
1506
 
1507
+ from pathlib import Path
1508
+
1509
+ import shutil
1510
+
1511
+ import hashlib
1512
+
1513
  ###################################################################################
1514
  #
1515
  # Original TMIDI Tegridy helper functions
 
3874
  nmt = monophonic_score[i+1][1]
3875
 
3876
  if note[1]+note[2] >= nmt:
3877
+ note_dur = max(1, nmt-note[1]-1)
3878
  else:
3879
  note_dur = note[2]
3880
 
 
3892
  nmt = monophonic_score[i+1][0]
3893
 
3894
  if note[0]+note[1] >= nmt:
3895
+ note_dur = max(1, nmt-note[0]-1)
3896
  else:
3897
  note_dur = note[1]
3898
 
 
4162
  ###################################################################################
4163
 
4164
  def advanced_score_processor(raw_score,
4165
+ patches_to_analyze=list(range(129)),
4166
+ return_score_analysis=False,
4167
+ return_enhanced_score=False,
4168
+ return_enhanced_score_notes=False,
4169
+ return_enhanced_monophonic_melody=False,
4170
+ return_chordified_enhanced_score=False,
4171
+ return_chordified_enhanced_score_with_lyrics=False,
4172
+ return_score_tones_chords=False,
4173
+ return_text_and_lyric_events=False,
4174
+ apply_sustain=False
4175
  ):
4176
 
4177
  '''TMIDIX Advanced Score Processor'''
 
4211
  e[2] = e[2] % 16
4212
  e[3] = e[3] % 128
4213
 
4214
+ if apply_sustain:
4215
+ apply_sustain_to_ms_score([1000, basic_single_track_score])
4216
+
4217
  basic_single_track_score.sort(key=lambda x: x[4] if x[0] == 'note' else 128, reverse=True)
4218
  basic_single_track_score.sort(key=lambda x: x[1])
4219
 
 
4728
  ceil_timings=False,
4729
  round_timings=False,
4730
  legacy_timings=True,
4731
+ sort_drums_last=False,
4732
+ even_timings=False
4733
  ):
4734
 
4735
  esn = copy.deepcopy(enhanced_score_notes)
 
4772
  e[4] = max(1, min(127, e[4] + pitch_shift))
4773
 
4774
  pe = enhanced_score_notes[i]
4775
+
4776
+
4777
+ if even_timings:
4778
+
4779
+ for e in esn:
4780
+ if e[1] % 2 != 0:
4781
+ e[1] += 1
4782
+
4783
+ if e[2] % 2 != 0:
4784
+ e[2] += 1
4785
 
4786
  if full_sorting:
4787
 
 
6722
  def align_escore_notes_to_bars(escore_notes,
6723
  bar_time=4000,
6724
  trim_durations=False,
6725
+ split_durations=False,
6726
+ even_timings=False
6727
  ):
6728
 
6729
  #=============================================================================
6730
+
6731
+ escore = copy.deepcopy(escore_notes)
6732
+
6733
+ if even_timings:
6734
+ for e in escore:
6735
+ if e[1] % 2 != 0:
6736
+ e[1] += 1
6737
+
6738
+ if e[2] % 2 != 0:
6739
+ e[2] += 1
6740
 
6741
+ aligned_escore_notes = copy.deepcopy(escore)
6742
 
6743
  abs_time = 0
6744
  nidx = 0
 
6750
 
6751
  while next_bar:
6752
 
6753
+ next_bar = find_next_bar(escore, bar_time, nidx, bcount)
6754
 
6755
  if next_bar:
6756
+ gescore_notes = escore[nidx:next_bar[1]]
6757
+
6758
  else:
6759
+ gescore_notes = escore[nidx:]
6760
 
6761
  original_timings = [delta] + [(b[1]-a[1]) for a, b in zip(gescore_notes[:-1], gescore_notes[1:])]
6762
  adj_timings = adjust_numbers_to_sum(original_timings, bar_time)
 
6771
  nidx += 1
6772
 
6773
  if next_bar:
6774
+ delta = escore[next_bar[1]][1]-escore[next_bar[1]-1][1]
6775
+
6776
  bcount += 1
6777
 
6778
  #=============================================================================
 
11338
 
11339
  ###################################################################################
11340
 
11341
+ def system_cpus_utilization(return_dict=False):
11342
+
11343
+ if return_dict:
11344
+ return {'num_cpus': psutil.cpu_count(),
11345
+ 'cpus_util': psutil.cpu_percent()
11346
+ }
11347
+
11348
+ else:
11349
+ print('Number of CPUs:', psutil.cpu_count())
11350
+ print('CPUs utilization:', psutil.cpu_percent())
11351
+
11352
+ ###################################################################################
11353
+
11354
  def create_files_list(datasets_paths=['./'],
11355
  files_exts=['.mid', '.midi', '.kar', '.MID', '.MIDI', '.KAR'],
11356
+ max_num_files_per_dir=-1,
11357
+ randomize_dir_files=False,
11358
+ max_total_files=-1,
11359
  randomize_files_list=True,
11360
+ check_for_dupes=False,
11361
+ use_md5_hashes=False,
11362
+ return_dupes=False,
11363
  verbose=True
11364
  ):
11365
+
11366
  if verbose:
11367
  print('=' * 70)
11368
  print('Searching for files...')
11369
  print('This may take a while on a large dataset in particular...')
11370
  print('=' * 70)
11371
 
 
 
11372
  files_exts = tuple(files_exts)
11373
 
11374
+ filez_set = defaultdict(None)
11375
+ dupes_list = []
11376
+
11377
+ for dataset_addr in datasets_paths:
11378
+
11379
+ print('=' * 70)
11380
+ print('Processing', dataset_addr)
11381
+ print('=' * 70)
11382
+
11383
+ for dirpath, dirnames, filenames in tqdm.tqdm(os.walk(dataset_addr), disable=not verbose):
11384
+
11385
+ if randomize_dir_files:
11386
+ random.shuffle(filenames)
11387
+
11388
+ if max_num_files_per_dir > 0:
11389
+ max_num_files = max_num_files_per_dir
11390
+
11391
+ else:
11392
+ max_num_files = len(filenames)
11393
+
11394
+ for file in filenames[:max_num_files]:
11395
+ if file.endswith(files_exts):
11396
+ if check_for_dupes:
11397
+
11398
+ if use_md5_hashes:
11399
+ md5_hash = hashlib.md5(open(os.path.join(dirpath, file), 'rb').read()).hexdigest()
11400
+
11401
+ if md5_hash not in filez_set:
11402
+ filez_set[md5_hash] = os.path.join(dirpath, file)
11403
+
11404
+ else:
11405
+ dupes_list.append(os.path.join(dirpath, file))
11406
+
11407
+ else:
11408
+ if file not in filez_set:
11409
+ filez_set[file] = os.path.join(dirpath, file)
11410
+
11411
+ else:
11412
+ dupes_list.append(os.path.join(dirpath, file))
11413
+ else:
11414
+ fpath = os.path.join(dirpath, file)
11415
+ filez_set[fpath] = fpath
11416
+
11417
+ filez = list(filez_set.values())
11418
 
11419
  if verbose:
11420
  print('Done!')
 
11434
 
11435
  if verbose:
11436
  print('Found', len(filez), 'files.')
11437
+ print('Skipped', len(dupes_list), 'duplicate files.')
11438
  print('=' * 70)
11439
 
11440
  else:
 
11442
  print('Could not find any files...')
11443
  print('Please check dataset dirs and files extensions...')
11444
  print('=' * 70)
11445
+
11446
+ if max_total_files > 0:
11447
+ if return_dupes:
11448
+ return filez[:max_total_files], dupes_list
11449
 
11450
+ else:
11451
+ return filez[:max_total_files]
11452
+
11453
+ else:
11454
+ if return_dupes:
11455
+ return filez, dupes_list
11456
+
11457
+ else:
11458
+ return filez
11459
 
11460
  ###################################################################################
11461
 
 
12276
  sort_by_counts=False,
12277
  use_full_chords=False
12278
  ):
12279
+
12280
+ if use_full_chords:
12281
+ CHORDS = ALL_CHORDS_FULL
12282
+
12283
+ else:
12284
+ CHORDS = ALL_CHORDS_SORTED
12285
+
12286
+ max_patch = max(0, min(128, max_patch))
12287
 
12288
+ escore_notes = [e for e in escore_notes if e[6] <= max_patch]
12289
 
12290
  if escore_notes:
12291
 
 
12294
  sig = []
12295
  dsig = []
12296
 
12297
+ drums_offset = len(CHORDS) + 128
12298
 
12299
  bad_chords_counter = 0
12300
 
 
12311
  tones_chord = sorted(set([p % 12 for p in pitches]))
12312
 
12313
  try:
12314
+ sig_token = CHORDS.index(tones_chord) + 128
12315
  except:
12316
  checked_tones_chord = check_and_fix_tones_chord(tones_chord, use_full_chords=use_full_chords)
12317
+ sig_token = CHORDS.index(checked_tones_chord) + 128
12318
  bad_chords_counter += 1
12319
 
12320
  elif len(pitches) == 1:
 
12347
  else:
12348
  return []
12349
 
12350
+ ###################################################################################
12351
+
12352
+ def compute_sustain_intervals(events):
12353
+
12354
+ intervals = []
12355
+ pedal_on = False
12356
+ current_start = None
12357
+
12358
+ for t, cc in events:
12359
+ if not pedal_on and cc >= 64:
12360
+
12361
+ pedal_on = True
12362
+ current_start = t
12363
+ elif pedal_on and cc < 64:
12364
+
12365
+ pedal_on = False
12366
+ intervals.append((current_start, t))
12367
+ current_start = None
12368
+
12369
+ if pedal_on:
12370
+ intervals.append((current_start, float('inf')))
12371
+
12372
+ merged = []
12373
+
12374
+ for interval in intervals:
12375
+ if merged and interval[0] <= merged[-1][1]:
12376
+ merged[-1] = (merged[-1][0], max(merged[-1][1], interval[1]))
12377
+ else:
12378
+ merged.append(interval)
12379
+ return merged
12380
+
12381
+ ###################################################################################
12382
+
12383
+ def apply_sustain_to_ms_score(score):
12384
+
12385
+ sustain_by_channel = {}
12386
+
12387
+ for track in score[1:]:
12388
+ for event in track:
12389
+ if event[0] == 'control_change' and event[3] == 64:
12390
+ channel = event[2]
12391
+ sustain_by_channel.setdefault(channel, []).append((event[1], event[4]))
12392
+
12393
+ sustain_intervals_by_channel = {}
12394
+
12395
+ for channel, events in sustain_by_channel.items():
12396
+ events.sort(key=lambda x: x[0])
12397
+ sustain_intervals_by_channel[channel] = compute_sustain_intervals(events)
12398
+
12399
+ global_max_off = 0
12400
+
12401
+ for track in score[1:]:
12402
+ for event in track:
12403
+ if event[0] == 'note':
12404
+ global_max_off = max(global_max_off, event[1] + event[2])
12405
+
12406
+ for channel, intervals in sustain_intervals_by_channel.items():
12407
+ updated_intervals = []
12408
+ for start, end in intervals:
12409
+ if end == float('inf'):
12410
+ end = global_max_off
12411
+ updated_intervals.append((start, end))
12412
+ sustain_intervals_by_channel[channel] = updated_intervals
12413
+
12414
+ if sustain_intervals_by_channel:
12415
+
12416
+ for track in score[1:]:
12417
+ for event in track:
12418
+ if event[0] == 'note':
12419
+ start = event[1]
12420
+ nominal_dur = event[2]
12421
+ nominal_off = start + nominal_dur
12422
+ channel = event[3]
12423
+
12424
+ intervals = sustain_intervals_by_channel.get(channel, [])
12425
+ effective_off = nominal_off
12426
+
12427
+ for intv_start, intv_end in intervals:
12428
+ if intv_start < nominal_off < intv_end:
12429
+ effective_off = intv_end
12430
+ break
12431
+
12432
+ effective_dur = effective_off - start
12433
+
12434
+ event[2] = effective_dur
12435
+
12436
+ return score
12437
+
12438
+ ###################################################################################
12439
+
12440
+ def copy_file(src_file: str, trg_dir: str, add_subdir: bool = False, verbose: bool = False):
12441
+
12442
+ src_path = Path(src_file)
12443
+ target_directory = Path(trg_dir)
12444
+
12445
+ if not src_path.is_file():
12446
+ if verbose:
12447
+ print("Source file does not exist or is not a file.")
12448
+
12449
+ return None
12450
+
12451
+ target_directory.mkdir(parents=True, exist_ok=True)
12452
+
12453
+ if add_subdir:
12454
+ first_letter = src_path.name[0]
12455
+ target_directory = target_directory / first_letter
12456
+ target_directory.mkdir(parents=True, exist_ok=True)
12457
+
12458
+ destination = target_directory / src_path.name
12459
+
12460
+ try:
12461
+ shutil.copy2(src_path, destination)
12462
+
12463
+ except:
12464
+ if verbose:
12465
+ print('File could not be copied!')
12466
+
12467
+ return None
12468
+
12469
+ if verbose:
12470
+ print('File copied!')
12471
+
12472
+ return None
12473
+
12474
+ ###################################################################################
12475
+
12476
+ def escore_notes_even_timings(escore_notes, in_place=True):
12477
+
12478
+ if in_place:
12479
+ for e in escore_notes:
12480
+ if e[1] % 2 != 0:
12481
+ e[1] += 1
12482
+
12483
+ if e[2] % 2 != 0:
12484
+ e[2] += 1
12485
+
12486
+ return []
12487
+
12488
+ else:
12489
+ escore = copy.deepcopy(escore_notes)
12490
+
12491
+ for e in escore:
12492
+ if e[1] % 2 != 0:
12493
+ e[1] += 1
12494
+
12495
+ if e[2] % 2 != 0:
12496
+ e[2] += 1
12497
+
12498
+ return escore
12499
+
12500
+ ###################################################################################
12501
+
12502
+ def both_chords(chord1, chord2, merge_threshold=2):
12503
+
12504
+ if len(chord1) > 1 and len(chord2) > 0 and chord2[0][1]-chord1[0][1] <= merge_threshold:
12505
+ return True
12506
+
12507
+ elif len(chord1) > 0 and len(chord2) > 1 and chord2[0][1]-chord1[0][1] <= merge_threshold:
12508
+ return True
12509
+
12510
+ else:
12511
+ return False
12512
+
12513
+ def merge_chords(chord1, chord2, sort_drums_last=False):
12514
+
12515
+ mchord = chord1
12516
+
12517
+ seen = []
12518
+
12519
+ for e in chord2:
12520
+ if tuple([e[4], e[6]]) not in seen:
12521
+ mchord.append(e)
12522
+ seen.append(tuple([e[4], e[6]]))
12523
+
12524
+ for e in mchord[1:]:
12525
+ e[1] = mchord[0][1]
12526
+
12527
+ if sort_drums_last:
12528
+ mchord.sort(key=lambda x: (-x[4], x[6]) if x[6] != 128 else (x[6], -x[4]))
12529
+
12530
+ else:
12531
+ mchord.sort(key=lambda x: (-x[4], x[6]))
12532
+
12533
+ return mchord
12534
+
12535
+ def merge_escore_notes(escore_notes, merge_threshold=2, sort_drums_last=False):
12536
+
12537
+ cscore = chordify_score([1000, escore_notes])
12538
+
12539
+ merged_chords = []
12540
+ merged_chord = cscore[0]
12541
+
12542
+ for i in range(1, len(cscore)):
12543
+
12544
+ cchord = cscore[i]
12545
+
12546
+ if both_chords(merged_chord, cchord, merge_threshold=merge_threshold):
12547
+ merged_chord = merge_chords(merged_chord, cchord, sort_drums_last=sort_drums_last)
12548
+
12549
+ else:
12550
+ merged_chords.append(merged_chord)
12551
+ merged_chord = cchord
12552
+
12553
+ return flatten(merged_chords)
12554
+
12555
+ ###################################################################################
12556
+
12557
+ def solo_piano_escore_notes_tokenized(escore_notes,
12558
+ compress_start_times=True,
12559
+ encode_velocities=False,
12560
+ verbose=False
12561
+ ):
12562
+
12563
+ if verbose:
12564
+ print('=' * 70)
12565
+ print('Encoding MIDI...')
12566
+
12567
+ sp_escore_notes = solo_piano_escore_notes(escore_notes)
12568
+ zscore = recalculate_score_timings(sp_escore_notes)
12569
+ dscore = delta_score_notes(zscore, timings_clip_value=127)
12570
+
12571
+ score = []
12572
+
12573
+ notes_counter = 0
12574
+ chords_counter = 1
12575
+
12576
+ for i, e in enumerate(dscore):
12577
+
12578
+ dtime = e[1]
12579
+ dur = e[2]
12580
+ ptc = e[4]
12581
+ vel = e[5]
12582
+
12583
+ if compress_start_times:
12584
+
12585
+ if i == 0:
12586
+ score.extend([0, dur+128, ptc+256])
12587
+
12588
+ if encode_velocities:
12589
+ score.append(vel+384)
12590
+
12591
+ else:
12592
+ if dtime == 0:
12593
+ score.extend([dur+128, ptc+256])
12594
+
12595
+ else:
12596
+ score.extend([dtime, dur+128, ptc+256])
12597
+
12598
+ if encode_velocities:
12599
+ score.append(vel+384)
12600
+
12601
+ if dtime != 0:
12602
+ chords_counter += 1
12603
+
12604
+ else:
12605
+ score.extend([dtime, dur+128, ptc+256])
12606
+
12607
+ if encode_velocities:
12608
+ score.append(vel+384)
12609
+
12610
+ if dtime != 0:
12611
+ chords_counter += 1
12612
+
12613
+ notes_counter += 1
12614
+
12615
+ if verbose:
12616
+ print('Done!')
12617
+ print('=' * 70)
12618
+
12619
+ print('Source MIDI composition has', len(zscore), 'notes')
12620
+ print('Source MIDI composition has', len([d[1] for d in dscore if d[1] !=0 ])+1, 'chords')
12621
+ print('-' * 70)
12622
+ print('Encoded sequence has', notes_counter, 'pitches')
12623
+ print('Encoded sequence has', chords_counter, 'chords')
12624
+ print('-' * 70)
12625
+ print('Final encoded sequence has', len(score), 'tokens')
12626
+ print('=' * 70)
12627
+
12628
+ return score
12629
+
12630
+ ###################################################################################
12631
+
12632
+ def equalize_closest_elements_dynamic(seq,
12633
+ min_val=128,
12634
+ max_val=256,
12635
+ splitting_factor=1.5,
12636
+ tightness_threshold=0.15
12637
+ ):
12638
+
12639
+ candidates = [(i, x) for i, x in enumerate(seq) if min_val <= x <= max_val]
12640
+
12641
+ if len(candidates) < 2:
12642
+ return seq.copy()
12643
+
12644
+ sorted_candidates = sorted(candidates, key=lambda pair: pair[1])
12645
+ candidate_values = [val for _, val in sorted_candidates]
12646
+
12647
+ differences = [candidate_values[i+1] - candidate_values[i] for i in range(len(candidate_values)-1)]
12648
+
12649
+ def median(lst):
12650
+
12651
+ n = len(lst)
12652
+ sorted_lst = sorted(lst)
12653
+ mid = n // 2
12654
+
12655
+ if n % 2 == 0:
12656
+ return (sorted_lst[mid - 1] + sorted_lst[mid]) / 2.0
12657
+
12658
+ else:
12659
+ return sorted_lst[mid]
12660
+
12661
+ med_diff = median(differences)
12662
+
12663
+ split_indices = [i for i, diff in enumerate(differences) if diff > splitting_factor * med_diff]
12664
+
12665
+ clusters = []
12666
+
12667
+ if split_indices:
12668
+ start = 0
12669
+ for split_index in split_indices:
12670
+ clusters.append(sorted_candidates[start:split_index+1])
12671
+ start = split_index + 1
12672
+ clusters.append(sorted_candidates[start:])
12673
+
12674
+ else:
12675
+ clusters = [sorted_candidates]
12676
+
12677
+
12678
+ valid_clusters = [cluster for cluster in clusters if len(cluster) >= 2]
12679
+ if not valid_clusters:
12680
+ return seq.copy()
12681
+
12682
+ def cluster_spread(cluster):
12683
+ values = [val for (_, val) in cluster]
12684
+ return max(values) - min(values)
12685
+
12686
+ valid_clusters.sort(key=lambda cluster: (len(cluster), -cluster_spread(cluster)), reverse=True)
12687
+ selected_cluster = valid_clusters[0]
12688
+
12689
+ allowed_range_width = max_val - min_val
12690
+ spread = cluster_spread(selected_cluster)
12691
+ ratio = spread / allowed_range_width
12692
+
12693
+ if ratio > tightness_threshold:
12694
+ return seq.copy()
12695
+
12696
+ cluster_values = [val for (_, val) in selected_cluster]
12697
+ equal_value = sum(cluster_values) // len(cluster_values)
12698
+
12699
+
12700
+ result = list(seq)
12701
+ for idx, _ in selected_cluster:
12702
+ result[idx] = equal_value
12703
+
12704
+ return result
12705
+
12706
+ ###################################################################################
12707
+
12708
+ def chunk_list(lst, chunk_size):
12709
+ return [lst[i:i + chunk_size] for i in range(0, len(lst), chunk_size)]
12710
+
12711
+ ###################################################################################
12712
+
12713
+ def compress_tokens_sequence(seq,
12714
+ min_val=128,
12715
+ max_val=256,
12716
+ group_size=2,
12717
+ splitting_factor=1.5,
12718
+ tightness_threshold=0.15
12719
+ ):
12720
+
12721
+ comp_seq = equalize_closest_elements_dynamic(seq,
12722
+ min_val,
12723
+ max_val,
12724
+ splitting_factor=splitting_factor,
12725
+ tightness_threshold=tightness_threshold
12726
+ )
12727
+
12728
+ seq_split = sorted(chunk_list(comp_seq, group_size), key=lambda x: (-x[0], -x[1]))
12729
+
12730
+ seq_grouped = [[[k]] + [vv[1:] for vv in v] for k, v in groupby(seq_split, key=lambda x: x[0])]
12731
+
12732
+ return flatten(flatten(sorted(seq_grouped, key=lambda x: -x[1][0])))
12733
+
12734
+ ###################################################################################
12735
+
12736
+ def merge_adjacent_pairs(values_counts):
12737
+
12738
+ merged = []
12739
+ i = 0
12740
+
12741
+ while i < len(values_counts):
12742
+
12743
+ if i < len(values_counts) - 1:
12744
+ value1, count1 = values_counts[i]
12745
+ value2, count2 = values_counts[i + 1]
12746
+
12747
+ if value2 - value1 == 1:
12748
+ if count2 > count1:
12749
+ merged_value = value2
12750
+
12751
+ else:
12752
+ merged_value = value1
12753
+
12754
+ merged_count = count1 + count2
12755
+ merged.append((merged_value, merged_count))
12756
+
12757
+ i += 2
12758
+
12759
+ continue
12760
+
12761
+ merged.append(values_counts[i])
12762
+
12763
+ i += 1
12764
+
12765
+ return merged
12766
+
12767
+ ###################################################################################
12768
+
12769
+ def merge_escore_notes_start_times(escore_notes, num_merges=1):
12770
+
12771
+ new_dscore = delta_score_notes(escore_notes)
12772
+
12773
+ times = [e[1] for e in new_dscore if e[1] != 0]
12774
+ times_counts = sorted(Counter(times).most_common())
12775
+
12776
+ prev_counts = []
12777
+ new_times_counts = times_counts
12778
+
12779
+ mcount = 0
12780
+
12781
+ while prev_counts != new_times_counts:
12782
+ prev_counts = new_times_counts
12783
+ new_times_counts = merge_adjacent_pairs(new_times_counts)
12784
+
12785
+ mcount += 1
12786
+
12787
+ if mcount == num_merges:
12788
+ break
12789
+
12790
+ gtimes = [r[0] for r in new_times_counts]
12791
+
12792
+ for e in new_dscore:
12793
+ if e[1] > 0:
12794
+ e[1] = find_closest_value(gtimes, e[1])[0]
12795
+ e[2] -= num_merges
12796
+
12797
+ return delta_score_to_abs_score(new_dscore)
12798
+
12799
+ ###################################################################################
12800
+
12801
+ def multi_instrumental_escore_notes_tokenized(escore_notes, compress_seq=False):
12802
+
12803
+ melody_chords = []
12804
+
12805
+ pe = escore_notes[0]
12806
+
12807
+ for i, e in enumerate(escore_notes):
12808
+
12809
+ dtime = max(0, min(255, e[1]-pe[1]))
12810
+
12811
+ dur = max(0, min(255, e[2]))
12812
+
12813
+ cha = max(0, min(15, e[3]))
12814
+
12815
+ if cha == 9:
12816
+ pat = 128
12817
+
12818
+ else:
12819
+ pat = max(0, min(127, e[6]))
12820
+
12821
+ ptc = max(0, min(127, e[4]))
12822
+
12823
+ vel = max(8, min(127, e[5]))
12824
+ velocity = round(vel / 15)-1
12825
+
12826
+ dur_vel = (8 * dur) + velocity
12827
+ pat_ptc = (129 * pat) + ptc
12828
+
12829
+ if compress_seq:
12830
+ if dtime != 0 or i == 0:
12831
+ melody_chords.extend([dtime, dur_vel+256, pat_ptc+2304])
12832
+
12833
+ else:
12834
+ melody_chords.extend([dur_vel+256, pat_ptc+2304])
12835
+
12836
+ else:
12837
+ melody_chords.extend([dtime, dur_vel+256, pat_ptc+2304])
12838
+
12839
+ pe = e
12840
+
12841
+ return melody_chords
12842
+
12843
+ ###################################################################################
12844
+
12845
+ def merge_counts(data, return_lists=True):
12846
+
12847
+ merged = defaultdict(int)
12848
+
12849
+ for value, count in data:
12850
+ merged[value] += count
12851
+
12852
+ if return_lists:
12853
+ return [[k, v] for k, v in merged.items()]
12854
+
12855
+ else:
12856
+ return list(merged.items())
12857
+
12858
+ ###################################################################################
12859
+
12860
+ def convert_escore_notes_pitches_chords_signature(signature, convert_to_full_chords=True):
12861
+
12862
+ if convert_to_full_chords:
12863
+ SRC_CHORDS = ALL_CHORDS_SORTED
12864
+ TRG_CHORDS = ALL_CHORDS_FULL
12865
+
12866
+ else:
12867
+ SRC_CHORDS = ALL_CHORDS_FULL
12868
+ TRG_CHORDS = ALL_CHORDS_SORTED
12869
+
12870
+ cdiff = len(TRG_CHORDS) - len(SRC_CHORDS)
12871
+
12872
+ pitches_counts = [c for c in signature if -1 < c[0] < 128]
12873
+ chords_counts = [c for c in signature if 127 < c[0] < len(SRC_CHORDS)+128]
12874
+ drums_counts = [[c[0]+cdiff, c[1]] for c in signature if len(SRC_CHORDS)+127 < c[0] < len(SRC_CHORDS)+256]
12875
+ bad_chords_count = [c for c in signature if c[0] == -1]
12876
+
12877
+ new_chords_counts = []
12878
+
12879
+ for c in chords_counts:
12880
+ tones_chord = SRC_CHORDS[c[0]-128]
12881
+
12882
+ if tones_chord not in TRG_CHORDS:
12883
+ tones_chord = check_and_fix_tones_chord(tones_chord, use_full_chords=convert_to_full_chords)
12884
+ bad_chords_count[0][1] += 1
12885
+
12886
+ new_chords_counts.append([TRG_CHORDS.index(tones_chord)+128, c[1]])
12887
+
12888
+ return pitches_counts + merge_counts(new_chords_counts) + drums_counts + bad_chords_count
12889
+
12890
+ ###################################################################################
12891
+
12892
+ def convert_bytes_in_nested_list(lst, encoding='utf-8', errors='ignore'):
12893
+
12894
+ new_list = []
12895
+
12896
+ for item in lst:
12897
+ if isinstance(item, list):
12898
+ new_list.append(convert_bytes_in_nested_list(item))
12899
+
12900
+ elif isinstance(item, bytes):
12901
+ new_list.append(item.decode(encoding, errors=errors))
12902
+
12903
+ else:
12904
+ new_list.append(item)
12905
+
12906
+ return new_list
12907
+
12908
+ ###################################################################################
12909
+
12910
+ print('Module loaded!')
12911
+ print('=' * 70)
12912
+ print('Enjoy! :)')
12913
+ print('=' * 70)
12914
+
12915
  ###################################################################################
12916
  # This is the end of the TMIDI X Python module
12917
  ###################################################################################
fluidsynth-master.zip CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:3df6cfb54c07db465ec9341f672f964deee2c6b089f69b60e138c305a812dd5d
3
- size 1969176
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a9ca64296dc83e6b1294e9eb1e4f1b88a826600009c15aa254f736fe3cb1457f
3
+ size 1979452
monster_search_and_filter.py CHANGED
@@ -54,7 +54,7 @@ r'''############################################################################
54
  # Critical dependencies
55
  #
56
  # !pip install cupy-cuda12x
57
- # !pip install numpy==1.24.4
58
  #
59
  ###################################################################################
60
  ###################################################################################
@@ -1942,7 +1942,9 @@ def search_and_filter(sigs_dicts,
1942
  number_of_top_matches_to_copy = 30,
1943
  transpose_factor=6,
1944
  convert_counts_to_ratios=True,
1945
- omit_drums=True
 
 
1946
  ):
1947
 
1948
  transpose_factor = max(0, min(6, transpose_factor))
@@ -1972,9 +1974,7 @@ def search_and_filter(sigs_dicts,
1972
  trg_sigs = get_MIDI_signature(midi,
1973
  transpose_factor=transpose_factor,
1974
  convert_counts_to_ratios=convert_counts_to_ratios,
1975
- omit_drums=omit_drums,
1976
- mismatch_penalty=10,
1977
- p=3
1978
  )
1979
 
1980
  tv = list(range(tsidx, teidx))
@@ -2025,4 +2025,4 @@ print('=' * 70)
2025
 
2026
  ###################################################################################
2027
  # This is the end of the monster_search_and_filter Python module
2028
- ###################################################################################
 
54
  # Critical dependencies
55
  #
56
  # !pip install cupy-cuda12x
57
+ # !pip install numpy==1.26.4
58
  #
59
  ###################################################################################
60
  ###################################################################################
 
1942
  number_of_top_matches_to_copy = 30,
1943
  transpose_factor=6,
1944
  convert_counts_to_ratios=True,
1945
+ omit_drums=True,
1946
+ mismatch_penalty=10,
1947
+ p=3
1948
  ):
1949
 
1950
  transpose_factor = max(0, min(6, transpose_factor))
 
1974
  trg_sigs = get_MIDI_signature(midi,
1975
  transpose_factor=transpose_factor,
1976
  convert_counts_to_ratios=convert_counts_to_ratios,
1977
+ omit_drums=omit_drums
 
 
1978
  )
1979
 
1980
  tv = list(range(tsidx, teidx))
 
2025
 
2026
  ###################################################################################
2027
  # This is the end of the monster_search_and_filter Python module
2028
+ ###################################################################################