projectlosangeles commited on
Commit
b6d498e
1 Parent(s): ae0d7ea

Upload 2 files

Browse files
Los_Angeles_MIDI_Dataset_Search_and_Explore.ipynb CHANGED
@@ -11,7 +11,7 @@
11
  "id": "SiTIpPjArIyr"
12
  },
13
  "source": [
14
- "# Los Angeles MIDI Dataset: Search and Explore (ver. 2.0)\n",
15
  "\n",
16
  "***\n",
17
  "\n",
@@ -107,6 +107,8 @@
107
  "\n",
108
  "from huggingface_hub import hf_hub_download\n",
109
  "\n",
 
 
110
  "os.chdir('/content/')\n",
111
  "print('Done!')"
112
  ]
@@ -597,11 +599,18 @@
597
  "cell_type": "code",
598
  "source": [
599
  "#@title Legacy MIDI Matrixes Search (Slow)\n",
600
- "matching_type = \"minkowski\" #@param {type:\"string\"}\n",
 
 
 
601
  "stop_search_on_exact_match = True #@param {type:\"boolean\"}\n",
 
 
602
  "\n",
603
  "#=================================================================================\n",
604
  "\n",
 
 
605
  "def compress_matrix(midi_matrix):\n",
606
  "\n",
607
  " MX = 38\n",
@@ -701,7 +710,15 @@
701
  " sco= []\n",
702
  " for D in matbatch:\n",
703
  "\n",
704
- " dist = pairwise_distances(matrix, decompress_matrix(D[1]), metric=matching_type)[0][0] \n",
 
 
 
 
 
 
 
 
705
  " sco.append(dist)\n",
706
  "\n",
707
  " return sco\n",
@@ -759,6 +776,7 @@
759
  " print('=' * 70)\n",
760
  " print('Continuing search...')\n",
761
  " print('=' * 70)\n",
 
762
  " except KeyboardInterrupt:\n",
763
  " break\n",
764
  " \n",
@@ -774,6 +792,64 @@
774
  "print('LAMDa File Name:', midi_matrixes[scores.index(min(scores))][0])\n",
775
  "print('=' * 70)\n",
776
  "\n",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
777
  "print('Top 100 matches')\n",
778
  "print('=' * 70)\n",
779
  "\n",
@@ -799,8 +875,13 @@
799
  {
800
  "cell_type": "code",
801
  "source": [
802
- "#@title MIDI Pitches Search\n",
 
 
803
  "\n",
 
 
 
804
  "render_MIDI_to_audio = False #@param {type:\"boolean\"}\n",
805
  "\n",
806
  "print('=' * 70)\n",
@@ -810,12 +891,34 @@
810
  "ratios = []\n",
811
  "\n",
812
  "for d in tqdm(meta_data):\n",
813
- " p_counts = d[1][3][1]\n",
814
  "\n",
815
- " num_same_pitches = len(set([T[0] for T in p_counts]) & set([m[0] for m in pitches_counts]))\n",
816
- " same_pitches_ratio = (num_same_pitches / len(set([m[0] for m in p_counts]+[T[0] for T in pitches_counts])))\n",
 
 
 
 
 
 
 
 
 
 
817
  "\n",
818
- " ratios.append(same_pitches_ratio)\n",
 
 
 
 
 
 
 
 
 
 
 
 
 
819
  "\n",
820
  "max_ratio = max(ratios)\n",
821
  "max_ratio_index = ratios.index(max(ratios))\n",
@@ -889,8 +992,12 @@
889
  {
890
  "cell_type": "code",
891
  "source": [
892
- "#@title MIDI Patches Search\n",
893
  "\n",
 
 
 
 
894
  "render_MIDI_to_audio = False #@param {type:\"boolean\"}\n",
895
  "\n",
896
  "print('=' * 70)\n",
@@ -900,16 +1007,32 @@
900
  "ratios = []\n",
901
  "\n",
902
  "for d in tqdm(meta_data):\n",
903
- " p_list= d[1][4][1]\n",
904
  "\n",
905
- " num_same_patches = len(set(p_list) & set(patches_list))\n",
906
- " \n",
907
- " if len(set(p_list + patches_list)) > 0:\n",
908
- " same_patches_ratio = num_same_patches / len(set(p_list + patches_list))\n",
909
- " else:\n",
910
- " same_patches_ratio = 0\n",
 
 
 
 
911
  "\n",
912
- " ratios.append(same_patches_ratio)\n",
 
 
 
 
 
 
 
 
 
 
 
 
 
913
  "\n",
914
  "max_ratio = max(ratios)\n",
915
  "max_ratio_index = ratios.index(max(ratios))\n",
@@ -984,7 +1107,11 @@
984
  "cell_type": "code",
985
  "source": [
986
  "#@title Metadata Search\n",
 
 
 
987
  "search_query = \"Come To My Window\" #@param {type:\"string\"}\n",
 
988
  "case_sensitive_search = False #@param {type:\"boolean\"}\n",
989
  "\n",
990
  "fields_to_search = ['track_name', \n",
@@ -1003,29 +1130,72 @@
1003
  " ]\n",
1004
  "\n",
1005
  "print('=' * 70)\n",
1006
- "print('Sarching...')\n",
 
 
1007
  "print('=' * 70)\n",
1008
  "\n",
1009
- "for d in tqdm(meta_data):\n",
1010
- " for dd in d[1]:\n",
1011
- " if dd[0] in fields_to_search:\n",
1012
- " if case_sensitive_search:\n",
1013
- " if str(search_query) in str(dd[2]):\n",
1014
- " print('Found!')\n",
1015
- " print('=' * 70)\n",
1016
- " print('Metadata index:', meta_data.index(d))\n",
1017
- " print('MIDI file name:', meta_data[meta_data.index(d)][0])\n",
1018
- " print('Result:', dd[2])\n",
1019
- " print('=' * 70)\n",
1020
- " \n",
1021
- " else:\n",
1022
- " if str(search_query).lower() in str(dd[2]).lower():\n",
1023
- " print('Found!')\n",
1024
- " print('=' * 70)\n",
1025
- " print('Metadata index:', meta_data.index(d))\n",
1026
- " print('MIDI file name:', meta_data[meta_data.index(d)][0])\n",
1027
- " print('Result:', dd[2])\n",
1028
- " print('=' * 70)"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1029
  ],
1030
  "metadata": {
1031
  "cellView": "form",
@@ -1034,6 +1204,188 @@
1034
  "execution_count": null,
1035
  "outputs": []
1036
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1037
  {
1038
  "cell_type": "markdown",
1039
  "source": [
 
11
  "id": "SiTIpPjArIyr"
12
  },
13
  "source": [
14
+ "# Los Angeles MIDI Dataset: Search and Explore (ver. 2.1)\n",
15
  "\n",
16
  "***\n",
17
  "\n",
 
107
  "\n",
108
  "from huggingface_hub import hf_hub_download\n",
109
  "\n",
110
+ "from google.colab import files\n",
111
+ "\n",
112
  "os.chdir('/content/')\n",
113
  "print('Done!')"
114
  ]
 
599
  "cell_type": "code",
600
  "source": [
601
  "#@title Legacy MIDI Matrixes Search (Slow)\n",
602
+ "\n",
603
+ "#@markdown NOTE: You can stop the search at any time to render partial results\n",
604
+ "\n",
605
+ "minimum_match_ratio_to_search_for = 0 #@param {type:\"slider\", min:0, max:500, step:1}\n",
606
  "stop_search_on_exact_match = True #@param {type:\"boolean\"}\n",
607
+ "skip_exact_matches = False #@param {type:\"boolean\"}\n",
608
+ "render_MIDI_to_audio = False #@param {type:\"boolean\"}\n",
609
  "\n",
610
  "#=================================================================================\n",
611
  "\n",
612
+ "matching_type = \"minkowski\"\n",
613
+ "\n",
614
  "def compress_matrix(midi_matrix):\n",
615
  "\n",
616
  " MX = 38\n",
 
710
  " sco= []\n",
711
  " for D in matbatch:\n",
712
  "\n",
713
+ " dist = pairwise_distances(matrix, decompress_matrix(D[1]), metric=matching_type)[0][0]\n",
714
+ "\n",
715
+ " if skip_exact_matches:\n",
716
+ " if dist == 0:\n",
717
+ " dist = 999999\n",
718
+ "\n",
719
+ " if dist <= minimum_match_ratio_to_search_for:\n",
720
+ " dist = 999999\n",
721
+ "\n",
722
  " sco.append(dist)\n",
723
  "\n",
724
  " return sco\n",
 
776
  " print('=' * 70)\n",
777
  " print('Continuing search...')\n",
778
  " print('=' * 70)\n",
779
+ "\n",
780
  " except KeyboardInterrupt:\n",
781
  " break\n",
782
  " \n",
 
792
  "print('LAMDa File Name:', midi_matrixes[scores.index(min(scores))][0])\n",
793
  "print('=' * 70)\n",
794
  "\n",
795
+ "#============================================\n",
796
+ "# MIDI rendering code\n",
797
+ "#============================================\n",
798
+ "\n",
799
+ "print('Rendering source MIDI...')\n",
800
+ "print('=' * 70)\n",
801
+ "\n",
802
+ "fn = midi_matrixes[scores.index(min(scores))][0]\n",
803
+ "\n",
804
+ "try:\n",
805
+ " fn_idx = [y[0] for y in LAMD_files_list].index(fn)\n",
806
+ "\n",
807
+ " f = LAMD_files_list[fn_idx][1]\n",
808
+ "\n",
809
+ " ms_score = MIDI.midi2ms_score(open(f, 'rb').read())\n",
810
+ "\n",
811
+ " itrack = 1\n",
812
+ " song_f = []\n",
813
+ "\n",
814
+ " while itrack < len(ms_score):\n",
815
+ " for event in ms_score[itrack]: \n",
816
+ " if event[0] == 'note':\n",
817
+ " song_f.append(event)\n",
818
+ " itrack += 1\n",
819
+ "\n",
820
+ " song_f.sort(key=lambda x: x[1])\n",
821
+ "\n",
822
+ " fname = f.split('.mid')[0]\n",
823
+ "\n",
824
+ " x = []\n",
825
+ " y =[]\n",
826
+ " c = []\n",
827
+ "\n",
828
+ " colors = ['red', 'yellow', 'green', 'cyan', 'blue', 'pink', 'orange', 'purple', 'gray', 'white', 'gold', 'silver', 'aqua', 'azure', 'bisque', 'coral']\n",
829
+ "\n",
830
+ " for s in song_f:\n",
831
+ " x.append(s[1] / 1000)\n",
832
+ " y.append(s[4])\n",
833
+ " c.append(colors[s[3]])\n",
834
+ "\n",
835
+ " if render_MIDI_to_audio:\n",
836
+ " FluidSynth(\"/usr/share/sounds/sf2/FluidR3_GM.sf2\", 16000).midi_to_audio(str(fname + '.mid'), str(fname + '.wav'))\n",
837
+ " display(Audio(str(fname + '.wav'), rate=16000))\n",
838
+ "\n",
839
+ " plt.figure(figsize=(14,5))\n",
840
+ " ax=plt.axes(title=fname)\n",
841
+ " ax.set_facecolor('black')\n",
842
+ "\n",
843
+ " plt.scatter(x,y, c=c)\n",
844
+ " plt.xlabel(\"Time\")\n",
845
+ " plt.ylabel(\"Pitch\")\n",
846
+ " plt.show()\n",
847
+ "\n",
848
+ "except:\n",
849
+ " pass\n",
850
+ "\n",
851
+ "#============================================\n",
852
+ "\n",
853
  "print('Top 100 matches')\n",
854
  "print('=' * 70)\n",
855
  "\n",
 
875
  {
876
  "cell_type": "code",
877
  "source": [
878
+ "#@title MIDI Pitches Search (Fast)\n",
879
+ "\n",
880
+ "#@markdown NOTE: You can stop the search at any time to render partial results\n",
881
  "\n",
882
+ "maximum_match_ratio_to_search_for = 1 #@param {type:\"slider\", min:0, max:1, step:0.01}\n",
883
+ "pitches_counts_cutoff_threshold_ratio = 0.2 #@param {type:\"slider\", min:0, max:1, step:0.05}\n",
884
+ "skip_exact_matches = False #@param {type:\"boolean\"}\n",
885
  "render_MIDI_to_audio = False #@param {type:\"boolean\"}\n",
886
  "\n",
887
  "print('=' * 70)\n",
 
891
  "ratios = []\n",
892
  "\n",
893
  "for d in tqdm(meta_data):\n",
 
894
  "\n",
895
+ " try:\n",
896
+ " p_counts = d[1][3][1]\n",
897
+ " p_counts.sort(reverse = True, key = lambda x: x[1])\n",
898
+ " max_p_count = p_counts[1][0]\n",
899
+ " trimmed_p_counts = [y for y in p_counts if y[1] >= (max_p_count * pitches_counts_cutoff_threshold_ratio)] \n",
900
+ "\n",
901
+ " pitches_counts.sort(reverse = True, key = lambda x: x[1])\n",
902
+ " max_pitches_count = pitches_counts[1][0]\n",
903
+ " trimmed_pitches_counts = [y for y in pitches_counts if y[1] >= (max_pitches_count * pitches_counts_cutoff_threshold_ratio)] \n",
904
+ "\n",
905
+ " num_same_pitches = len(set([T[0] for T in trimmed_p_counts]) & set([m[0] for m in trimmed_pitches_counts]))\n",
906
+ " same_pitches_ratio = (num_same_pitches / len(set([m[0] for m in trimmed_p_counts]+[T[0] for T in trimmed_pitches_counts])))\n",
907
  "\n",
908
+ " if skip_exact_matches:\n",
909
+ " if same_pitches_ratio == 1:\n",
910
+ " same_pitches_ratio = 0\n",
911
+ "\n",
912
+ " if same_pitches_ratio > maximum_match_ratio_to_search_for:\n",
913
+ " same_pitches_ratio = 0\n",
914
+ " \n",
915
+ " ratios.append(same_pitches_ratio)\n",
916
+ " \n",
917
+ " except KeyboardInterrupt:\n",
918
+ " break\n",
919
+ " \n",
920
+ " except:\n",
921
+ " break\n",
922
  "\n",
923
  "max_ratio = max(ratios)\n",
924
  "max_ratio_index = ratios.index(max(ratios))\n",
 
992
  {
993
  "cell_type": "code",
994
  "source": [
995
+ "#@title MIDI Patches Search (Fast)\n",
996
  "\n",
997
+ "#@markdown NOTE: You can stop the search at any time to render partial results\n",
998
+ "\n",
999
+ "maximum_match_ratio_to_search_for = 1 #@param {type:\"slider\", min:0, max:1, step:0.01}\n",
1000
+ "skip_exact_matches = False #@param {type:\"boolean\"}\n",
1001
  "render_MIDI_to_audio = False #@param {type:\"boolean\"}\n",
1002
  "\n",
1003
  "print('=' * 70)\n",
 
1007
  "ratios = []\n",
1008
  "\n",
1009
  "for d in tqdm(meta_data):\n",
 
1010
  "\n",
1011
+ " try:\n",
1012
+ "\n",
1013
+ " p_list= d[1][4][1]\n",
1014
+ "\n",
1015
+ " num_same_patches = len(set(p_list) & set(patches_list))\n",
1016
+ " \n",
1017
+ " if len(set(p_list + patches_list)) > 0:\n",
1018
+ " same_patches_ratio = num_same_patches / len(set(p_list + patches_list))\n",
1019
+ " else:\n",
1020
+ " same_patches_ratio = 0\n",
1021
  "\n",
1022
+ " if skip_exact_matches:\n",
1023
+ " if same_patches_ratio == 1:\n",
1024
+ " same_patches_ratio = 0\n",
1025
+ "\n",
1026
+ " if same_patches_ratio > maximum_match_ratio_to_search_for:\n",
1027
+ " same_patches_ratio = 0\n",
1028
+ " \n",
1029
+ " ratios.append(same_patches_ratio)\n",
1030
+ " \n",
1031
+ " except KeyboardInterrupt:\n",
1032
+ " break\n",
1033
+ " \n",
1034
+ " except:\n",
1035
+ " break\n",
1036
  "\n",
1037
  "max_ratio = max(ratios)\n",
1038
  "max_ratio_index = ratios.index(max(ratios))\n",
 
1107
  "cell_type": "code",
1108
  "source": [
1109
  "#@title Metadata Search\n",
1110
+ "\n",
1111
+ "#@markdown You can search the metadata by search query or by MIDI md5 hash file name\n",
1112
+ "\n",
1113
  "search_query = \"Come To My Window\" #@param {type:\"string\"}\n",
1114
+ "md5_hash_MIDI_file_name = \"d9a7e1c6a375b8e560155a5977fc10f8\" #@param {type:\"string\"}\n",
1115
  "case_sensitive_search = False #@param {type:\"boolean\"}\n",
1116
  "\n",
1117
  "fields_to_search = ['track_name', \n",
 
1130
  " ]\n",
1131
  "\n",
1132
  "print('=' * 70)\n",
1133
+ "print('Los Angeles MIDI Dataset Metadata Search')\n",
1134
+ "print('=' * 70)\n",
1135
+ "print('Searching...')\n",
1136
  "print('=' * 70)\n",
1137
  "\n",
1138
+ "if md5_hash_MIDI_file_name != '':\n",
1139
+ " for d in tqdm(meta_data):\n",
1140
+ " try:\n",
1141
+ " if d[0] == md5_hash_MIDI_file_name:\n",
1142
+ " print('Found!')\n",
1143
+ " print('=' * 70)\n",
1144
+ " print('Metadata index:', meta_data.index(d))\n",
1145
+ " print('MIDI file name:', meta_data[meta_data.index(d)][0])\n",
1146
+ " print('Result:', d[1])\n",
1147
+ " print('=' * 70)\n",
1148
+ " break\n",
1149
+ " \n",
1150
+ " except KeyboardInterrupt:\n",
1151
+ " print('Ending search...')\n",
1152
+ " print('=' * 70)\n",
1153
+ " break\n",
1154
+ " \n",
1155
+ " except:\n",
1156
+ " print('Ending search...')\n",
1157
+ " print('=' * 70)\n",
1158
+ " break\n",
1159
+ "\n",
1160
+ " if d[0] != md5_hash_MIDI_file_name:\n",
1161
+ " print('Not found!')\n",
1162
+ " print('=' * 70)\n",
1163
+ " print('md5 hash was not found!')\n",
1164
+ " print('Ending search...')\n",
1165
+ " print('=' * 70)\n",
1166
+ "\n",
1167
+ "else:\n",
1168
+ " for d in tqdm(meta_data):\n",
1169
+ " try:\n",
1170
+ " for dd in d[1]:\n",
1171
+ " if dd[0] in fields_to_search:\n",
1172
+ " if case_sensitive_search:\n",
1173
+ " if str(search_query) in str(dd[2]):\n",
1174
+ " print('Found!')\n",
1175
+ " print('=' * 70)\n",
1176
+ " print('Metadata index:', meta_data.index(d))\n",
1177
+ " print('MIDI file name:', meta_data[meta_data.index(d)][0])\n",
1178
+ " print('Result:', dd[2])\n",
1179
+ " print('=' * 70)\n",
1180
+ " \n",
1181
+ " else:\n",
1182
+ " if str(search_query).lower() in str(dd[2]).lower():\n",
1183
+ " print('Found!')\n",
1184
+ " print('=' * 70)\n",
1185
+ " print('Metadata index:', meta_data.index(d))\n",
1186
+ " print('MIDI file name:', meta_data[meta_data.index(d)][0])\n",
1187
+ " print('Result:', dd[2])\n",
1188
+ " print('=' * 70)\n",
1189
+ " \n",
1190
+ " except KeyboardInterrupt:\n",
1191
+ " print('Ending search...')\n",
1192
+ " print('=' * 70)\n",
1193
+ " break\n",
1194
+ " \n",
1195
+ " except:\n",
1196
+ " print('Ending search...')\n",
1197
+ " print('=' * 70)\n",
1198
+ " break"
1199
  ],
1200
  "metadata": {
1201
  "cellView": "form",
 
1204
  "execution_count": null,
1205
  "outputs": []
1206
  },
1207
+ {
1208
+ "cell_type": "markdown",
1209
+ "source": [
1210
+ "# (MIDI FILE PLAYER)"
1211
+ ],
1212
+ "metadata": {
1213
+ "id": "ih7bAzjv2amL"
1214
+ }
1215
+ },
1216
+ {
1217
+ "cell_type": "code",
1218
+ "source": [
1219
+ "#@title MIDI file player\n",
1220
+ "\n",
1221
+ "#@markdown NOTE: You can use md5 hash file name or full MIDI file path to play it\n",
1222
+ "\n",
1223
+ "md5_hash_MIDI_file_name = \"d9a7e1c6a375b8e560155a5977fc10f8\" #@param {type:\"string\"}\n",
1224
+ "full_path_to_MIDI = \"/content/Los-Angeles-MIDI-Dataset/Come-To-My-Window-Modified-Sample-MIDI.mid\" #@param {type:\"string\"}\n",
1225
+ "render_MIDI_to_audio = False #@param {type:\"boolean\"}\n",
1226
+ "\n",
1227
+ "#============================================\n",
1228
+ "# MIDI rendering code\n",
1229
+ "#============================================\n",
1230
+ "\n",
1231
+ "print('=' * 70)\n",
1232
+ "print('MIDI file player')\n",
1233
+ "print('=' * 70)\n",
1234
+ "\n",
1235
+ "try:\n",
1236
+ "\n",
1237
+ " if os.path.exists(full_path_to_MIDI):\n",
1238
+ " f = full_path_to_MIDI\n",
1239
+ " print('Using full path to MIDI')\n",
1240
+ "\n",
1241
+ " else:\n",
1242
+ " fn = md5_hash_MIDI_file_name\n",
1243
+ " fn_idx = [y[0] for y in LAMD_files_list].index(fn)\n",
1244
+ " f = LAMD_files_list[fn_idx][1]\n",
1245
+ " \n",
1246
+ " print('Using md5 hash filename')\n",
1247
+ " \n",
1248
+ " print('=' * 70)\n",
1249
+ " print('Rendering MIDI...')\n",
1250
+ " print('=' * 70)\n",
1251
+ "\n",
1252
+ " ms_score = MIDI.midi2ms_score(open(f, 'rb').read())\n",
1253
+ "\n",
1254
+ " itrack = 1\n",
1255
+ " song_f = []\n",
1256
+ "\n",
1257
+ " while itrack < len(ms_score):\n",
1258
+ " for event in ms_score[itrack]: \n",
1259
+ " if event[0] == 'note':\n",
1260
+ " song_f.append(event)\n",
1261
+ " itrack += 1\n",
1262
+ "\n",
1263
+ " song_f.sort(key=lambda x: x[1])\n",
1264
+ "\n",
1265
+ " fname = f.split('.mid')[0]\n",
1266
+ "\n",
1267
+ " x = []\n",
1268
+ " y =[]\n",
1269
+ " c = []\n",
1270
+ "\n",
1271
+ " colors = ['red', 'yellow', 'green', 'cyan', 'blue', 'pink', 'orange', 'purple', 'gray', 'white', 'gold', 'silver', 'aqua', 'azure', 'bisque', 'coral']\n",
1272
+ "\n",
1273
+ " for s in song_f:\n",
1274
+ " x.append(s[1] / 1000)\n",
1275
+ " y.append(s[4])\n",
1276
+ " c.append(colors[s[3]])\n",
1277
+ "\n",
1278
+ " if render_MIDI_to_audio:\n",
1279
+ " FluidSynth(\"/usr/share/sounds/sf2/FluidR3_GM.sf2\", 16000).midi_to_audio(str(fname + '.mid'), str(fname + '.wav'))\n",
1280
+ " display(Audio(str(fname + '.wav'), rate=16000))\n",
1281
+ "\n",
1282
+ " plt.figure(figsize=(14,5))\n",
1283
+ " ax=plt.axes(title=fname)\n",
1284
+ " ax.set_facecolor('black')\n",
1285
+ "\n",
1286
+ " plt.scatter(x,y, c=c)\n",
1287
+ " plt.xlabel(\"Time\")\n",
1288
+ " plt.ylabel(\"Pitch\")\n",
1289
+ " plt.show()\n",
1290
+ "\n",
1291
+ "except:\n",
1292
+ " print('File not found!!!')\n",
1293
+ " print('Check the filename!')\n",
1294
+ " print('=' * 70)"
1295
+ ],
1296
+ "metadata": {
1297
+ "cellView": "form",
1298
+ "id": "rfnp7dQw2egM"
1299
+ },
1300
+ "execution_count": null,
1301
+ "outputs": []
1302
+ },
1303
+ {
1304
+ "cell_type": "markdown",
1305
+ "source": [
1306
+ "# (COLAB MIDI FILES LOCATOR/DOWNLOADER)"
1307
+ ],
1308
+ "metadata": {
1309
+ "id": "pk1Wf3SfARmy"
1310
+ }
1311
+ },
1312
+ {
1313
+ "cell_type": "code",
1314
+ "source": [
1315
+ "#@title Loacate and/or download desired MIDI files by MIDI md5 hash file names\n",
1316
+ "\n",
1317
+ "MIDI_md5_hash_file_name_1 = \"d9a7e1c6a375b8e560155a5977fc10f8\" #@param {type:\"string\"}\n",
1318
+ "MIDI_md5_hash_file_name_2 = \"\" #@param {type:\"string\"}\n",
1319
+ "MIDI_md5_hash_file_name_3 = \"\" #@param {type:\"string\"}\n",
1320
+ "MIDI_md5_hash_file_name_4 = \"\" #@param {type:\"string\"}\n",
1321
+ "MIDI_md5_hash_file_name_5 = \"\" #@param {type:\"string\"}\n",
1322
+ "download_located_files = False #@param {type:\"boolean\"}\n",
1323
+ "\n",
1324
+ "print('=' * 70)\n",
1325
+ "print('MIDI files locator and downloader')\n",
1326
+ "print('=' * 70)\n",
1327
+ "\n",
1328
+ "md5_list = []\n",
1329
+ "\n",
1330
+ "if MIDI_md5_hash_file_name_1 != '':\n",
1331
+ " md5_list.append(MIDI_md5_hash_file_name_1)\n",
1332
+ "\n",
1333
+ "if MIDI_md5_hash_file_name_2 != '':\n",
1334
+ " md5_list.append(MIDI_md5_hash_file_name_2)\n",
1335
+ "\n",
1336
+ "if MIDI_md5_hash_file_name_3 != '':\n",
1337
+ " md5_list.append(MIDI_md5_hash_file_name_3)\n",
1338
+ "\n",
1339
+ "if MIDI_md5_hash_file_name_4 != '':\n",
1340
+ " md5_list.append(MIDI_md5_hash_file_name_4)\n",
1341
+ "\n",
1342
+ "if MIDI_md5_hash_file_name_5 != '':\n",
1343
+ " md5_list.append(MIDI_md5_hash_file_name_5)\n",
1344
+ "\n",
1345
+ "if len(md5_list) > 0:\n",
1346
+ " for m in md5_list:\n",
1347
+ " try:\n",
1348
+ "\n",
1349
+ " fn = m\n",
1350
+ " fn_idx = [y[0] for y in LAMD_files_list].index(fn)\n",
1351
+ " f = LAMD_files_list[fn_idx][1]\n",
1352
+ "\n",
1353
+ " print('Found md5 hash file name', m)\n",
1354
+ "\n",
1355
+ " location_str = ''\n",
1356
+ "\n",
1357
+ " fl = f.split('/')\n",
1358
+ " for fa in fl[:-1]:\n",
1359
+ " if fa != '' and fa != 'content':\n",
1360
+ " location_str += '/'\n",
1361
+ " location_str += str(fa)\n",
1362
+ "\n",
1363
+ " print('Colab location/folder', location_str)\n",
1364
+ "\n",
1365
+ " if download_located_files:\n",
1366
+ " print('Downloading MIDI file', str(m) + '.mid')\n",
1367
+ " files.download(f)\n",
1368
+ "\n",
1369
+ " print('=' * 70)\n",
1370
+ "\n",
1371
+ " except:\n",
1372
+ " print('md5 hash file name', m, 'not found!!!')\n",
1373
+ " print('Check the file name!')\n",
1374
+ " print('=' * 70)\n",
1375
+ " continue\n",
1376
+ "\n",
1377
+ "else:\n",
1378
+ " print('No md5 hash file names were specified!')\n",
1379
+ " print('Check input!')\n",
1380
+ " print('=' * 70)\n"
1381
+ ],
1382
+ "metadata": {
1383
+ "cellView": "form",
1384
+ "id": "MCehs2qxAaOl"
1385
+ },
1386
+ "execution_count": null,
1387
+ "outputs": []
1388
+ },
1389
  {
1390
  "cell_type": "markdown",
1391
  "source": [
los_angeles_midi_dataset_search_and_explore.py ADDED
@@ -0,0 +1,1273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Los_Angeles_MIDI_Dataset_Search_and_Explore.ipynb
3
+
4
+ Automatically generated by Colaboratory.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/github/asigalov61/Los-Angeles-MIDI-Dataset/blob/main/Los_Angeles_MIDI_Dataset_Search_and_Explore.ipynb
8
+
9
+ # Los Angeles MIDI Dataset: Search and Explore (ver. 2.1)
10
+
11
+ ***
12
+
13
+ Powered by tegridy-tools: https://github.com/asigalov61/tegridy-tools
14
+
15
+ ***
16
+
17
+ #### Project Los Angeles
18
+
19
+ #### Tegridy Code 2023
20
+
21
+ ***
22
+
23
+ # (SETUP ENVIRONMENT)
24
+ """
25
+
26
+ #@title Install all dependencies (run only once per session)
27
+ !git clone --depth 1 https://github.com/asigalov61/Los-Angeles-MIDI-Dataset
28
+ !pip install huggingface_hub
29
+ !pip install matplotlib
30
+ !pip install sklearn
31
+ !pip install tqdm
32
+ !apt install fluidsynth #Pip does not work for some reason. Only apt works
33
+ !pip install midi2audio
34
+
35
+ #@title Import all needed modules
36
+
37
+ print('Loading core modules...')
38
+ import os
39
+ import copy
40
+ from collections import Counter
41
+ import random
42
+ import pickle
43
+ from tqdm import tqdm
44
+
45
+ from joblib import Parallel, delayed
46
+ import multiprocessing
47
+
48
+ if not os.path.exists('/content/LAMD'):
49
+ os.makedirs('/content/LAMD')
50
+
51
+ print('Loading MIDI.py module...')
52
+ os.chdir('/content/Los-Angeles-MIDI-Dataset')
53
+ import MIDI
54
+
55
+ print('Loading aux modules...')
56
+ from sklearn.metrics import pairwise_distances, pairwise
57
+ import matplotlib.pyplot as plt
58
+
59
+ from midi2audio import FluidSynth
60
+ from IPython.display import Audio, display
61
+
62
+ from huggingface_hub import hf_hub_download
63
+
64
+ from google.colab import files
65
+
66
+ os.chdir('/content/')
67
+ print('Done!')
68
+
69
+ """# (PREP DATA)"""
70
+
71
+ # Commented out IPython magic to ensure Python compatibility.
72
+ #@title Unzip LAMDa data
73
+ # %cd /content/Los-Angeles-MIDI-Dataset/META-DATA
74
+
75
+ print('=' * 70)
76
+ print('Unzipping META-DATA...Please wait...')
77
+
78
+ !cat LAMDa_META_DATA.zip* > LAMDa_META_DATA.zip
79
+ print('=' * 70)
80
+
81
+ !unzip -j LAMDa_META_DATA.zip
82
+ print('=' * 70)
83
+
84
+ print('Done! Enjoy! :)')
85
+ print('=' * 70)
86
+ # %cd /content/
87
+
88
+ #================================================
89
+
90
+ # %cd /content/Los-Angeles-MIDI-Dataset/MIDI-MATRIXES
91
+
92
+ print('=' * 70)
93
+ print('Unzipping MIDI-MATRIXES...Please wait...')
94
+
95
+ !cat LAMDa_MIDI_MATRIXES.zip* > LAMDa_MIDI_MATRIXES.zip
96
+ print('=' * 70)
97
+
98
+ !unzip -j LAMDa_MIDI_MATRIXES.zip
99
+ print('=' * 70)
100
+
101
+ print('Done! Enjoy! :)')
102
+ print('=' * 70)
103
+ # %cd /content/
104
+
105
+ #==================================================
106
+
107
+ # %cd /content/Los-Angeles-MIDI-Dataset/TOTALS
108
+
109
+ print('=' * 70)
110
+ print('Unzipping TOTALS...Please wait...')
111
+
112
+ !unzip -j LAMDa_TOTALS.zip
113
+ print('=' * 70)
114
+
115
+ print('Done! Enjoy! :)')
116
+ print('=' * 70)
117
+ # %cd /content/
118
+
119
+ #@title Load LAMDa data
120
+ print('=' * 70)
121
+ print('Loading LAMDa data...Please wait...')
122
+ print('=' * 70)
123
+ print('Loading LAMDa META-DATA...')
124
+ meta_data = pickle.load(open('/content/Los-Angeles-MIDI-Dataset/META-DATA/LAMDa_META_DATA.pickle', 'rb'))
125
+ print('Done!')
126
+ print('=' * 70)
127
+ print('Loading LAMDa MIDI-MATRIXES...')
128
+ midi_matrixes = pickle.load(open('/content/Los-Angeles-MIDI-Dataset/MIDI-MATRIXES/LAMDa_MIDI_MATRIXES.pickle', 'rb'))
129
+ print('Done!')
130
+ print('=' * 70)
131
+ print('Loading LAMDa TOTALS...')
132
+ totals = pickle.load(open('/content/Los-Angeles-MIDI-Dataset/TOTALS/LAMDa_TOTALS.pickle', 'rb'))
133
+ print('Done!')
134
+ print('=' * 70)
135
+ print('Enjoy!')
136
+ print('=' * 70)
137
+
138
+ """# (PREP MIDI DATASET)"""
139
+
140
+ #@title Download the dataset
141
+ print('=' * 70)
142
+ print('Downloading Los Angeles MIDI Dataset...Please wait...')
143
+ print('=' * 70)
144
+
145
+ hf_hub_download(repo_id='projectlosangeles/Los-Angeles-MIDI-Dataset',
146
+ filename='Los-Angeles-MIDI-Dataset-Ver-2-0-CC-BY-NC-SA.zip',
147
+ repo_type="dataset",
148
+ local_dir='/content/LAMD',
149
+ local_dir_use_symlinks=False)
150
+ print('=' * 70)
151
+ print('Done! Enjoy! :)')
152
+ print('=' * 70)
153
+
154
+ # Commented out IPython magic to ensure Python compatibility.
155
+ #@title Unzip the dataset
156
+ # %cd /content/LAMD
157
+
158
+ print('=' * 70)
159
+ print('Unzipping Los Angeles MIDI Dataset...Please wait...')
160
+ !unzip 'Los-Angeles-MIDI-Dataset-Ver-2-0-CC-BY-NC-SA.zip'
161
+ print('=' * 70)
162
+
163
+ print('Done! Enjoy! :)')
164
+ print('=' * 70)
165
+ # %cd /content/
166
+
167
+ #@title Create dataset files list
168
+ print('=' * 70)
169
+ print('Creating dataset files list...')
170
+ dataset_addr = "/content/LAMD/MIDIs"
171
+
172
+ # os.chdir(dataset_addr)
173
+ filez = list()
174
+ for (dirpath, dirnames, filenames) in os.walk(dataset_addr):
175
+ filez += [os.path.join(dirpath, file) for file in filenames]
176
+
177
+ if filez == []:
178
+ print('Could not find any MIDI files. Please check Dataset dir...')
179
+ print('=' * 70)
180
+
181
+ print('=' * 70)
182
+ print('Randomizing file list...')
183
+ random.shuffle(filez)
184
+ print('=' * 70)
185
+
186
+ LAMD_files_list = []
187
+
188
+ for f in tqdm(filez):
189
+ LAMD_files_list.append([f.split('/')[-1].split('.mid')[0], f])
190
+ print('Done!')
191
+ print('=' * 70)
192
+
193
+ """# (PLOT TOTALS)"""
194
+
195
+ #@title Plot Totals
196
+
197
+ cos_sim = pairwise.cosine_similarity(
198
+ totals[0][0][4]
199
+ )
200
+ plt.figure(figsize=(8, 8))
201
+ plt.imshow(cos_sim, cmap="inferno", interpolation="none")
202
+ im_ratio = 1
203
+ plt.colorbar(fraction=0.046 * im_ratio, pad=0.04)
204
+ plt.title('Times')
205
+ plt.xlabel("Position")
206
+ plt.ylabel("Position")
207
+ plt.tight_layout()
208
+ plt.plot()
209
+
210
+ cos_sim = pairwise.cosine_similarity(
211
+ totals[0][0][5]
212
+ )
213
+ plt.figure(figsize=(8, 8))
214
+ plt.imshow(cos_sim, cmap="inferno", interpolation="none")
215
+ im_ratio = 1
216
+ plt.colorbar(fraction=0.046 * im_ratio, pad=0.04)
217
+ plt.title('Durations')
218
+ plt.xlabel("Position")
219
+ plt.ylabel("Position")
220
+ plt.tight_layout()
221
+ plt.plot()
222
+
223
+ cos_sim = pairwise.cosine_similarity(
224
+ totals[0][0][6]
225
+ )
226
+ plt.figure(figsize=(8, 8))
227
+ plt.imshow(cos_sim, cmap="inferno", interpolation="none")
228
+ im_ratio = 1
229
+ plt.colorbar(fraction=0.046 * im_ratio, pad=0.04)
230
+ plt.title('Channels')
231
+ plt.xlabel("Position")
232
+ plt.ylabel("Position")
233
+ plt.tight_layout()
234
+ plt.plot()
235
+
236
+ cos_sim = pairwise.cosine_similarity(
237
+ totals[0][0][7]
238
+ )
239
+ plt.figure(figsize=(8, 8))
240
+ plt.imshow(cos_sim, cmap="inferno", interpolation="none")
241
+ im_ratio = 1
242
+ plt.colorbar(fraction=0.046 * im_ratio, pad=0.04)
243
+ plt.title('Instruments')
244
+ plt.xlabel("Position")
245
+ plt.ylabel("Position")
246
+ plt.tight_layout()
247
+ plt.plot()
248
+
249
+ cos_sim = pairwise.cosine_similarity(
250
+ totals[0][0][8]
251
+ )
252
+ plt.figure(figsize=(8, 8))
253
+ plt.imshow(cos_sim, cmap="inferno", interpolation="none")
254
+ im_ratio = 1
255
+ plt.colorbar(fraction=0.046 * im_ratio, pad=0.04)
256
+ plt.title('Pitches')
257
+ plt.xlabel("Position")
258
+ plt.ylabel("Position")
259
+ plt.tight_layout()
260
+ plt.plot()
261
+
262
+ cos_sim = pairwise.cosine_similarity(
263
+ totals[0][0][9]
264
+ )
265
+ plt.figure(figsize=(8, 8))
266
+ plt.imshow(cos_sim, cmap="inferno", interpolation="none")
267
+ im_ratio = 1
268
+ plt.colorbar(fraction=0.046 * im_ratio, pad=0.04)
269
+ plt.title('Velocities')
270
+ plt.xlabel("Position")
271
+ plt.ylabel("Position")
272
+ plt.tight_layout()
273
+ plt.plot()
274
+
275
+ """# (LOAD SOURCE MIDI)"""
276
+
277
+ #@title Load source MIDI
278
+
279
+ full_path_to_source_MIDI = "/content/Los-Angeles-MIDI-Dataset/Come-To-My-Window-Modified-Sample-MIDI.mid" #@param {type:"string"}
280
+ render_MIDI_to_audio = False #@param {type:"boolean"}
281
+
282
+ #=================================================================================
283
+
284
+ f = full_path_to_source_MIDI
285
+
286
+ print('=' * 70)
287
+ print('Loading MIDI file...')
288
+
289
+ score = MIDI.midi2ms_score(open(f, 'rb').read())
290
+
291
+ events_matrix = []
292
+
293
+ itrack = 1
294
+
295
+ while itrack < len(score):
296
+ for event in score[itrack]:
297
+ events_matrix.append(event)
298
+ itrack += 1
299
+
300
+ # Sorting...
301
+ events_matrix.sort(key=lambda x: x[1])
302
+
303
+ # recalculating timings
304
+ for e in events_matrix:
305
+ e[1] = int(e[1] / 10)
306
+ if e[0] == 'note':
307
+ e[2] = int(e[2] / 20)
308
+
309
+ # final processing...
310
+
311
+ melody_chords = []
312
+
313
+ patches = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
314
+
315
+ pe = events_matrix[0]
316
+ for e in events_matrix:
317
+
318
+ if e[0] == 'note':
319
+ # ['note', start_time, duration, channel, note, velocity]
320
+ time = max(0, min(255, e[1]-pe[1]))
321
+ duration = max(1, min(255, e[2]))
322
+ channel = max(0, min(15, e[3]))
323
+
324
+ if e[3] != 9:
325
+ instrument = max(0, min(127, patches[e[3]]))
326
+ else:
327
+ instrument = max(128, min(255, patches[e[3]]+128))
328
+
329
+ if e[3] != 9:
330
+
331
+ pitch = max(1, min(127, e[4]))
332
+ else:
333
+ pitch = max(129, min(255, e[4]+128))
334
+
335
+ if e[3] != 9:
336
+ velocity = max(1, min(127, e[5]))
337
+ else:
338
+ velocity = max(129, min(255, e[5]+128))
339
+
340
+ melody_chords.append([time, duration, channel, instrument, pitch, velocity])
341
+
342
+ if e[0] == 'patch_change':
343
+ # ['patch_change', dtime, channel, patch]
344
+ time = max(0, min(127, e[1]-pe[1]))
345
+ channel = max(0, min(15, e[2]))
346
+ patch = max(0, min(127, e[3]))
347
+
348
+ patches[channel] = patch
349
+
350
+ pe = e # Previous event
351
+
352
+ MATRIX = [[0]*256 for i in range(38)]
353
+
354
+ for m in melody_chords:
355
+
356
+ MATRIX[0][m[0]] += 1
357
+ MATRIX[1][m[1]] += 1
358
+ MATRIX[2][m[2]] += 1
359
+ MATRIX[3][m[3]] += 1
360
+ MATRIX[4][m[4]] += 1
361
+ MATRIX[5][m[5]] += 1
362
+ MATRIX[m[2]+6][m[3]] += 1
363
+ MATRIX[m[2]+22][m[4]] += 1
364
+
365
+ #==================================================
366
+
367
+ score = MIDI.midi2score(open(f, 'rb').read())
368
+
369
+ events_matrix = []
370
+
371
+ track_count = 0
372
+
373
+ for s in score:
374
+
375
+ if track_count > 0:
376
+ track = s
377
+ track.sort(key=lambda x: x[1])
378
+ events_matrix.extend(track)
379
+ else:
380
+ midi_ticks = s
381
+
382
+ track_count += 1
383
+
384
+ events_matrix.sort(key=lambda x: x[1])
385
+
386
+ for e in events_matrix:
387
+ if e[0] == 'note':
388
+ if e[3] == 9:
389
+ e[4] = ((e[4] % 128) + 128)
390
+
391
+ pitches_counts = [[y[0],y[1]] for y in Counter([y[4] for y in events_matrix if y[0] == 'note']).most_common()]
392
+ pitches_counts.sort(key=lambda x: x[0], reverse=True)
393
+
394
+ patches_list = sorted(list(set([y[3] for y in events_matrix if y[0] == 'patch_change'])))
395
+
396
+ print('=' * 70)
397
+ print('Done!')
398
+ print('=' * 70)
399
+
400
+ #============================================
401
+ # MIDI rendering code
402
+ #============================================
403
+
404
+ print('Rendering source MIDI...')
405
+ print('=' * 70)
406
+
407
+ ms_score = MIDI.midi2ms_score(open(f, 'rb').read())
408
+
409
+ itrack = 1
410
+ song_f = []
411
+
412
+ while itrack < len(ms_score):
413
+ for event in ms_score[itrack]:
414
+ if event[0] == 'note':
415
+ song_f.append(event)
416
+ itrack += 1
417
+
418
+ song_f.sort(key=lambda x: x[1])
419
+
420
+ fname = f.split('.mid')[0]
421
+
422
+ x = []
423
+ y =[]
424
+ c = []
425
+
426
+ colors = ['red', 'yellow', 'green', 'cyan', 'blue', 'pink', 'orange', 'purple', 'gray', 'white', 'gold', 'silver', 'aqua', 'azure', 'bisque', 'coral']
427
+
428
+ for s in song_f:
429
+ x.append(s[1] / 1000)
430
+ y.append(s[4])
431
+ c.append(colors[s[3]])
432
+
433
+ if render_MIDI_to_audio:
434
+ FluidSynth("/usr/share/sounds/sf2/FluidR3_GM.sf2", 16000).midi_to_audio(str(fname + '.mid'), str(fname + '.wav'))
435
+ display(Audio(str(fname + '.wav'), rate=16000))
436
+
437
+ plt.figure(figsize=(14,5))
438
+ ax=plt.axes(title=fname)
439
+ ax.set_facecolor('black')
440
+
441
+ plt.scatter(x,y, c=c)
442
+ plt.xlabel("Time")
443
+ plt.ylabel("Pitch")
444
+ plt.show()
445
+
446
+ """# (SEARCH AND EXPLORE)"""
447
+
448
+ #@title Legacy MIDI Matrixes Search (Slow)
449
+
450
+ #@markdown NOTE: You can stop the search at any time to render partial results
451
+
452
+ minimum_match_ratio_to_search_for = 0 #@param {type:"slider", min:0, max:500, step:1}
453
+ stop_search_on_exact_match = True #@param {type:"boolean"}
454
+ skip_exact_matches = False #@param {type:"boolean"}
455
+ render_MIDI_to_audio = False #@param {type:"boolean"}
456
+
457
+ #=================================================================================
458
+
459
+ matching_type = "minkowski"
460
+
461
+ def compress_matrix(midi_matrix):
462
+
463
+ MX = 38
464
+ MY = 256
465
+
466
+ if len(midi_matrix) == MX:
467
+
468
+ compressed_matrix = []
469
+ zeros = 0
470
+ zeros_shift = 0
471
+ zeros_count = 0
472
+
473
+ for m in midi_matrix:
474
+ for mm in m:
475
+ zeros_shift = max(zeros_shift, mm) + 1
476
+
477
+ compressed_matrix.append(zeros_shift)
478
+
479
+ for m in midi_matrix:
480
+ if len(m) == MY:
481
+ for mm in m:
482
+ if mm != 0:
483
+ if zeros > 0:
484
+ compressed_matrix.append(zeros+zeros_shift)
485
+ zeros = 0
486
+ compressed_matrix.append(mm)
487
+
488
+ else:
489
+ zeros += 1
490
+ zeros_count += 1
491
+
492
+ else:
493
+ print('Wrong matrix format!')
494
+ return [1]
495
+
496
+ if zeros > 0:
497
+ compressed_matrix.append(zeros+zeros_shift)
498
+
499
+ compressed_matrix.append(zeros_count+zeros_shift)
500
+ compressed_matrix.append(zeros_shift)
501
+
502
+ return compressed_matrix
503
+
504
+ else:
505
+ print('Wrong matrix format!')
506
+ return [0]
507
+
508
+ #=================================================================================
509
+
510
+ def decompress_matrix(compressed_midi_matrix):
511
+
512
+ MX = 38
513
+ MY = 256
514
+
515
+ zeros_count = 0
516
+
517
+ temp_matrix = []
518
+ decompressed_matrix = [[0]*MY for i in range(MX)]
519
+
520
+ if compressed_midi_matrix[0] == compressed_midi_matrix[-1]:
521
+ zeros_shift = compressed_midi_matrix[0]
522
+ mcount = 0
523
+
524
+ for c in compressed_midi_matrix[1:-2]:
525
+ if c > zeros_shift:
526
+ temp_matrix.extend([0] * (c-zeros_shift))
527
+ zeros_count += (c-zeros_shift)
528
+
529
+ else:
530
+ temp_matrix.extend([c])
531
+
532
+ if len(temp_matrix) == (MX * MY):
533
+
534
+ for i in range(MX):
535
+ for j in range(MY):
536
+ decompressed_matrix[i][j] = copy.deepcopy(temp_matrix[(i*MY) + j])
537
+
538
+ if len(decompressed_matrix) == MX and zeros_count == (compressed_midi_matrix[-2]-zeros_shift):
539
+ return decompressed_matrix
540
+
541
+ else:
542
+ print('Matrix is corrupted!')
543
+ return [len(decompressed_matrix), (MX * MY), zeros_count, (compressed_midi_matrix[-2]-zeros_shift)]
544
+
545
+ else:
546
+ print('Matrix is corrupted!')
547
+ return [len(temp_matrix), zeros_count]
548
+
549
+ else:
550
+ print('Matrix is corrupted!')
551
+ return [0]
552
+
553
+ #=================================================================================
554
+
555
+ def batched_scores(matbatch, matrix):
556
+
557
+ sco= []
558
+ for D in matbatch:
559
+
560
+ dist = pairwise_distances(matrix, decompress_matrix(D[1]), metric=matching_type)[0][0]
561
+
562
+ if skip_exact_matches:
563
+ if dist == 0:
564
+ dist = 999999
565
+
566
+ if dist <= minimum_match_ratio_to_search_for:
567
+ dist = 999999
568
+
569
+ sco.append(dist)
570
+
571
+ return sco
572
+
573
+ #=================================================================================
574
+
575
+ print('=' * 70)
576
+ print('Searching...Please wait...')
577
+ print('=' * 70)
578
+
579
+ scores = []
580
+
581
+ c_count = multiprocessing.cpu_count()
582
+
583
+ par = Parallel(n_jobs=c_count)
584
+
585
+ num_jobs = c_count
586
+ scores_per_job = 100
587
+
588
+ MATRIX_X = [MATRIX] * num_jobs
589
+
590
+ for i in tqdm(range(0, len(midi_matrixes), (num_jobs*scores_per_job))):
591
+
592
+ try:
593
+
594
+ MAT_BATCHES = []
595
+
596
+ for j in range(num_jobs):
597
+ MAT_BATCHES.append(midi_matrixes[i+(j*scores_per_job):i+((j+1)*scores_per_job)])
598
+
599
+ output = par(delayed(batched_scores) (MB, MAT) for MB, MAT in zip(MAT_BATCHES, MATRIX_X))
600
+
601
+ output1 = []
602
+
603
+ for o in output:
604
+ output1.extend(o)
605
+
606
+ scores.extend(output1)
607
+
608
+ if stop_search_on_exact_match:
609
+ if 0 in output1:
610
+ print('=' * 70)
611
+ print('Found exact match!')
612
+ print('Stoping further search...')
613
+ print('=' * 70)
614
+ break
615
+
616
+ else:
617
+ if 0 in output1:
618
+ print('=' * 70)
619
+ print('Found exact match!')
620
+ print('=' * 70)
621
+ print('LAMDa Index:', scores.index(min(scores)))
622
+ print('LAMDa File Name:', midi_matrixes[scores.index(min(scores))][0])
623
+ print('=' * 70)
624
+ print('Continuing search...')
625
+ print('=' * 70)
626
+
627
+ except KeyboardInterrupt:
628
+ break
629
+
630
+ except:
631
+ continue
632
+
633
+ print('Done!')
634
+ print('=' * 70)
635
+ print('Best match:')
636
+ print('=' * 70)
637
+ print(matching_type.title(), 'distance ==', min(scores))
638
+ print('LAMDa Index:', scores.index(min(scores)))
639
+ print('LAMDa File Name:', midi_matrixes[scores.index(min(scores))][0])
640
+ print('=' * 70)
641
+
642
+ #============================================
643
+ # MIDI rendering code
644
+ #============================================
645
+
646
+ print('Rendering source MIDI...')
647
+ print('=' * 70)
648
+
649
+ fn = midi_matrixes[scores.index(min(scores))][0]
650
+
651
+ try:
652
+ fn_idx = [y[0] for y in LAMD_files_list].index(fn)
653
+
654
+ f = LAMD_files_list[fn_idx][1]
655
+
656
+ ms_score = MIDI.midi2ms_score(open(f, 'rb').read())
657
+
658
+ itrack = 1
659
+ song_f = []
660
+
661
+ while itrack < len(ms_score):
662
+ for event in ms_score[itrack]:
663
+ if event[0] == 'note':
664
+ song_f.append(event)
665
+ itrack += 1
666
+
667
+ song_f.sort(key=lambda x: x[1])
668
+
669
+ fname = f.split('.mid')[0]
670
+
671
+ x = []
672
+ y =[]
673
+ c = []
674
+
675
+ colors = ['red', 'yellow', 'green', 'cyan', 'blue', 'pink', 'orange', 'purple', 'gray', 'white', 'gold', 'silver', 'aqua', 'azure', 'bisque', 'coral']
676
+
677
+ for s in song_f:
678
+ x.append(s[1] / 1000)
679
+ y.append(s[4])
680
+ c.append(colors[s[3]])
681
+
682
+ if render_MIDI_to_audio:
683
+ FluidSynth("/usr/share/sounds/sf2/FluidR3_GM.sf2", 16000).midi_to_audio(str(fname + '.mid'), str(fname + '.wav'))
684
+ display(Audio(str(fname + '.wav'), rate=16000))
685
+
686
+ plt.figure(figsize=(14,5))
687
+ ax=plt.axes(title=fname)
688
+ ax.set_facecolor('black')
689
+
690
+ plt.scatter(x,y, c=c)
691
+ plt.xlabel("Time")
692
+ plt.ylabel("Pitch")
693
+ plt.show()
694
+
695
+ except:
696
+ pass
697
+
698
+ #============================================
699
+
700
+ print('Top 100 matches')
701
+ print('=' * 70)
702
+
703
+ top_matches = []
704
+
705
+ for i in range(len(scores)):
706
+ top_matches.append([midi_matrixes[i][0], scores[i]])
707
+
708
+ top_matches.sort(key=lambda x: x[1])
709
+
710
+ for t in top_matches[:100]:
711
+ print(t)
712
+
713
+ print('=' * 70)
714
+
715
+ #@title MIDI Pitches Search (Fast)
716
+
717
+ #@markdown NOTE: You can stop the search at any time to render partial results
718
+
719
+ maximum_match_ratio_to_search_for = 1 #@param {type:"slider", min:0, max:1, step:0.01}
720
+ pitches_counts_cutoff_threshold_ratio = 0.2 #@param {type:"slider", min:0, max:1, step:0.05}
721
+ skip_exact_matches = False #@param {type:"boolean"}
722
+ render_MIDI_to_audio = False #@param {type:"boolean"}
723
+
724
+ print('=' * 70)
725
+ print('MIDI Pitches Search')
726
+ print('=' * 70)
727
+
728
+ ratios = []
729
+
730
+ for d in tqdm(meta_data):
731
+
732
+ try:
733
+ p_counts = d[1][3][1]
734
+ p_counts.sort(reverse = True, key = lambda x: x[1])
735
+ max_p_count = p_counts[1][0]
736
+ trimmed_p_counts = [y for y in p_counts if y[1] >= (max_p_count * pitches_counts_cutoff_threshold_ratio)]
737
+
738
+ pitches_counts.sort(reverse = True, key = lambda x: x[1])
739
+ max_pitches_count = pitches_counts[1][0]
740
+ trimmed_pitches_counts = [y for y in pitches_counts if y[1] >= (max_pitches_count * pitches_counts_cutoff_threshold_ratio)]
741
+
742
+ num_same_pitches = len(set([T[0] for T in trimmed_p_counts]) & set([m[0] for m in trimmed_pitches_counts]))
743
+ same_pitches_ratio = (num_same_pitches / len(set([m[0] for m in trimmed_p_counts]+[T[0] for T in trimmed_pitches_counts])))
744
+
745
+ if skip_exact_matches:
746
+ if same_pitches_ratio == 1:
747
+ same_pitches_ratio = 0
748
+
749
+ if same_pitches_ratio > maximum_match_ratio_to_search_for:
750
+ same_pitches_ratio = 0
751
+
752
+ ratios.append(same_pitches_ratio)
753
+
754
+ except KeyboardInterrupt:
755
+ break
756
+
757
+ except:
758
+ break
759
+
760
+ max_ratio = max(ratios)
761
+ max_ratio_index = ratios.index(max(ratios))
762
+
763
+ print('FOUND')
764
+ print('=' * 70)
765
+ print('Match ratio', max_ratio)
766
+ print('MIDI file name', meta_data[max_ratio_index][0])
767
+ print('=' * 70)
768
+ print('First metadata MIDI event', meta_data[max_ratio_index][1][0])
769
+ print('=' * 70)
770
+
771
+ #============================================
772
+ # MIDI rendering code
773
+ #============================================
774
+
775
+ print('Rendering source MIDI...')
776
+ print('=' * 70)
777
+
778
+ fn = meta_data[max_ratio_index][0]
779
+ fn_idx = [y[0] for y in LAMD_files_list].index(fn)
780
+
781
+ f = LAMD_files_list[fn_idx][1]
782
+
783
+ ms_score = MIDI.midi2ms_score(open(f, 'rb').read())
784
+
785
+ itrack = 1
786
+ song_f = []
787
+
788
+ while itrack < len(ms_score):
789
+ for event in ms_score[itrack]:
790
+ if event[0] == 'note':
791
+ song_f.append(event)
792
+ itrack += 1
793
+
794
+ song_f.sort(key=lambda x: x[1])
795
+
796
+ fname = f.split('.mid')[0]
797
+
798
+ x = []
799
+ y =[]
800
+ c = []
801
+
802
+ colors = ['red', 'yellow', 'green', 'cyan', 'blue', 'pink', 'orange', 'purple', 'gray', 'white', 'gold', 'silver', 'aqua', 'azure', 'bisque', 'coral']
803
+
804
+ for s in song_f:
805
+ x.append(s[1] / 1000)
806
+ y.append(s[4])
807
+ c.append(colors[s[3]])
808
+
809
+ if render_MIDI_to_audio:
810
+ FluidSynth("/usr/share/sounds/sf2/FluidR3_GM.sf2", 16000).midi_to_audio(str(fname + '.mid'), str(fname + '.wav'))
811
+ display(Audio(str(fname + '.wav'), rate=16000))
812
+
813
+ plt.figure(figsize=(14,5))
814
+ ax=plt.axes(title=fname)
815
+ ax.set_facecolor('black')
816
+
817
+ plt.scatter(x,y, c=c)
818
+ plt.xlabel("Time")
819
+ plt.ylabel("Pitch")
820
+ plt.show()
821
+
822
+ #@title MIDI Patches Search (Fast)
823
+
824
+ #@markdown NOTE: You can stop the search at any time to render partial results
825
+
826
+ maximum_match_ratio_to_search_for = 1 #@param {type:"slider", min:0, max:1, step:0.01}
827
+ skip_exact_matches = False #@param {type:"boolean"}
828
+ render_MIDI_to_audio = False #@param {type:"boolean"}
829
+
830
+ print('=' * 70)
831
+ print('MIDI Patches Search')
832
+ print('=' * 70)
833
+
834
+ ratios = []
835
+
836
+ for d in tqdm(meta_data):
837
+
838
+ try:
839
+
840
+ p_list= d[1][4][1]
841
+
842
+ num_same_patches = len(set(p_list) & set(patches_list))
843
+
844
+ if len(set(p_list + patches_list)) > 0:
845
+ same_patches_ratio = num_same_patches / len(set(p_list + patches_list))
846
+ else:
847
+ same_patches_ratio = 0
848
+
849
+ if skip_exact_matches:
850
+ if same_patches_ratio == 1:
851
+ same_patches_ratio = 0
852
+
853
+ if same_patches_ratio > maximum_match_ratio_to_search_for:
854
+ same_patches_ratio = 0
855
+
856
+ ratios.append(same_patches_ratio)
857
+
858
+ except KeyboardInterrupt:
859
+ break
860
+
861
+ except:
862
+ break
863
+
864
+ max_ratio = max(ratios)
865
+ max_ratio_index = ratios.index(max(ratios))
866
+
867
+ print('FOUND')
868
+ print('=' * 70)
869
+ print('Match ratio', max_ratio)
870
+ print('MIDI file name', meta_data[max_ratio_index][0])
871
+ print('=' * 70)
872
+ print('Found MIDI patches list', meta_data[max_ratio_index][1][4][1])
873
+ print('=' * 70)
874
+
875
+ #============================================
876
+ # MIDI rendering code
877
+ #============================================
878
+
879
+ print('Rendering source MIDI...')
880
+ print('=' * 70)
881
+
882
+ fn = meta_data[max_ratio_index][0]
883
+ fn_idx = [y[0] for y in LAMD_files_list].index(fn)
884
+
885
+ f = LAMD_files_list[fn_idx][1]
886
+
887
+ ms_score = MIDI.midi2ms_score(open(f, 'rb').read())
888
+
889
+ itrack = 1
890
+ song_f = []
891
+
892
+ while itrack < len(ms_score):
893
+ for event in ms_score[itrack]:
894
+ if event[0] == 'note':
895
+ song_f.append(event)
896
+ itrack += 1
897
+
898
+ song_f.sort(key=lambda x: x[1])
899
+
900
+ fname = f.split('.mid')[0]
901
+
902
+ x = []
903
+ y =[]
904
+ c = []
905
+
906
+ colors = ['red', 'yellow', 'green', 'cyan', 'blue', 'pink', 'orange', 'purple', 'gray', 'white', 'gold', 'silver', 'aqua', 'azure', 'bisque', 'coral']
907
+
908
+ for s in song_f:
909
+ x.append(s[1] / 1000)
910
+ y.append(s[4])
911
+ c.append(colors[s[3]])
912
+
913
+ if render_MIDI_to_audio:
914
+ FluidSynth("/usr/share/sounds/sf2/FluidR3_GM.sf2", 16000).midi_to_audio(str(fname + '.mid'), str(fname + '.wav'))
915
+ display(Audio(str(fname + '.wav'), rate=16000))
916
+
917
+ plt.figure(figsize=(14,5))
918
+ ax=plt.axes(title=fname)
919
+ ax.set_facecolor('black')
920
+
921
+ plt.scatter(x,y, c=c)
922
+ plt.xlabel("Time")
923
+ plt.ylabel("Pitch")
924
+ plt.show()
925
+
926
+ #@title Metadata Search
927
+
928
+ #@markdown You can search the metadata by search query or by MIDI md5 hash file name
929
+
930
+ search_query = "Come To My Window" #@param {type:"string"}
931
+ md5_hash_MIDI_file_name = "d9a7e1c6a375b8e560155a5977fc10f8" #@param {type:"string"}
932
+ case_sensitive_search = False #@param {type:"boolean"}
933
+
934
+ fields_to_search = ['track_name',
935
+ 'text_event',
936
+ 'lyric',
937
+ 'copyright_text_event',
938
+ 'marker',
939
+ 'text_event_08',
940
+ 'text_event_09',
941
+ 'text_event_0a',
942
+ 'text_event_0b',
943
+ 'text_event_0c',
944
+ 'text_event_0d',
945
+ 'text_event_0e',
946
+ 'text_event_0f',
947
+ ]
948
+
949
+ print('=' * 70)
950
+ print('Los Angeles MIDI Dataset Metadata Search')
951
+ print('=' * 70)
952
+ print('Searching...')
953
+ print('=' * 70)
954
+
955
+ if md5_hash_MIDI_file_name != '':
956
+ for d in tqdm(meta_data):
957
+ try:
958
+ if d[0] == md5_hash_MIDI_file_name:
959
+ print('Found!')
960
+ print('=' * 70)
961
+ print('Metadata index:', meta_data.index(d))
962
+ print('MIDI file name:', meta_data[meta_data.index(d)][0])
963
+ print('Result:', d[1])
964
+ print('=' * 70)
965
+ break
966
+
967
+ except KeyboardInterrupt:
968
+ print('Ending search...')
969
+ print('=' * 70)
970
+ break
971
+
972
+ except:
973
+ print('Ending search...')
974
+ print('=' * 70)
975
+ break
976
+
977
+ if d[0] != md5_hash_MIDI_file_name:
978
+ print('Not found!')
979
+ print('=' * 70)
980
+ print('md5 hash was not found!')
981
+ print('Ending search...')
982
+ print('=' * 70)
983
+
984
+ else:
985
+ for d in tqdm(meta_data):
986
+ try:
987
+ for dd in d[1]:
988
+ if dd[0] in fields_to_search:
989
+ if case_sensitive_search:
990
+ if str(search_query) in str(dd[2]):
991
+ print('Found!')
992
+ print('=' * 70)
993
+ print('Metadata index:', meta_data.index(d))
994
+ print('MIDI file name:', meta_data[meta_data.index(d)][0])
995
+ print('Result:', dd[2])
996
+ print('=' * 70)
997
+
998
+ else:
999
+ if str(search_query).lower() in str(dd[2]).lower():
1000
+ print('Found!')
1001
+ print('=' * 70)
1002
+ print('Metadata index:', meta_data.index(d))
1003
+ print('MIDI file name:', meta_data[meta_data.index(d)][0])
1004
+ print('Result:', dd[2])
1005
+ print('=' * 70)
1006
+
1007
+ except KeyboardInterrupt:
1008
+ print('Ending search...')
1009
+ print('=' * 70)
1010
+ break
1011
+
1012
+ except:
1013
+ print('Ending search...')
1014
+ print('=' * 70)
1015
+ break
1016
+
1017
+ """# (MIDI FILE PLAYER)"""
1018
+
1019
+ #@title MIDI file player
1020
+
1021
+ #@markdown NOTE: You can use md5 hash file name or full MIDI file path to play it
1022
+
1023
+ md5_hash_MIDI_file_name = "d9a7e1c6a375b8e560155a5977fc10f8" #@param {type:"string"}
1024
+ full_path_to_MIDI = "/content/Los-Angeles-MIDI-Dataset/Come-To-My-Window-Modified-Sample-MIDI.mid" #@param {type:"string"}
1025
+ render_MIDI_to_audio = False #@param {type:"boolean"}
1026
+
1027
+ #============================================
1028
+ # MIDI rendering code
1029
+ #============================================
1030
+
1031
+ print('=' * 70)
1032
+ print('MIDI file player')
1033
+ print('=' * 70)
1034
+
1035
+ try:
1036
+
1037
+ if os.path.exists(full_path_to_MIDI):
1038
+ f = full_path_to_MIDI
1039
+ print('Using full path to MIDI')
1040
+
1041
+ else:
1042
+ fn = md5_hash_MIDI_file_name
1043
+ fn_idx = [y[0] for y in LAMD_files_list].index(fn)
1044
+ f = LAMD_files_list[fn_idx][1]
1045
+
1046
+ print('Using md5 hash filename')
1047
+
1048
+ print('=' * 70)
1049
+ print('Rendering MIDI...')
1050
+ print('=' * 70)
1051
+
1052
+ ms_score = MIDI.midi2ms_score(open(f, 'rb').read())
1053
+
1054
+ itrack = 1
1055
+ song_f = []
1056
+
1057
+ while itrack < len(ms_score):
1058
+ for event in ms_score[itrack]:
1059
+ if event[0] == 'note':
1060
+ song_f.append(event)
1061
+ itrack += 1
1062
+
1063
+ song_f.sort(key=lambda x: x[1])
1064
+
1065
+ fname = f.split('.mid')[0]
1066
+
1067
+ x = []
1068
+ y =[]
1069
+ c = []
1070
+
1071
+ colors = ['red', 'yellow', 'green', 'cyan', 'blue', 'pink', 'orange', 'purple', 'gray', 'white', 'gold', 'silver', 'aqua', 'azure', 'bisque', 'coral']
1072
+
1073
+ for s in song_f:
1074
+ x.append(s[1] / 1000)
1075
+ y.append(s[4])
1076
+ c.append(colors[s[3]])
1077
+
1078
+ if render_MIDI_to_audio:
1079
+ FluidSynth("/usr/share/sounds/sf2/FluidR3_GM.sf2", 16000).midi_to_audio(str(fname + '.mid'), str(fname + '.wav'))
1080
+ display(Audio(str(fname + '.wav'), rate=16000))
1081
+
1082
+ plt.figure(figsize=(14,5))
1083
+ ax=plt.axes(title=fname)
1084
+ ax.set_facecolor('black')
1085
+
1086
+ plt.scatter(x,y, c=c)
1087
+ plt.xlabel("Time")
1088
+ plt.ylabel("Pitch")
1089
+ plt.show()
1090
+
1091
+ except:
1092
+ print('File not found!!!')
1093
+ print('Check the filename!')
1094
+ print('=' * 70)
1095
+
1096
+ """# (COLAB MIDI FILES LOCATOR/DOWNLOADER)"""
1097
+
1098
+ #@title Loacate and/or download desired MIDI files by MIDI md5 hash file names
1099
+
1100
+ MIDI_md5_hash_file_name_1 = "d9a7e1c6a375b8e560155a5977fc10f8" #@param {type:"string"}
1101
+ MIDI_md5_hash_file_name_2 = "" #@param {type:"string"}
1102
+ MIDI_md5_hash_file_name_3 = "" #@param {type:"string"}
1103
+ MIDI_md5_hash_file_name_4 = "" #@param {type:"string"}
1104
+ MIDI_md5_hash_file_name_5 = "" #@param {type:"string"}
1105
+ download_located_files = False #@param {type:"boolean"}
1106
+
1107
+ print('=' * 70)
1108
+ print('MIDI files locator and downloader')
1109
+ print('=' * 70)
1110
+
1111
+ md5_list = []
1112
+
1113
+ if MIDI_md5_hash_file_name_1 != '':
1114
+ md5_list.append(MIDI_md5_hash_file_name_1)
1115
+
1116
+ if MIDI_md5_hash_file_name_2 != '':
1117
+ md5_list.append(MIDI_md5_hash_file_name_2)
1118
+
1119
+ if MIDI_md5_hash_file_name_3 != '':
1120
+ md5_list.append(MIDI_md5_hash_file_name_3)
1121
+
1122
+ if MIDI_md5_hash_file_name_4 != '':
1123
+ md5_list.append(MIDI_md5_hash_file_name_4)
1124
+
1125
+ if MIDI_md5_hash_file_name_5 != '':
1126
+ md5_list.append(MIDI_md5_hash_file_name_5)
1127
+
1128
+ if len(md5_list) > 0:
1129
+ for m in md5_list:
1130
+ try:
1131
+
1132
+ fn = m
1133
+ fn_idx = [y[0] for y in LAMD_files_list].index(fn)
1134
+ f = LAMD_files_list[fn_idx][1]
1135
+
1136
+ print('Found md5 hash file name', m)
1137
+
1138
+ location_str = ''
1139
+
1140
+ fl = f.split('/')
1141
+ for fa in fl[:-1]:
1142
+ if fa != '' and fa != 'content':
1143
+ location_str += '/'
1144
+ location_str += str(fa)
1145
+
1146
+ print('Colab location/folder', location_str)
1147
+
1148
+ if download_located_files:
1149
+ print('Downloading MIDI file', str(m) + '.mid')
1150
+ files.download(f)
1151
+
1152
+ print('=' * 70)
1153
+
1154
+ except:
1155
+ print('md5 hash file name', m, 'not found!!!')
1156
+ print('Check the file name!')
1157
+ print('=' * 70)
1158
+ continue
1159
+
1160
+ else:
1161
+ print('No md5 hash file names were specified!')
1162
+ print('Check input!')
1163
+ print('=' * 70)
1164
+
1165
+ """# (CUSTOM ANALYSIS TEMPLATE)"""
1166
+
1167
+ #@title Los Angeles MIDI Dataset Reader
1168
+
1169
+ print('=' * 70)
1170
+ print('Los Angeles MIDI Dataset Reader')
1171
+ print('=' * 70)
1172
+ print('Starting up...')
1173
+ print('=' * 70)
1174
+
1175
+ ###########
1176
+
1177
+ print('Loading MIDI files...')
1178
+ print('This may take a while on a large dataset in particular.')
1179
+
1180
+ dataset_addr = "/content/LAMD/MIDIs"
1181
+
1182
+ # os.chdir(dataset_addr)
1183
+ filez = list()
1184
+ for (dirpath, dirnames, filenames) in os.walk(dataset_addr):
1185
+ filez += [os.path.join(dirpath, file) for file in filenames]
1186
+
1187
+ if filez == []:
1188
+ print('Could not find any MIDI files. Please check Dataset dir...')
1189
+ print('=' * 70)
1190
+
1191
+ print('=' * 70)
1192
+ print('Randomizing file list...')
1193
+ random.shuffle(filez)
1194
+ print('=' * 70)
1195
+
1196
+ ###########
1197
+
1198
+ START_FILE_NUMBER = 0
1199
+ LAST_SAVED_BATCH_COUNT = 0
1200
+
1201
+ input_files_count = START_FILE_NUMBER
1202
+ files_count = LAST_SAVED_BATCH_COUNT
1203
+
1204
+ stats = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
1205
+
1206
+ print('Reading MIDI files. Please wait...')
1207
+ print('=' * 70)
1208
+
1209
+ for f in tqdm(filez[START_FILE_NUMBER:]):
1210
+ try:
1211
+ input_files_count += 1
1212
+
1213
+ fn = os.path.basename(f)
1214
+ fn1 = fn.split('.mid')[0]
1215
+
1216
+ #=======================================================
1217
+ # START PROCESSING
1218
+ #=======================================================
1219
+
1220
+ # Convering MIDI to score with MIDI.py module
1221
+ score = MIDI.midi2score(open(f, 'rb').read())
1222
+
1223
+ events_matrix = []
1224
+
1225
+ itrack = 1
1226
+
1227
+ while itrack < len(score):
1228
+ for event in score[itrack]:
1229
+ events_matrix.append(event)
1230
+ itrack += 1
1231
+
1232
+ # Sorting...
1233
+ events_matrix.sort(key=lambda x: x[1])
1234
+
1235
+ if len(events_matrix) > 0:
1236
+
1237
+ #=======================================================
1238
+ # INSERT YOUR CUSTOM ANAYLSIS CODE RIGHT HERE
1239
+ #=======================================================
1240
+
1241
+ # Processed files counter
1242
+ files_count += 1
1243
+
1244
+ # Saving every 5000 processed files
1245
+ if files_count % 10000 == 0:
1246
+ print('=' * 70)
1247
+ print('Processed so far:', files_count, 'out of', input_files_count, '===', files_count / input_files_count, 'good files ratio')
1248
+ print('=' * 70)
1249
+
1250
+ except KeyboardInterrupt:
1251
+ print('Saving current progress and quitting...')
1252
+ break
1253
+
1254
+ except Exception as ex:
1255
+ print('WARNING !!!')
1256
+ print('=' * 70)
1257
+ print('Bad MIDI:', f)
1258
+ print('Error detected:', ex)
1259
+ print('=' * 70)
1260
+ continue
1261
+
1262
+ print('=' * 70)
1263
+ print('Final files counts:', files_count, 'out of', input_files_count, '===', files_count / input_files_count, 'good files ratio')
1264
+ print('=' * 70)
1265
+
1266
+ print('Resulting Stats:')
1267
+ print('=' * 70)
1268
+ print('Total good processed MIDI files:', files_count)
1269
+ print('=' * 70)
1270
+ print('Done!')
1271
+ print('=' * 70)
1272
+
1273
+ """# Congrats! You did it! :)"""