projectlosangeles commited on
Commit
b6bf062
1 Parent(s): 1f97699

Upload 2 files

Browse files
Master_MIDI_Dataset_GPU_Search_and_Filter.ipynb CHANGED
@@ -11,7 +11,7 @@
11
  "id": "SiTIpPjArIyr"
12
  },
13
  "source": [
14
- "# Master MIDI Dataset GPU Search and Filter (ver. 5.0)\n",
15
  "\n",
16
  "***\n",
17
  "\n",
@@ -26,24 +26,10 @@
26
  "***"
27
  ]
28
  },
29
- {
30
- "cell_type": "markdown",
31
- "metadata": {
32
- "gradient": {
33
- "editing": false,
34
- "id": "fa0a611c-1803-42ae-bdf6-a49b5a4e781b",
35
- "kernelId": ""
36
- },
37
- "id": "gOd93yV0sGd2"
38
- },
39
- "source": [
40
- "# (SETUP ENVIRONMENT)"
41
- ]
42
- },
43
  {
44
  "cell_type": "markdown",
45
  "source": [
46
- "# ( GPU CHECK)"
47
  ],
48
  "metadata": {
49
  "id": "0rMwKVc9FFRw"
@@ -161,7 +147,7 @@
161
  "id": "ObPxlEutsQBj"
162
  },
163
  "source": [
164
- "# (PREP MAIN MIDI DATASET)"
165
  ]
166
  },
167
  {
@@ -210,6 +196,15 @@
210
  "execution_count": null,
211
  "outputs": []
212
  },
 
 
 
 
 
 
 
 
 
213
  {
214
  "cell_type": "code",
215
  "source": [
@@ -246,10 +241,19 @@
246
  "execution_count": null,
247
  "outputs": []
248
  },
 
 
 
 
 
 
 
 
 
249
  {
250
  "cell_type": "code",
251
  "source": [
252
- "#@title Load Los Angeles MIDI Dataset Signatures Data\n",
253
  "\n",
254
  "print('=' * 70)\n",
255
  "print('Loading LAMDa Signatures Data...')\n",
@@ -290,22 +294,13 @@
290
  "execution_count": null,
291
  "outputs": []
292
  },
293
- {
294
- "cell_type": "markdown",
295
- "source": [
296
- "# (SEARCH AND FILTER)\n",
297
- "\n",
298
- "### DO NOT FORGET TO UPLOAD YOUR MASTER DATASET TO \"Master-MIDI-Dataset\" FOLDER"
299
- ],
300
- "metadata": {
301
- "id": "iaeqXuIHI0_T"
302
- }
303
- },
304
  {
305
  "cell_type": "code",
306
  "source": [
307
  "#@title Master MIDI Dataset Search and Filter\n",
308
  "\n",
 
 
309
  "#@markdown NOTE: You can stop the search at any time to render partial results\n",
310
  "\n",
311
  "number_of_top_matches_MIDIs_to_collect = 30 #@param {type:\"slider\", min:5, max:50, step:1}\n",
@@ -597,6 +592,338 @@
597
  "execution_count": null,
598
  "outputs": []
599
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
600
  {
601
  "cell_type": "markdown",
602
  "source": [
 
11
  "id": "SiTIpPjArIyr"
12
  },
13
  "source": [
14
+ "# Master MIDI Dataset GPU Search and Filter (ver. 6.0)\n",
15
  "\n",
16
  "***\n",
17
  "\n",
 
26
  "***"
27
  ]
28
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  {
30
  "cell_type": "markdown",
31
  "source": [
32
+ "# (GPU CHECK)"
33
  ],
34
  "metadata": {
35
  "id": "0rMwKVc9FFRw"
 
147
  "id": "ObPxlEutsQBj"
148
  },
149
  "source": [
150
+ "# (DOWNLOAD AND UNZIP MAIN MIDI DATASET)"
151
  ]
152
  },
153
  {
 
196
  "execution_count": null,
197
  "outputs": []
198
  },
199
+ {
200
+ "cell_type": "markdown",
201
+ "source": [
202
+ "# (CREATE MIDI DATASET FILES LIST)"
203
+ ],
204
+ "metadata": {
205
+ "id": "GE0hPlAEjCrs"
206
+ }
207
+ },
208
  {
209
  "cell_type": "code",
210
  "source": [
 
241
  "execution_count": null,
242
  "outputs": []
243
  },
244
+ {
245
+ "cell_type": "markdown",
246
+ "source": [
247
+ "# (SIGNATURES SEARCH)"
248
+ ],
249
+ "metadata": {
250
+ "id": "iaeqXuIHI0_T"
251
+ }
252
+ },
253
  {
254
  "cell_type": "code",
255
  "source": [
256
+ "# @title Load Los Angeles MIDI Dataset Signatures Data\n",
257
  "\n",
258
  "print('=' * 70)\n",
259
  "print('Loading LAMDa Signatures Data...')\n",
 
294
  "execution_count": null,
295
  "outputs": []
296
  },
 
 
 
 
 
 
 
 
 
 
 
297
  {
298
  "cell_type": "code",
299
  "source": [
300
  "#@title Master MIDI Dataset Search and Filter\n",
301
  "\n",
302
+ "#@markdown DO NOT FORGET TO UPLOAD YOUR MASTER DATASET TO \"Master-MIDI-Dataset\" FOLDER\n",
303
+ "\n",
304
  "#@markdown NOTE: You can stop the search at any time to render partial results\n",
305
  "\n",
306
  "number_of_top_matches_MIDIs_to_collect = 30 #@param {type:\"slider\", min:5, max:50, step:1}\n",
 
592
  "execution_count": null,
593
  "outputs": []
594
  },
595
+ {
596
+ "cell_type": "markdown",
597
+ "source": [
598
+ "# (KILO-CHORDS SEARCH)"
599
+ ],
600
+ "metadata": {
601
+ "id": "ekjgrYRaiFE0"
602
+ }
603
+ },
604
+ {
605
+ "cell_type": "code",
606
+ "source": [
607
+ "#@title Load Los Angeles MIDI Dataset Kilo-Chords Data\n",
608
+ "search_matching_type = \"Full-Kilo-Chords\" # @param [\"Full-Kilo-Chords\", \"Unique-Kilo-Chords\"]\n",
609
+ "\n",
610
+ "print('=' * 70)\n",
611
+ "print('Loading LAMDa Kilo-Chords Data...')\n",
612
+ "kilo_chords = pickle.load(open('/content/Main-MIDI-Dataset/KILO_CHORDS_DATA/LAMDa_KILO_CHORDS_DATA.pickle', 'rb'))\n",
613
+ "print('=' * 70)\n",
614
+ "\n",
615
+ "print('Prepping Kilo-Chords...')\n",
616
+ "print('=' * 70)\n",
617
+ "\n",
618
+ "random.shuffle(kilo_chords)\n",
619
+ "\n",
620
+ "if search_matching_type == 'Full-Kilo-Chords':\n",
621
+ "\n",
622
+ " kilo_chords_file_names = []\n",
623
+ "\n",
624
+ " for kc in tqdm(kilo_chords):\n",
625
+ "\n",
626
+ " kilo_chords_file_names.append(kc[0])\n",
627
+ "\n",
628
+ " kcho = kc[1]\n",
629
+ "\n",
630
+ " kcho += [0] * (1000 - len(kcho))\n",
631
+ "\n",
632
+ " print('=' * 70)\n",
633
+ " print('Loading Kilo-Chords...')\n",
634
+ " print('=' * 70)\n",
635
+ "\n",
636
+ " kilo_chords_data = cp.array([kc[1] for kc in kilo_chords])\n",
637
+ "\n",
638
+ "else:\n",
639
+ "\n",
640
+ " kilo_chords_file_names = []\n",
641
+ "\n",
642
+ " kilo_chords_matrixes = [ [0]*(len(TMIDIX.ALL_CHORDS)+128) for i in range(len(kilo_chords))]\n",
643
+ "\n",
644
+ " idx = 0\n",
645
+ " for kc in tqdm(kilo_chords):\n",
646
+ "\n",
647
+ " kilo_chords_file_names.append(kc[0])\n",
648
+ "\n",
649
+ " for c in kc[1]:\n",
650
+ " kilo_chords_matrixes[idx][c] += 1\n",
651
+ "\n",
652
+ " idx += 1\n",
653
+ "\n",
654
+ " print('=' * 70)\n",
655
+ " print('Loading Kilo-Chords...')\n",
656
+ " print('=' * 70)\n",
657
+ "\n",
658
+ " kilo_chords_data = cp.array(kilo_chords_matrixes)\n",
659
+ "\n",
660
+ "print('Done!')\n",
661
+ "print('=' * 70)"
662
+ ],
663
+ "metadata": {
664
+ "cellView": "form",
665
+ "id": "YVyUHQiNiJcX"
666
+ },
667
+ "execution_count": null,
668
+ "outputs": []
669
+ },
670
+ {
671
+ "cell_type": "code",
672
+ "source": [
673
+ "#@title Master MIDI Dataset Search and Filter\n",
674
+ "\n",
675
+ "#@markdown DO NOT FORGET TO UPLOAD YOUR MASTER DATASET TO \"Master-MIDI-Dataset\" FOLDER\n",
676
+ "\n",
677
+ "#@markdown NOTE: You can stop the search at any time to render partial results\n",
678
+ "\n",
679
+ "number_of_top_matches_MIDIs_to_collect = 30 #@param {type:\"slider\", min:5, max:50, step:1}\n",
680
+ "maximum_match_ratio_to_search_for = 1 #@param {type:\"slider\", min:0, max:1, step:0.001}\n",
681
+ "match_results_weight = 1 # @param {type:\"slider\", min:0.1, max:3, step:0.1}\n",
682
+ "match_lengths_weight = 0.5 # @param {type:\"slider\", min:0.1, max:3, step:0.1}\n",
683
+ "match_counts_weight = 0.5 # @param {type:\"slider\", min:0.1, max:3, step:0.1}\n",
684
+ "epsilon = 0.5 # @param {type:\"slider\", min:0.001, max:1, step:0.001}\n",
685
+ "\n",
686
+ "print('=' * 70)\n",
687
+ "print('Master MIDI Dataset GPU Search and Filter')\n",
688
+ "print('=' * 70)\n",
689
+ "\n",
690
+ "###########\n",
691
+ "\n",
692
+ "print('Loading MIDI files...')\n",
693
+ "print('This may take a while on a large dataset in particular.')\n",
694
+ "\n",
695
+ "dataset_addr = \"/content/Master-MIDI-Dataset\"\n",
696
+ "\n",
697
+ "filez = list()\n",
698
+ "\n",
699
+ "for (dirpath, dirnames, filenames) in os.walk(dataset_addr):\n",
700
+ " for file in filenames:\n",
701
+ " if file.endswith(('.mid', '.midi', '.kar')):\n",
702
+ " filez.append(os.path.join(dirpath, file))\n",
703
+ "\n",
704
+ "print('=' * 70)\n",
705
+ "\n",
706
+ "if filez:\n",
707
+ "\n",
708
+ " print('Randomizing file list...')\n",
709
+ " random.shuffle(filez)\n",
710
+ " print('=' * 70)\n",
711
+ "\n",
712
+ " ###################\n",
713
+ "\n",
714
+ " if not os.path.exists('/content/Output-MIDI-Dataset/'+search_matching_type):\n",
715
+ " os.makedirs('/content/Output-MIDI-Dataset/'+search_matching_type)\n",
716
+ "\n",
717
+ " ###################\n",
718
+ "\n",
719
+ " input_files_count = 0\n",
720
+ " files_count = 0\n",
721
+ "\n",
722
+ " for f in filez:\n",
723
+ "\n",
724
+ " try:\n",
725
+ "\n",
726
+ " input_files_count += 1\n",
727
+ "\n",
728
+ " fn = os.path.basename(f)\n",
729
+ " fn1 = os.path.splitext(fn)[0]\n",
730
+ " ext = os.path.splitext(f)[1]\n",
731
+ "\n",
732
+ " print('Processing MIDI File #', files_count+1, 'out of', len(filez))\n",
733
+ " print('MIDI file name', fn)\n",
734
+ " print('-' * 70)\n",
735
+ "\n",
736
+ " #=======================================================\n",
737
+ "\n",
738
+ " raw_score = TMIDIX.midi2single_track_ms_score(open(f, 'rb').read())\n",
739
+ " escore = TMIDIX.advanced_score_processor(raw_score, return_score_analysis=False, return_enhanced_score_notes=True)[0]\n",
740
+ "\n",
741
+ " for e in escore:\n",
742
+ " e[1] = int(e[1] / 16)\n",
743
+ " e[2] = int(e[2] / 16)\n",
744
+ "\n",
745
+ " src_kilo_chords = []\n",
746
+ "\n",
747
+ " for i in range(-6, 6):\n",
748
+ "\n",
749
+ " escore_copy = copy.deepcopy(escore)\n",
750
+ "\n",
751
+ " for e in escore_copy:\n",
752
+ " e[4] += i\n",
753
+ "\n",
754
+ " cscore = TMIDIX.chordify_score([1000, escore_copy])\n",
755
+ "\n",
756
+ " kilo_chord = []\n",
757
+ "\n",
758
+ " for c in cscore:\n",
759
+ "\n",
760
+ " pitches = sorted(set([p[4] for p in c if p[3] != 9]))\n",
761
+ "\n",
762
+ " if pitches:\n",
763
+ " if len(pitches) > 1:\n",
764
+ " tones_chord = sorted(set([p % 12 for p in pitches]))\n",
765
+ " checked_tones_chord = TMIDIX.check_and_fix_tones_chord(tones_chord)\n",
766
+ "\n",
767
+ " chord_token = TMIDIX.ALL_CHORDS.index(checked_tones_chord) + 128\n",
768
+ "\n",
769
+ " elif len(pitches) == 1:\n",
770
+ " chord_token = pitches[0]\n",
771
+ "\n",
772
+ " kilo_chord.append(chord_token)\n",
773
+ "\n",
774
+ " if search_matching_type == 'Full-Kilo-Chords':\n",
775
+ "\n",
776
+ " kilo_chord = kilo_chord[:1000]\n",
777
+ " kilo_chord_matrix = kilo_chord + [0] * (1000 - len(kilo_chord))\n",
778
+ "\n",
779
+ " else:\n",
780
+ "\n",
781
+ " kilo_chord_matrix = [0] * (len(TMIDIX.ALL_CHORDS)+128)\n",
782
+ "\n",
783
+ " for c in kilo_chord:\n",
784
+ " kilo_chord_matrix[c] += 1\n",
785
+ "\n",
786
+ " src_kilo_chords.append(kilo_chord_matrix)\n",
787
+ "\n",
788
+ " src_kilo_chords = cp.stack(cp.array(src_kilo_chords))\n",
789
+ "\n",
790
+ " #=======================================================\n",
791
+ "\n",
792
+ " print('Searching for matches...Please wait...')\n",
793
+ " print('-' * 70)\n",
794
+ "\n",
795
+ " lower_threshold = 0.0\n",
796
+ " upper_threshold = maximum_match_ratio_to_search_for\n",
797
+ " filter_size = number_of_top_matches_MIDIs_to_collect\n",
798
+ "\n",
799
+ " final_ratios = []\n",
800
+ "\n",
801
+ " avg_idxs = []\n",
802
+ "\n",
803
+ " all_filtered_means = []\n",
804
+ " all_filtered_idxs = []\n",
805
+ " all_filtered_tvs = []\n",
806
+ "\n",
807
+ " tv_idx = -6\n",
808
+ "\n",
809
+ " for target_kc in tqdm(src_kilo_chords):\n",
810
+ "\n",
811
+ " comps_lengths = cp.vstack((cp.repeat(cp.sum(target_kc != 0), kilo_chords_data.shape[0]), cp.sum(kilo_chords_data != 0, axis=1)))\n",
812
+ " comps_lengths_ratios = cp.divide(cp.min(comps_lengths, axis=0), cp.max(comps_lengths, axis=0))\n",
813
+ "\n",
814
+ " comps_counts_sums = cp.vstack((cp.repeat(cp.sum(target_kc), kilo_chords_data.shape[0]), cp.sum(kilo_chords_data, axis=1)))\n",
815
+ " comps_counts_sums_ratios = cp.divide(cp.min(comps_counts_sums, axis=0), cp.max(comps_counts_sums, axis=0))\n",
816
+ "\n",
817
+ " intersections = cp.where((kilo_chords_data == target_kc), kilo_chords_data, 0)\n",
818
+ " results = cp.mean(intersections != 0, axis=1)\n",
819
+ "\n",
820
+ " results_weight = match_results_weight\n",
821
+ " comp_lengths_weight = match_lengths_weight\n",
822
+ " comp_counts_sums_weight = match_counts_weight\n",
823
+ "\n",
824
+ " results = cp.divide(cp.add(cp.add(results_weight, comp_lengths_weight), comp_counts_sums_weight), cp.add(cp.add(cp.divide(results_weight, cp.where(results !=0, results, epsilon)), cp.divide(comp_lengths_weight, cp.where(comps_lengths_ratios !=0, comps_lengths_ratios, epsilon))), cp.divide(comp_counts_sums_weight, cp.where(comps_counts_sums_ratios !=0, comps_counts_sums_ratios, epsilon))))\n",
825
+ "\n",
826
+ " unique_means = cp.unique(results)\n",
827
+ " sorted_means = cp.sort(unique_means)[::-1]\n",
828
+ "\n",
829
+ " filtered_means = sorted_means[(sorted_means >= lower_threshold) & (sorted_means <= upper_threshold)][:filter_size]\n",
830
+ "\n",
831
+ " filtered_idxs = cp.where(cp.in1d(results, filtered_means))[0]\n",
832
+ "\n",
833
+ " all_filtered_means.extend(results[cp.in1d(results, filtered_means)].tolist())\n",
834
+ "\n",
835
+ " all_filtered_idxs.extend(filtered_idxs.tolist())\n",
836
+ "\n",
837
+ " filtered_tvs = [tv_idx] * filtered_idxs.shape[0]\n",
838
+ "\n",
839
+ " all_filtered_tvs.extend(filtered_tvs)\n",
840
+ "\n",
841
+ " tv_idx += 1\n",
842
+ "\n",
843
+ " f_results = sorted(zip(all_filtered_means, all_filtered_idxs, all_filtered_tvs), key=lambda x: x[0], reverse=True)\n",
844
+ "\n",
845
+ " triplet_dict = {}\n",
846
+ "\n",
847
+ " for triplet in f_results:\n",
848
+ "\n",
849
+ " if triplet[0] not in triplet_dict:\n",
850
+ " triplet_dict[triplet[0]] = triplet\n",
851
+ " else:\n",
852
+ " if triplet[2] == 0:\n",
853
+ " triplet_dict[triplet[0]] = triplet\n",
854
+ "\n",
855
+ " filtered_results = list(triplet_dict.values())[:filter_size]\n",
856
+ "\n",
857
+ " #=======================================================\n",
858
+ "\n",
859
+ " print('Done!')\n",
860
+ " print('-' * 70)\n",
861
+ " print('Max match ratio:', filtered_results[0][0])\n",
862
+ " print('Max match transpose value:', filtered_results[0][2])\n",
863
+ " print('Max match signature index:', filtered_results[0][1])\n",
864
+ " print('Max match file name:', kilo_chords_file_names[filtered_results[0][1]])\n",
865
+ " print('-' * 70)\n",
866
+ " print('Copying max ratios MIDIs...')\n",
867
+ "\n",
868
+ " for fr in filtered_results:\n",
869
+ "\n",
870
+ " max_ratio_index = fr[1]\n",
871
+ "\n",
872
+ " ffn = kilo_chords_file_names[fr[1]]\n",
873
+ " ffn_idx = [y[0] for y in LAMD_files_list].index(ffn)\n",
874
+ "\n",
875
+ " ff = LAMD_files_list[ffn_idx][1]\n",
876
+ "\n",
877
+ " #=======================================================\n",
878
+ "\n",
879
+ " dir_str = str(fn1)\n",
880
+ " copy_path = '/content/Output-MIDI-Dataset/'+search_matching_type+'/'+dir_str\n",
881
+ " if not os.path.exists(copy_path):\n",
882
+ " os.mkdir(copy_path)\n",
883
+ "\n",
884
+ " fff = str(fr[0] * 100) + '_' + str(fr[2]) + '_' + ffn + '.mid'\n",
885
+ "\n",
886
+ " shutil.copy2(ff, copy_path+'/'+fff)\n",
887
+ "\n",
888
+ " shutil.copy2(f, copy_path+'/'+fn)\n",
889
+ "\n",
890
+ " #======================================================='''\n",
891
+ " print('Done!')\n",
892
+ " print('=' * 70)\n",
893
+ "\n",
894
+ " #=======================================================\n",
895
+ "\n",
896
+ " # Processed files counter\n",
897
+ " files_count += 1\n",
898
+ "\n",
899
+ " except KeyboardInterrupt:\n",
900
+ " print('Quitting...')\n",
901
+ " print('Total number of processed MIDI files', files_count)\n",
902
+ " print('=' * 70)\n",
903
+ " break\n",
904
+ "\n",
905
+ " except Exception as ex:\n",
906
+ " print('WARNING !!!')\n",
907
+ " print('=' * 70)\n",
908
+ " print('Bad file:', f)\n",
909
+ " print('Error detected:', ex)\n",
910
+ " print('=' * 70)\n",
911
+ " continue\n",
912
+ "\n",
913
+ " print('Total number of processed MIDI files', files_count)\n",
914
+ " print('=' * 70)\n",
915
+ "\n",
916
+ "else:\n",
917
+ " print('Could not find any MIDI files. Please check Dataset dir...')\n",
918
+ " print('=' * 70)"
919
+ ],
920
+ "metadata": {
921
+ "cellView": "form",
922
+ "id": "fhgpI31piWiX"
923
+ },
924
+ "execution_count": null,
925
+ "outputs": []
926
+ },
927
  {
928
  "cell_type": "markdown",
929
  "source": [
master_midi_dataset_gpu_search_and_filter.py CHANGED
@@ -6,7 +6,7 @@ Automatically generated by Colaboratory.
6
  Original file is located at
7
  https://colab.research.google.com/github/asigalov61/Los-Angeles-MIDI-Dataset/blob/main/Extras/Master_MIDI_Dataset_GPU_Search_and_Filter.ipynb
8
 
9
- # Master MIDI Dataset GPU Search and Filter (ver. 5.0)
10
 
11
  ***
12
 
@@ -20,9 +20,7 @@ Powered by tegridy-tools: https://github.com/asigalov61/tegridy-tools
20
 
21
  ***
22
 
23
- # (SETUP ENVIRONMENT)
24
-
25
- # ( GPU CHECK)
26
  """
27
 
28
  # @title NVIDIA GPU Check
@@ -79,7 +77,7 @@ if not os.path.exists('/content/Output-MIDI-Dataset'):
79
  print('Done!')
80
  print('Enjoy! :)')
81
 
82
- """# (PREP MAIN MIDI DATASET)"""
83
 
84
  #@title Download Los Angeles MIDI Dataset
85
  print('=' * 70)
@@ -108,6 +106,8 @@ print('Done! Enjoy! :)')
108
  print('=' * 70)
109
  # %cd /content/
110
 
 
 
111
  #@title Create Los Angeles MIDI Dataset files list
112
  print('=' * 70)
113
  print('Creating dataset files list...')
@@ -134,7 +134,9 @@ for f in tqdm(filez):
134
  print('Done!')
135
  print('=' * 70)
136
 
137
- #@title Load Los Angeles MIDI Dataset Signatures Data
 
 
138
 
139
  print('=' * 70)
140
  print('Loading LAMDa Signatures Data...')
@@ -168,13 +170,10 @@ signatures_data = cp.array(sigs_matrixes)
168
  print('Done!')
169
  print('=' * 70)
170
 
171
- """# (SEARCH AND FILTER)
172
-
173
- ### DO NOT FORGET TO UPLOAD YOUR MASTER DATASET TO "Master-MIDI-Dataset" FOLDER
174
- """
175
-
176
  #@title Master MIDI Dataset Search and Filter
177
 
 
 
178
  #@markdown NOTE: You can stop the search at any time to render partial results
179
 
180
  number_of_top_matches_MIDIs_to_collect = 30 #@param {type:"slider", min:5, max:50, step:1}
@@ -459,6 +458,311 @@ else:
459
  print('Could not find any MIDI files. Please check Dataset dir...')
460
  print('=' * 70)
461
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
462
  """# (DOWNLOAD RESULTS)"""
463
 
464
  # Commented out IPython magic to ensure Python compatibility.
 
6
  Original file is located at
7
  https://colab.research.google.com/github/asigalov61/Los-Angeles-MIDI-Dataset/blob/main/Extras/Master_MIDI_Dataset_GPU_Search_and_Filter.ipynb
8
 
9
+ # Master MIDI Dataset GPU Search and Filter (ver. 6.0)
10
 
11
  ***
12
 
 
20
 
21
  ***
22
 
23
+ # (GPU CHECK)
 
 
24
  """
25
 
26
  # @title NVIDIA GPU Check
 
77
  print('Done!')
78
  print('Enjoy! :)')
79
 
80
+ """# (DOWNLOAD AND UNZIP MAIN MIDI DATASET)"""
81
 
82
  #@title Download Los Angeles MIDI Dataset
83
  print('=' * 70)
 
106
  print('=' * 70)
107
  # %cd /content/
108
 
109
+ """# (CREATE MIDI DATASET FILES LIST)"""
110
+
111
  #@title Create Los Angeles MIDI Dataset files list
112
  print('=' * 70)
113
  print('Creating dataset files list...')
 
134
  print('Done!')
135
  print('=' * 70)
136
 
137
+ """# (SIGNATURES SEARCH)"""
138
+
139
+ # @title Load Los Angeles MIDI Dataset Signatures Data
140
 
141
  print('=' * 70)
142
  print('Loading LAMDa Signatures Data...')
 
170
  print('Done!')
171
  print('=' * 70)
172
 
 
 
 
 
 
173
  #@title Master MIDI Dataset Search and Filter
174
 
175
+ #@markdown DO NOT FORGET TO UPLOAD YOUR MASTER DATASET TO "Master-MIDI-Dataset" FOLDER
176
+
177
  #@markdown NOTE: You can stop the search at any time to render partial results
178
 
179
  number_of_top_matches_MIDIs_to_collect = 30 #@param {type:"slider", min:5, max:50, step:1}
 
458
  print('Could not find any MIDI files. Please check Dataset dir...')
459
  print('=' * 70)
460
 
461
+ """# (KILO-CHORDS SEARCH)"""
462
+
463
+ #@title Load Los Angeles MIDI Dataset Kilo-Chords Data
464
+ search_matching_type = "Full-Kilo-Chords" # @param ["Full-Kilo-Chords", "Unique-Kilo-Chords"]
465
+
466
+ print('=' * 70)
467
+ print('Loading LAMDa Kilo-Chords Data...')
468
+ kilo_chords = pickle.load(open('/content/Main-MIDI-Dataset/KILO_CHORDS_DATA/LAMDa_KILO_CHORDS_DATA.pickle', 'rb'))
469
+ print('=' * 70)
470
+
471
+ print('Prepping Kilo-Chords...')
472
+ print('=' * 70)
473
+
474
+ random.shuffle(kilo_chords)
475
+
476
+ if search_matching_type == 'Full-Kilo-Chords':
477
+
478
+ kilo_chords_file_names = []
479
+
480
+ for kc in tqdm(kilo_chords):
481
+
482
+ kilo_chords_file_names.append(kc[0])
483
+
484
+ kcho = kc[1]
485
+
486
+ kcho += [0] * (1000 - len(kcho))
487
+
488
+ print('=' * 70)
489
+ print('Loading Kilo-Chords...')
490
+ print('=' * 70)
491
+
492
+ kilo_chords_data = cp.array([kc[1] for kc in kilo_chords])
493
+
494
+ else:
495
+
496
+ kilo_chords_file_names = []
497
+
498
+ kilo_chords_matrixes = [ [0]*(len(TMIDIX.ALL_CHORDS)+128) for i in range(len(kilo_chords))]
499
+
500
+ idx = 0
501
+ for kc in tqdm(kilo_chords):
502
+
503
+ kilo_chords_file_names.append(kc[0])
504
+
505
+ for c in kc[1]:
506
+ kilo_chords_matrixes[idx][c] += 1
507
+
508
+ idx += 1
509
+
510
+ print('=' * 70)
511
+ print('Loading Kilo-Chords...')
512
+ print('=' * 70)
513
+
514
+ kilo_chords_data = cp.array(kilo_chords_matrixes)
515
+
516
+ print('Done!')
517
+ print('=' * 70)
518
+
519
+ #@title Master MIDI Dataset Search and Filter
520
+
521
+ #@markdown DO NOT FORGET TO UPLOAD YOUR MASTER DATASET TO "Master-MIDI-Dataset" FOLDER
522
+
523
+ #@markdown NOTE: You can stop the search at any time to render partial results
524
+
525
+ number_of_top_matches_MIDIs_to_collect = 30 #@param {type:"slider", min:5, max:50, step:1}
526
+ maximum_match_ratio_to_search_for = 1 #@param {type:"slider", min:0, max:1, step:0.001}
527
+ match_results_weight = 1 # @param {type:"slider", min:0.1, max:3, step:0.1}
528
+ match_lengths_weight = 0.5 # @param {type:"slider", min:0.1, max:3, step:0.1}
529
+ match_counts_weight = 0.5 # @param {type:"slider", min:0.1, max:3, step:0.1}
530
+ epsilon = 0.5 # @param {type:"slider", min:0.001, max:1, step:0.001}
531
+
532
+ print('=' * 70)
533
+ print('Master MIDI Dataset GPU Search and Filter')
534
+ print('=' * 70)
535
+
536
+ ###########
537
+
538
+ print('Loading MIDI files...')
539
+ print('This may take a while on a large dataset in particular.')
540
+
541
+ dataset_addr = "/content/Master-MIDI-Dataset"
542
+
543
+ filez = list()
544
+
545
+ for (dirpath, dirnames, filenames) in os.walk(dataset_addr):
546
+ for file in filenames:
547
+ if file.endswith(('.mid', '.midi', '.kar')):
548
+ filez.append(os.path.join(dirpath, file))
549
+
550
+ print('=' * 70)
551
+
552
+ if filez:
553
+
554
+ print('Randomizing file list...')
555
+ random.shuffle(filez)
556
+ print('=' * 70)
557
+
558
+ ###################
559
+
560
+ if not os.path.exists('/content/Output-MIDI-Dataset/'+search_matching_type):
561
+ os.makedirs('/content/Output-MIDI-Dataset/'+search_matching_type)
562
+
563
+ ###################
564
+
565
+ input_files_count = 0
566
+ files_count = 0
567
+
568
+ for f in filez:
569
+
570
+ try:
571
+
572
+ input_files_count += 1
573
+
574
+ fn = os.path.basename(f)
575
+ fn1 = os.path.splitext(fn)[0]
576
+ ext = os.path.splitext(f)[1]
577
+
578
+ print('Processing MIDI File #', files_count+1, 'out of', len(filez))
579
+ print('MIDI file name', fn)
580
+ print('-' * 70)
581
+
582
+ #=======================================================
583
+
584
+ raw_score = TMIDIX.midi2single_track_ms_score(open(f, 'rb').read())
585
+ escore = TMIDIX.advanced_score_processor(raw_score, return_score_analysis=False, return_enhanced_score_notes=True)[0]
586
+
587
+ for e in escore:
588
+ e[1] = int(e[1] / 16)
589
+ e[2] = int(e[2] / 16)
590
+
591
+ src_kilo_chords = []
592
+
593
+ for i in range(-6, 6):
594
+
595
+ escore_copy = copy.deepcopy(escore)
596
+
597
+ for e in escore_copy:
598
+ e[4] += i
599
+
600
+ cscore = TMIDIX.chordify_score([1000, escore_copy])
601
+
602
+ kilo_chord = []
603
+
604
+ for c in cscore:
605
+
606
+ pitches = sorted(set([p[4] for p in c if p[3] != 9]))
607
+
608
+ if pitches:
609
+ if len(pitches) > 1:
610
+ tones_chord = sorted(set([p % 12 for p in pitches]))
611
+ checked_tones_chord = TMIDIX.check_and_fix_tones_chord(tones_chord)
612
+
613
+ chord_token = TMIDIX.ALL_CHORDS.index(checked_tones_chord) + 128
614
+
615
+ elif len(pitches) == 1:
616
+ chord_token = pitches[0]
617
+
618
+ kilo_chord.append(chord_token)
619
+
620
+ if search_matching_type == 'Full-Kilo-Chords':
621
+
622
+ kilo_chord = kilo_chord[:1000]
623
+ kilo_chord_matrix = kilo_chord + [0] * (1000 - len(kilo_chord))
624
+
625
+ else:
626
+
627
+ kilo_chord_matrix = [0] * (len(TMIDIX.ALL_CHORDS)+128)
628
+
629
+ for c in kilo_chord:
630
+ kilo_chord_matrix[c] += 1
631
+
632
+ src_kilo_chords.append(kilo_chord_matrix)
633
+
634
+ src_kilo_chords = cp.stack(cp.array(src_kilo_chords))
635
+
636
+ #=======================================================
637
+
638
+ print('Searching for matches...Please wait...')
639
+ print('-' * 70)
640
+
641
+ lower_threshold = 0.0
642
+ upper_threshold = maximum_match_ratio_to_search_for
643
+ filter_size = number_of_top_matches_MIDIs_to_collect
644
+
645
+ final_ratios = []
646
+
647
+ avg_idxs = []
648
+
649
+ all_filtered_means = []
650
+ all_filtered_idxs = []
651
+ all_filtered_tvs = []
652
+
653
+ tv_idx = -6
654
+
655
+ for target_kc in tqdm(src_kilo_chords):
656
+
657
+ comps_lengths = cp.vstack((cp.repeat(cp.sum(target_kc != 0), kilo_chords_data.shape[0]), cp.sum(kilo_chords_data != 0, axis=1)))
658
+ comps_lengths_ratios = cp.divide(cp.min(comps_lengths, axis=0), cp.max(comps_lengths, axis=0))
659
+
660
+ comps_counts_sums = cp.vstack((cp.repeat(cp.sum(target_kc), kilo_chords_data.shape[0]), cp.sum(kilo_chords_data, axis=1)))
661
+ comps_counts_sums_ratios = cp.divide(cp.min(comps_counts_sums, axis=0), cp.max(comps_counts_sums, axis=0))
662
+
663
+ intersections = cp.where((kilo_chords_data == target_kc), kilo_chords_data, 0)
664
+ results = cp.mean(intersections != 0, axis=1)
665
+
666
+ results_weight = match_results_weight
667
+ comp_lengths_weight = match_lengths_weight
668
+ comp_counts_sums_weight = match_counts_weight
669
+
670
+ results = cp.divide(cp.add(cp.add(results_weight, comp_lengths_weight), comp_counts_sums_weight), cp.add(cp.add(cp.divide(results_weight, cp.where(results !=0, results, epsilon)), cp.divide(comp_lengths_weight, cp.where(comps_lengths_ratios !=0, comps_lengths_ratios, epsilon))), cp.divide(comp_counts_sums_weight, cp.where(comps_counts_sums_ratios !=0, comps_counts_sums_ratios, epsilon))))
671
+
672
+ unique_means = cp.unique(results)
673
+ sorted_means = cp.sort(unique_means)[::-1]
674
+
675
+ filtered_means = sorted_means[(sorted_means >= lower_threshold) & (sorted_means <= upper_threshold)][:filter_size]
676
+
677
+ filtered_idxs = cp.where(cp.in1d(results, filtered_means))[0]
678
+
679
+ all_filtered_means.extend(results[cp.in1d(results, filtered_means)].tolist())
680
+
681
+ all_filtered_idxs.extend(filtered_idxs.tolist())
682
+
683
+ filtered_tvs = [tv_idx] * filtered_idxs.shape[0]
684
+
685
+ all_filtered_tvs.extend(filtered_tvs)
686
+
687
+ tv_idx += 1
688
+
689
+ f_results = sorted(zip(all_filtered_means, all_filtered_idxs, all_filtered_tvs), key=lambda x: x[0], reverse=True)
690
+
691
+ triplet_dict = {}
692
+
693
+ for triplet in f_results:
694
+
695
+ if triplet[0] not in triplet_dict:
696
+ triplet_dict[triplet[0]] = triplet
697
+ else:
698
+ if triplet[2] == 0:
699
+ triplet_dict[triplet[0]] = triplet
700
+
701
+ filtered_results = list(triplet_dict.values())[:filter_size]
702
+
703
+ #=======================================================
704
+
705
+ print('Done!')
706
+ print('-' * 70)
707
+ print('Max match ratio:', filtered_results[0][0])
708
+ print('Max match transpose value:', filtered_results[0][2])
709
+ print('Max match signature index:', filtered_results[0][1])
710
+ print('Max match file name:', kilo_chords_file_names[filtered_results[0][1]])
711
+ print('-' * 70)
712
+ print('Copying max ratios MIDIs...')
713
+
714
+ for fr in filtered_results:
715
+
716
+ max_ratio_index = fr[1]
717
+
718
+ ffn = kilo_chords_file_names[fr[1]]
719
+ ffn_idx = [y[0] for y in LAMD_files_list].index(ffn)
720
+
721
+ ff = LAMD_files_list[ffn_idx][1]
722
+
723
+ #=======================================================
724
+
725
+ dir_str = str(fn1)
726
+ copy_path = '/content/Output-MIDI-Dataset/'+search_matching_type+'/'+dir_str
727
+ if not os.path.exists(copy_path):
728
+ os.mkdir(copy_path)
729
+
730
+ fff = str(fr[0] * 100) + '_' + str(fr[2]) + '_' + ffn + '.mid'
731
+
732
+ shutil.copy2(ff, copy_path+'/'+fff)
733
+
734
+ shutil.copy2(f, copy_path+'/'+fn)
735
+
736
+ #======================================================='''
737
+ print('Done!')
738
+ print('=' * 70)
739
+
740
+ #=======================================================
741
+
742
+ # Processed files counter
743
+ files_count += 1
744
+
745
+ except KeyboardInterrupt:
746
+ print('Quitting...')
747
+ print('Total number of processed MIDI files', files_count)
748
+ print('=' * 70)
749
+ break
750
+
751
+ except Exception as ex:
752
+ print('WARNING !!!')
753
+ print('=' * 70)
754
+ print('Bad file:', f)
755
+ print('Error detected:', ex)
756
+ print('=' * 70)
757
+ continue
758
+
759
+ print('Total number of processed MIDI files', files_count)
760
+ print('=' * 70)
761
+
762
+ else:
763
+ print('Could not find any MIDI files. Please check Dataset dir...')
764
+ print('=' * 70)
765
+
766
  """# (DOWNLOAD RESULTS)"""
767
 
768
  # Commented out IPython magic to ensure Python compatibility.