{ "cells": [ { "cell_type": "markdown", "metadata": { "gradient": { "editing": false, "id": "ac5a4cf0-d9d2-47b5-9633-b53f8d99a4d2", "kernelId": "" }, "id": "SiTIpPjArIyr" }, "source": [ "# Master MIDI Dataset Search and Filter (ver. 4.0)\n", "\n", "***\n", "\n", "Powered by tegridy-tools: https://github.com/asigalov61/tegridy-tools\n", "\n", "***\n", "\n", "#### Project Los Angeles\n", "\n", "#### Tegridy Code 2023\n", "\n", "***" ] }, { "cell_type": "markdown", "metadata": { "gradient": { "editing": false, "id": "fa0a611c-1803-42ae-bdf6-a49b5a4e781b", "kernelId": "" }, "id": "gOd93yV0sGd2" }, "source": [ "# (SETUP ENVIRONMENT)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "gradient": { "editing": false, "id": "a1a45a91-d909-4fd4-b67a-5e16b971d179", "kernelId": "" }, "id": "fX12Yquyuihc" }, "outputs": [], "source": [ "#@title Install all dependencies (run only once per session)\n", "\n", "!git clone https://github.com/asigalov61/tegridy-tools\n", "!pip install huggingface_hub\n", "!pip install tqdm" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "gradient": { "editing": false, "id": "b8207b76-9514-4c07-95db-95a4742e52c5", "kernelId": "" }, "id": "z7n9vnKmug1J", "cellView": "form" }, "outputs": [], "source": [ "#@title Import all needed modules\n", "\n", "print('Loading core modules... Please wait...')\n", "import os\n", "import copy\n", "from collections import Counter\n", "import random\n", "import pickle\n", "from tqdm import tqdm\n", "import pprint\n", "import statistics\n", "import shutil\n", "\n", "print('Creating IO dirs... Please wait...')\n", "\n", "if not os.path.exists('/content/Main-MIDI-Dataset'):\n", " os.makedirs('/content/Main-MIDI-Dataset')\n", "\n", "if not os.path.exists('/content/Master-MIDI-Dataset'):\n", " os.makedirs('/content/Master-MIDI-Dataset')\n", "\n", "if not os.path.exists('/content/Output-MIDI-Dataset'):\n", " os.makedirs('/content/Output-MIDI-Dataset')\n", "\n", "print('Loading TMIDIX module...')\n", "os.chdir('/content/tegridy-tools/tegridy-tools')\n", "\n", "import TMIDIX\n", "\n", "print('Done!')\n", "\n", "from huggingface_hub import hf_hub_download\n", "\n", "os.chdir('/content/')\n", "print('Enjoy! :)')" ] }, { "cell_type": "markdown", "metadata": { "gradient": { "editing": false, "id": "20b8698a-0b4e-4fdb-ae49-24d063782e77", "kernelId": "" }, "id": "ObPxlEutsQBj" }, "source": [ "# (PREP MAIN MIDI DATASET)" ] }, { "cell_type": "code", "source": [ "#@title Download Los Angeles MIDI Dataset\n", "print('=' * 70)\n", "print('Downloading Los Angeles MIDI Dataset...Please wait...')\n", "print('=' * 70)\n", "\n", "hf_hub_download(repo_id='projectlosangeles/Los-Angeles-MIDI-Dataset',\n", " filename='Los-Angeles-MIDI-Dataset-Ver-4-0-CC-BY-NC-SA.zip',\n", " repo_type=\"dataset\",\n", " local_dir='/content/Main-MIDI-Dataset',\n", " local_dir_use_symlinks=False)\n", "print('=' * 70)\n", "print('Done! Enjoy! :)')\n", "print('=' * 70)" ], "metadata": { "cellView": "form", "id": "7aItlhq9cRxZ" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "#@title Unzip Los Angeles MIDI Dataset\n", "%cd /content/Main-MIDI-Dataset/\n", "\n", "print('=' * 70)\n", "print('Unzipping Los Angeles MIDI Dataset...Please wait...')\n", "!unzip 'Los-Angeles-MIDI-Dataset-Ver-4-0-CC-BY-NC-SA.zip'\n", "print('=' * 70)\n", "\n", "print('Done! Enjoy! :)')\n", "print('=' * 70)\n", "%cd /content/" ], "metadata": { "cellView": "form", "id": "zMF4vdMNDYYg" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "#@title Create Los Angeles MIDI Dataset files list\n", "print('=' * 70)\n", "print('Creating dataset files list...')\n", "dataset_addr = \"/content/Main-MIDI-Dataset/MIDIs\"\n", "\n", "# os.chdir(dataset_addr)\n", "filez = list()\n", "for (dirpath, dirnames, filenames) in os.walk(dataset_addr):\n", " filez += [os.path.join(dirpath, file) for file in filenames]\n", "\n", "if filez == []:\n", " print('Could not find any MIDI files. Please check Dataset dir...')\n", " print('=' * 70)\n", "\n", "print('=' * 70)\n", "print('Randomizing file list...')\n", "random.shuffle(filez)\n", "print('=' * 70)\n", "\n", "LAMD_files_list = []\n", "\n", "for f in tqdm(filez):\n", " LAMD_files_list.append([f.split('/')[-1].split('.mid')[0], f])\n", "print('Done!')\n", "print('=' * 70)" ], "metadata": { "cellView": "form", "id": "btrUDk8MDfdw" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "#@title Load Los Angeles MIDI Dataset metadata\n", "print('=' * 70)\n", "print('Loading LAMDa data...Please wait...')\n", "print('=' * 70)\n", "print('Loading LAMDa META-DATA...')\n", "meta_data = pickle.load(open('/content/Main-MIDI-Dataset/META_DATA/LAMDa_META_DATA.pickle', 'rb'))\n", "print('Done!')" ], "metadata": { "cellView": "form", "id": "Mv-pjxbrIqi2" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# (SEARCH AND FILTER)\n", "\n", "### DO NOT FORGET TO UPLOAD YOUR MASTER DATASET TO \"Master-MIDI-Dataset\" FOLDER" ], "metadata": { "id": "iaeqXuIHI0_T" } }, { "cell_type": "code", "source": [ "#@title Master MIDI Dataset Search and Filter\n", "\n", "#@markdown NOTE: You can stop the search at any time to render partial results\n", "\n", "number_of_top_ratios_MIDIs_to_collect = 10 #@param {type:\"slider\", min:1, max:20, step:1}\n", "\n", "#@markdown Match ratio control option\n", "\n", "maximum_match_ratio_to_search_for = 1 #@param {type:\"slider\", min:0, max:1, step:0.01}\n", "\n", "#@markdown MIDI pitches search options\n", "\n", "pitches_counts_cutoff_threshold_ratio = 0 #@param {type:\"slider\", min:0, max:1, step:0.05}\n", "search_transposed_pitches = False #@param {type:\"boolean\"}\n", "skip_exact_matches = False #@param {type:\"boolean\"}\n", "\n", "#@markdown Additional search options\n", "\n", "add_pitches_counts_ratios = False #@param {type:\"boolean\"}\n", "add_timings_ratios = False #@param {type:\"boolean\"}\n", "add_durations_ratios = False #@param {type:\"boolean\"}\n", "\n", "print('=' * 70)\n", "print('Master MIDI Dataset Search and Filter')\n", "print('=' * 70)\n", "\n", "###########\n", "\n", "print('Loading MIDI files...')\n", "print('This may take a while on a large dataset in particular.')\n", "\n", "dataset_addr = \"/content/Master-MIDI-Dataset\"\n", "# os.chdir(dataset_addr)\n", "filez = list()\n", "for (dirpath, dirnames, filenames) in os.walk(dataset_addr):\n", " filez += [os.path.join(dirpath, file) for file in filenames]\n", "print('=' * 70)\n", "\n", "if filez == []:\n", " print('Could not find any MIDI files. Please check Dataset dir...')\n", " print('=' * 70)\n", "\n", "print('Randomizing file list...')\n", "random.shuffle(filez)\n", "print('=' * 70)\n", "\n", "###################\n", "\n", "if not os.path.exists('/content/Output-MIDI-Dataset'):\n", " os.makedirs('/content/Output-MIDI-Dataset')\n", "\n", "###################\n", "\n", "input_files_count = 0\n", "files_count = 0\n", "\n", "for f in filez:\n", " try:\n", "\n", " input_files_count += 1\n", "\n", " fn = os.path.basename(f)\n", " fn1 = fn.split('.mid')[0]\n", " ext = fn.split('.')[-1]\n", "\n", " if ext == 'mid' or ext == 'midi' or ext == 'kar':\n", "\n", " print('Processing MIDI File #', files_count+1, 'out of', len(filez))\n", " print('MIDI file name', fn)\n", " print('-' * 70)\n", "\n", " #=======================================================\n", "\n", " score = TMIDIX.midi2score(open(f, 'rb').read())\n", "\n", " events_matrix = []\n", "\n", " track_count = 0\n", "\n", " for s in score:\n", "\n", " if track_count > 0:\n", " track = s\n", " track.sort(key=lambda x: x[1])\n", " events_matrix.extend(track)\n", " else:\n", " midi_ticks = s\n", "\n", " track_count += 1\n", "\n", " events_matrix.sort(key=lambda x: x[1])\n", "\n", " mult_pitches_counts = []\n", "\n", " for i in range(-6, 6):\n", "\n", " events_matrix1 = []\n", "\n", " for e in events_matrix:\n", "\n", " ev = copy.deepcopy(e)\n", "\n", " if e[0] == 'note':\n", " if e[3] == 9:\n", " ev[4] = ((e[4] % 128) + 128)\n", " else:\n", " ev[4] = ((e[4] % 128) + i)\n", "\n", " events_matrix1.append(ev)\n", "\n", " pitches_counts = [[y[0],y[1]] for y in Counter([y[4] for y in events_matrix1 if y[0] == 'note']).most_common()]\n", " pitches_counts.sort(key=lambda x: x[0], reverse=True)\n", "\n", " mult_pitches_counts.append(pitches_counts)\n", "\n", " patches_list = sorted(list(set([y[3] for y in events_matrix if y[0] == 'patch_change'])))\n", "\n", " #==================================================\n", "\n", " ms_score = TMIDIX.midi2ms_score(open(f, 'rb').read())\n", "\n", " ms_events_matrix = []\n", "\n", " itrack1 = 1\n", "\n", " while itrack1 < len(ms_score):\n", " for event in ms_score[itrack1]:\n", " if event[0] == 'note':\n", " ms_events_matrix.append(event)\n", " itrack1 += 1\n", "\n", " ms_events_matrix.sort(key=lambda x: x[1])\n", "\n", "\n", " chords = []\n", " pe = ms_events_matrix[0]\n", " cho = []\n", " for e in ms_events_matrix:\n", " if (e[1] - pe[1]) == 0:\n", " if e[3] != 9:\n", " if (e[4] % 12) not in cho:\n", " cho.append(e[4] % 12)\n", " else:\n", " if len(cho) > 0:\n", " chords.append(sorted(cho))\n", " cho = []\n", " if e[3] != 9:\n", " if (e[4] % 12) not in cho:\n", " cho.append(e[4] % 12)\n", "\n", " pe = e\n", "\n", " if len(cho) > 0:\n", " chords.append(sorted(cho))\n", "\n", " ms_chords_counts = sorted([[list(key), val] for key,val in Counter([tuple(c) for c in chords if len(c) > 1]).most_common()], reverse=True, key = lambda x: x[1])\n", "\n", " times = []\n", " pt = ms_events_matrix[0][1]\n", " start = True\n", " for e in ms_events_matrix:\n", " if (e[1]-pt) != 0 or start == True:\n", " times.append((e[1]-pt))\n", " start = False\n", " pt = e[1]\n", "\n", " durs = [e[2] for e in ms_events_matrix]\n", " vels = [e[5] for e in ms_events_matrix]\n", "\n", " avg_time = int(sum(times) / len(times))\n", " avg_dur = int(sum(durs) / len(durs))\n", "\n", " mode_time = statistics.mode(times)\n", " mode_dur = statistics.mode(durs)\n", "\n", " median_time = int(statistics.median(times))\n", " median_dur = int(statistics.median(durs))\n", "\n", " #=======================================================\n", "\n", " print('Searching for matches...Please wait...')\n", " print('-' * 70)\n", "\n", " final_ratios = []\n", "\n", " for d in tqdm(meta_data):\n", "\n", " p_counts = d[1][10][1]\n", " p_counts.sort(reverse = True, key = lambda x: x[1])\n", " max_p_count = p_counts[0][1]\n", " trimmed_p_counts = [y for y in p_counts if y[1] >= (max_p_count * pitches_counts_cutoff_threshold_ratio)]\n", " total_p_counts = sum([y[1] for y in trimmed_p_counts])\n", "\n", " if search_transposed_pitches:\n", " search_pitches = mult_pitches_counts\n", " else:\n", " search_pitches = [mult_pitches_counts[6]]\n", "\n", " #===================================================\n", "\n", " ratios_list = []\n", "\n", " #===================================================\n", "\n", " atrat = [0]\n", "\n", " if add_timings_ratios:\n", "\n", " source_times = [avg_time,\n", " median_time,\n", " mode_time]\n", "\n", " match_times = meta_data[0][1][3][1]\n", "\n", " times_ratios = []\n", "\n", " for i in range(len(source_times)):\n", " maxtratio = max(source_times[i], match_times[i])\n", " mintratio = min(source_times[i], match_times[i])\n", " times_ratios.append(mintratio / maxtratio)\n", "\n", " avg_times_ratio = sum(times_ratios) / len(times_ratios)\n", "\n", " atrat[0] = avg_times_ratio\n", "\n", " #===================================================\n", "\n", " adrat = [0]\n", "\n", " if add_durations_ratios:\n", "\n", " source_durs = [avg_dur,\n", " median_dur,\n", " mode_dur]\n", "\n", " match_durs = meta_data[0][1][4][1]\n", "\n", " durs_ratios = []\n", "\n", " for i in range(len(source_durs)):\n", " maxtratio = max(source_durs[i], match_durs[i])\n", " mintratio = min(source_durs[i], match_durs[i])\n", " durs_ratios.append(mintratio / maxtratio)\n", "\n", " avg_durs_ratio = sum(durs_ratios) / len(durs_ratios)\n", "\n", " adrat[0] = avg_durs_ratio\n", "\n", " #===================================================\n", "\n", " for m in search_pitches:\n", "\n", " sprat = []\n", "\n", " m.sort(reverse = True, key = lambda x: x[1])\n", " max_pitches_count = m[0][1]\n", " trimmed_pitches_counts = [y for y in m if y[1] >= (max_pitches_count * pitches_counts_cutoff_threshold_ratio)]\n", " total_pitches_counts = sum([y[1] for y in trimmed_pitches_counts])\n", "\n", " same_pitches = set([T[0] for T in trimmed_p_counts]) & set([m[0] for m in trimmed_pitches_counts])\n", " num_same_pitches = len(same_pitches)\n", "\n", " if num_same_pitches == len(trimmed_pitches_counts):\n", " same_pitches_ratio = (num_same_pitches / len(trimmed_p_counts))\n", " else:\n", " same_pitches_ratio = (num_same_pitches / max(len(trimmed_p_counts), len(trimmed_pitches_counts)))\n", "\n", " if skip_exact_matches:\n", " if same_pitches_ratio == 1:\n", " same_pitches_ratio = 0\n", "\n", " sprat.append(same_pitches_ratio)\n", "\n", " #===================================================\n", "\n", " spcrat = [0]\n", "\n", " if add_pitches_counts_ratios:\n", "\n", " same_trimmed_p_counts = sorted([T for T in trimmed_p_counts if T[0] in same_pitches], reverse = True)\n", " same_trimmed_pitches_counts = sorted([T for T in trimmed_pitches_counts if T[0] in same_pitches], reverse = True)\n", "\n", " same_trimmed_p_counts_ratios = [[s[0], s[1] / total_p_counts] for s in same_trimmed_p_counts]\n", " same_trimmed_pitches_counts_ratios = [[s[0], s[1] / total_pitches_counts] for s in same_trimmed_pitches_counts]\n", "\n", " same_pitches_counts_ratios = []\n", "\n", " for i in range(len(same_trimmed_p_counts_ratios)):\n", " mincratio = min(same_trimmed_p_counts_ratios[i][1], same_trimmed_pitches_counts_ratios[i][1])\n", " maxcratio = max(same_trimmed_p_counts_ratios[i][1], same_trimmed_pitches_counts_ratios[i][1])\n", " same_pitches_counts_ratios.append([same_trimmed_p_counts_ratios[i][0], mincratio / maxcratio])\n", "\n", " same_counts_ratios = [s[1] for s in same_pitches_counts_ratios]\n", "\n", " if len(same_counts_ratios) > 0:\n", " avg_same_pitches_counts_ratio = sum(same_counts_ratios) / len(same_counts_ratios)\n", " else:\n", " avg_same_pitches_counts_ratio = 0\n", "\n", " spcrat[0] = avg_same_pitches_counts_ratio\n", "\n", " #===================================================\n", "\n", " r_list = [sprat[0]]\n", "\n", " if add_pitches_counts_ratios:\n", " r_list.append(spcrat[0])\n", "\n", " if add_timings_ratios:\n", " r_list.append(atrat[0])\n", "\n", " if add_durations_ratios:\n", " r_list.append(adrat[0])\n", "\n", " ratios_list.append(r_list)\n", "\n", " #===================================================\n", "\n", " avg_ratios_list = []\n", "\n", " for r in ratios_list:\n", " avg_ratios_list.append(sum(r) / len(r))\n", "\n", " #===================================================\n", "\n", " final_ratio = max(avg_ratios_list)\n", "\n", " if final_ratio > maximum_match_ratio_to_search_for:\n", " final_ratio = 0\n", "\n", " final_ratios.append(final_ratio)\n", "\n", " #=======================================================\n", "\n", " print('-' * 70)\n", "\n", " max_ratios = sorted(set(final_ratios), reverse=True)[:number_of_top_ratios_MIDIs_to_collect]\n", "\n", " print('Max match ratio', max_ratios[0])\n", " print('-' * 70)\n", " print('Copying max ratios MIDIs...')\n", "\n", " for m in max_ratios:\n", "\n", " max_ratio_index = final_ratios.index(m)\n", "\n", " ffn = meta_data[max_ratio_index][0]\n", " ffn_idx = [y[0] for y in LAMD_files_list].index(ffn)\n", "\n", " ff = LAMD_files_list[ffn_idx][1]\n", "\n", " #=======================================================\n", "\n", " dir_str = str(fn1)\n", " copy_path = '/content/Output-MIDI-Dataset/'+dir_str\n", " if not os.path.exists(copy_path):\n", " os.mkdir(copy_path)\n", "\n", " fff = str(m * 100) + '_' + ffn + '.mid'\n", "\n", " shutil.copy2(ff, copy_path+'/'+fff)\n", "\n", " shutil.copy2(f, copy_path+'/'+fn)\n", "\n", " #=======================================================\n", "\n", " print('Done!')\n", " print('=' * 70)\n", "\n", " #=======================================================\n", "\n", " # Processed files counter\n", " files_count += 1\n", "\n", " except KeyboardInterrupt:\n", " print('Quitting...')\n", " print('Total number of processed MIDI files', files_count)\n", " print('=' * 70)\n", " break\n", "\n", " except Exception as ex:\n", " print('WARNING !!!')\n", " print('=' * 70)\n", " print('Bad file:', f)\n", " print('Error detected:', ex)\n", " print('=' * 70)\n", " continue\n", "\n", "print('Total number of processed MIDI files', files_count)\n", "print('=' * 70)" ], "metadata": { "cellView": "form", "id": "M0JWCPzBGNvh" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "YzCMd94Tu_gz" }, "source": [ "# Congrats! You did it! :)" ] } ], "metadata": { "colab": { "machine_shape": "hm", "private_outputs": true, "provenance": [] }, "gpuClass": "standard", "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.7" } }, "nbformat": 4, "nbformat_minor": 0 }