{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "private_outputs": true,
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "# MIDI Images Solo Piano Dataset Maker (ver. 1.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 2024\n",
        "\n",
        "***"
      ],
      "metadata": {
        "id": "LUgrspEA-68o"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "# (SETUP ENVIRONMENT)"
      ],
      "metadata": {
        "id": "7N-KXNgQ_a0h"
      }
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "pxNxlyfZ8hCg",
        "cellView": "form"
      },
      "outputs": [],
      "source": [
        "# @title Install dependecies\n",
        "!git clone --depth 1 https://github.com/asigalov61/tegridy-tools"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "#@title Import all needed modules\n",
        "\n",
        "print('=' * 70)\n",
        "print('Loading core modules...')\n",
        "print('Please wait...')\n",
        "print('=' * 70)\n",
        "\n",
        "import os\n",
        "import copy\n",
        "import math\n",
        "import statistics\n",
        "import random\n",
        "import pickle\n",
        "import shutil\n",
        "from itertools import groupby\n",
        "from collections import Counter\n",
        "from sklearn.metrics import pairwise_distances\n",
        "from sklearn import metrics\n",
        "from joblib import Parallel, delayed, parallel_config\n",
        "import numpy as np\n",
        "from tqdm import tqdm\n",
        "from PIL import Image\n",
        "import matplotlib.pyplot as plt\n",
        "\n",
        "print('Done!')\n",
        "print('=' * 70)\n",
        "print('Creating I/O dirs...')\n",
        "\n",
        "if not os.path.exists('/content/Dataset'):\n",
        "    os.makedirs('/content/Dataset')\n",
        "\n",
        "print('Done!')\n",
        "print('=' * 70)\n",
        "print('Loading tegridy-tools modules...')\n",
        "print('=' * 70)\n",
        "\n",
        "%cd /content/tegridy-tools/tegridy-tools\n",
        "\n",
        "import TMIDIX\n",
        "import TMELODIES\n",
        "import TPLOTS\n",
        "import HaystackSearch\n",
        "\n",
        "%cd /content/\n",
        "\n",
        "print('=' * 70)\n",
        "print('Done!')\n",
        "print('=' * 70)"
      ],
      "metadata": {
        "id": "OblKfMMT8rfM",
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# (DOWNLOAD SAMPLE MIDI DATASET)"
      ],
      "metadata": {
        "id": "gUXM7WsN_ioe"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# @title Download sample MIDI dataset (POP909)\n",
        "%cd /content/Dataset/\n",
        "!git clone --depth 1 https://github.com/music-x-lab/POP909-Dataset\n",
        "%cd /content/"
      ],
      "metadata": {
        "id": "JLm4OmOUYlEK",
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "#@title Save file list\n",
        "###########\n",
        "\n",
        "print('=' * 70)\n",
        "print('Loading MIDI files...')\n",
        "print('This may take a while on a large dataset in particular...')\n",
        "\n",
        "dataset_addr = '/content/Dataset/'\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 if file.endswith('.mid') or file.endswith('.midi') or file.endswith('.kar')]\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('Done!')\n",
        "print('=' * 70)\n",
        "print('Total found MIDI files:', len(filez))\n",
        "print('=' * 70)\n",
        "\n",
        "TMIDIX.Tegridy_Any_Pickle_File_Writer(filez, 'filez')\n",
        "\n",
        "print('=' * 70)"
      ],
      "metadata": {
        "cellView": "form",
        "id": "AJrFrZ9grhMM"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# (LOAD TMIDIX MIDI PROCESSOR)"
      ],
      "metadata": {
        "id": "RJeTdierAbeF"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "#@title Load TMIDIX MIDI processor\n",
        "\n",
        "print('=' * 70)\n",
        "print('TMIDIX MIDI Processor')\n",
        "print('=' * 70)\n",
        "print('Loading...')\n",
        "\n",
        "###########\n",
        "\n",
        "def TMIDIX_MIDI_Processor(midi_file):\n",
        "\n",
        "    fn = os.path.basename(midi_file)\n",
        "    fn1 = fn.split('.mid')[0]\n",
        "\n",
        "    try:\n",
        "\n",
        "        #=======================================================\n",
        "        # START PROCESSING\n",
        "\n",
        "        raw_score = TMIDIX.midi2single_track_ms_score(midi_file)\n",
        "\n",
        "        escore_notes = TMIDIX.advanced_score_processor(raw_score, return_enhanced_score_notes=True)[0]\n",
        "\n",
        "        escore_notes = TMIDIX.augment_enhanced_score_notes(escore_notes, timings_divider=256)\n",
        "\n",
        "        sp_escore_notes = TMIDIX.recalculate_score_timings(TMIDIX.solo_piano_escore_notes(escore_notes, keep_drums=False))\n",
        "\n",
        "        if sp_escore_notes:\n",
        "\n",
        "            bmatrix = TMIDIX.escore_notes_to_binary_matrix(sp_escore_notes)\n",
        "\n",
        "            return [fn1, bmatrix]\n",
        "\n",
        "        else:\n",
        "            return [fn1, []]\n",
        "\n",
        "        #=======================================================\n",
        "\n",
        "    except Exception as ex:\n",
        "        print('WARNING !!!')\n",
        "        print('=' * 70)\n",
        "        print('Bad MIDI:', midi_file)\n",
        "        print('Error detected:', ex)\n",
        "        print('=' * 70)\n",
        "        return None\n",
        "\n",
        "print('Done!')\n",
        "print('=' * 70)"
      ],
      "metadata": {
        "cellView": "form",
        "id": "fBbIiUWSZA5y"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# (PROCESS MIDIs)"
      ],
      "metadata": {
        "id": "R3QxQN6OA_jX"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "#@title Process MIDIs with TMIDIX MIDI processor\n",
        "output_folder = \"/content/MIDI-Images/\" # @param {\"type\":\"string\"}\n",
        "\n",
        "NUMBER_OF_PARALLEL_JOBS = 4 # Number of parallel jobs\n",
        "NUMBER_OF_FILES_PER_ITERATION = 4 # Number of files to queue for each parallel iteration\n",
        "SAVE_EVERY_NUMBER_OF_ITERATIONS = 128 # Save every 2560 files\n",
        "\n",
        "print('=' * 70)\n",
        "print('TMIDIX MIDI Processor')\n",
        "print('=' * 70)\n",
        "print('Starting up...')\n",
        "print('=' * 70)\n",
        "\n",
        "###########\n",
        "\n",
        "melody_chords_f = []\n",
        "\n",
        "files_count = 0\n",
        "\n",
        "print('Processing MIDI files...')\n",
        "print('Please wait...')\n",
        "print('=' * 70)\n",
        "\n",
        "for i in tqdm(range(0, len(filez), NUMBER_OF_FILES_PER_ITERATION)):\n",
        "\n",
        "  with parallel_config(backend='threading', n_jobs=NUMBER_OF_PARALLEL_JOBS, verbose = 0):\n",
        "\n",
        "    output = Parallel(n_jobs=NUMBER_OF_PARALLEL_JOBS, verbose=0)(delayed(TMIDIX_MIDI_Processor)(f) for f in filez[i:i+NUMBER_OF_FILES_PER_ITERATION])\n",
        "\n",
        "    for o in output:\n",
        "\n",
        "        if o is not None:\n",
        "            melody_chords_f.append(o)\n",
        "\n",
        "    if i % (NUMBER_OF_FILES_PER_ITERATION * SAVE_EVERY_NUMBER_OF_ITERATIONS) == 0 and i != 0:\n",
        "\n",
        "        print('SAVING !!!')\n",
        "        print('=' * 70)\n",
        "        print('Saving processed files...')\n",
        "        files_count += len(melody_chords_f)\n",
        "        print('=' * 70)\n",
        "        print('Processed so far:', files_count, 'out of', len(filez), '===', files_count / len(filez), 'good files ratio')\n",
        "        print('=' * 70)\n",
        "        print('Writing images...')\n",
        "        print('Please wait...')\n",
        "\n",
        "        for mat in melody_chords_f:\n",
        "\n",
        "          if mat[1]:\n",
        "\n",
        "            TPLOTS.binary_matrix_to_images(mat[1],\n",
        "                                            128,\n",
        "                                            32,\n",
        "                                            output_folder=output_folder+str(mat[0])+'/',\n",
        "                                            output_img_prefix=str(mat[0]),\n",
        "                                            output_img_ext='.png',\n",
        "                                            verbose=False\n",
        "                                            )\n",
        "\n",
        "        print('Done!')\n",
        "        print('=' * 70)\n",
        "        melody_chords_f = []\n",
        "\n",
        "print('SAVING !!!')\n",
        "print('=' * 70)\n",
        "print('Saving processed files...')\n",
        "files_count += len(melody_chords_f)\n",
        "print('=' * 70)\n",
        "print('Processed so far:', files_count, 'out of', len(filez), '===', files_count / len(filez), 'good files ratio')\n",
        "print('=' * 70)\n",
        "print('Writing images...')\n",
        "print('Please wait...')\n",
        "\n",
        "for mat in melody_chords_f:\n",
        "\n",
        "  if mat[1]:\n",
        "\n",
        "    TPLOTS.binary_matrix_to_images(mat[1],\n",
        "                                    128,\n",
        "                                    32,\n",
        "                                    output_folder=output_folder+str(mat[0])+'/',\n",
        "                                    output_img_prefix=str(mat[0]),\n",
        "                                    output_img_ext='.png',\n",
        "                                    verbose=False\n",
        "                                    )\n",
        "\n",
        "print('Done!')\n",
        "print('=' * 70)"
      ],
      "metadata": {
        "cellView": "form",
        "id": "15y4uzSOZX52"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# (LOAD IMAGES)"
      ],
      "metadata": {
        "id": "GtejvUFAFocZ"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "#@title Load created MIDI images\n",
        "full_path_to_metadata_pickle_files = \"/content/MIDI-Images\" #@param {type:\"string\"}\n",
        "\n",
        "print('=' * 70)\n",
        "print('MIDI Images Reader')\n",
        "print('=' * 70)\n",
        "print('Searching for images...')\n",
        "\n",
        "filez = list()\n",
        "for (dirpath, dirnames, filenames) in os.walk(full_path_to_metadata_pickle_files):\n",
        "    filez += [os.path.join(dirpath, file) for file in filenames if file.endswith('.png')]\n",
        "print('=' * 70)\n",
        "\n",
        "filez.sort()\n",
        "\n",
        "print('Found', len(filez), 'images!')\n",
        "print('=' * 70)\n",
        "print('Reading images...')\n",
        "print('Please wait...')\n",
        "print('=' * 70)\n",
        "\n",
        "fidx = 0\n",
        "\n",
        "all_read_images = []\n",
        "\n",
        "for img in tqdm(filez):\n",
        "\n",
        "    img = Image.open(img)\n",
        "\n",
        "    img_arr = np.array(img).tolist()\n",
        "\n",
        "    all_read_images.append(img_arr)\n",
        "\n",
        "    fidx += 1\n",
        "\n",
        "print('Done!')\n",
        "print('=' * 70)\n",
        "print('Loaded', fidx, 'images!')\n",
        "print('=' * 70)\n",
        "print('Done!')\n",
        "print('=' * 70)"
      ],
      "metadata": {
        "cellView": "form",
        "id": "cXpLWHG1dBB3"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# (TEST IMAGES)"
      ],
      "metadata": {
        "id": "qbClHSmhB1NF"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# @title Test created MIDI images\n",
        "\n",
        "print('=' * 70)\n",
        "\n",
        "image = random.choice(all_read_images)\n",
        "\n",
        "escore = TMIDIX.binary_matrix_to_original_escore_notes(image)\n",
        "\n",
        "output_score, patches, overflow_patches = TMIDIX.patch_enhanced_score_notes(escore)\n",
        "\n",
        "detailed_stats = TMIDIX.Tegridy_ms_SONG_to_MIDI_Converter(output_score,\n",
        "                                                          output_signature = 'MIDI Images',\n",
        "                                                          output_file_name = '/content/MIDI-Images-Composition',\n",
        "                                                          track_name='Project Los Angeles',\n",
        "                                                          list_of_MIDI_patches=patches,\n",
        "                                                          timings_multiplier=256\n",
        "                                                          )\n",
        "\n",
        "print('=' * 70)"
      ],
      "metadata": {
        "id": "nrPDM1VQdKES",
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# (ZIP IMAGES)"
      ],
      "metadata": {
        "id": "sIq55gvPCgJh"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# @title Zip created MIDI images\n",
        "!zip -9 -r POP909_MIDI_Images_128_128_32_BW.zip MIDI-Images/ > /dev/null"
      ],
      "metadata": {
        "id": "tVe0REKSqJeV",
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Congrats! You did it! :)"
      ],
      "metadata": {
        "id": "iDdMYg4haGFn"
      }
    }
  ]
}