# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     name: python3
# ---

# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/darshana-22/Music-Genre-Classification/blob/main/Preparing_the_dataset.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>

# + id="YsWr2bshKkMe"
import pandas as pd
import numpy as np
import math
import json
import matplotlib.pyplot as plt
import scipy
import sys
import os
import pickle
import librosa
import librosa.display
from IPython.display import Audio
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
import tensorflow as tf
from tensorflow import keras

# + colab={"base_uri": "https://localhost:8080/"} id="NQL4Q524QQ-U" outputId="72a4f391-e6aa-40b0-b68d-c13345cf7c7c"
from google.colab import drive
drive.mount('/content/drive')

# + id="-7TjS_cuQNL0"
# !unzip "/content/drive/MyDrive/Data.zip"

# + id="JrS9g5gwh0dz"
DATASET_PATH = "/content/genres_original"
JSON_PATH = "data.json"
SAMPLE_RATE = 22050
DURATION = 30 # in seconds
SAMPLES_PER_TRACK = SAMPLE_RATE * DURATION


# + id="yxo4c0ZdYdfv"
def save_mfcc(dataset_path, json_path, n_mfcc=13, n_fft=2048, hop_length=512, num_segments=5):
  # dictionary to store data
  data={
      "mapping": [],
      "mfcc":[],
      "labels": []
  }
  num_samples_per_segment = int (SAMPLES_PER_TRACK / num_segments)
  expected_num_mfcc_vectors_per_segment = math.ceil(num_samples_per_segment/ hop_length)

  for i, (dirpath, dirnames, filenames) in enumerate (os.walk(dataset_path)):
    if dirpath is not dataset_path:
      # save the semantic label
      dirpath_components = dirpath.split("/")
      semantic_label = dirpath_components[-1]
      data["mapping"].append(semantic_label)
      print("\nprocessing {}".format(semantic_label))

      for f in filenames:
        #loading audio file
        file_path = os.path.join(dirpath, f)
        signal, sr = librosa.load(file_path, sr= SAMPLE_RATE)

        # process segments extracting mfcc and storing data
        for s in range(num_segments):
          start_sample = num_samples_per_segment * s
          finish_sample = start_sample + num_samples_per_segment


          mfcc = librosa.feature.mfcc(signal[start_sample:finish_sample],
                                      sr = sr,
                                      n_fft = n_fft,
                                      n_mfcc = n_mfcc ,
                                      hop_length = hop_length)
          
          
          mfcc = mfcc.T
          if len(mfcc) == expected_num_mfcc_vectors_per_segment:
            data["mfcc"].append(mfcc.tolist())
            data["labels"].append(i-1)
            print("{}, segment:{}".format(file_path, s+1))

  with open(json_path, "w") as fp:
     json.dump(data, fp, indent=4)   






# + id="pPaL9vflv865"
save_mfcc(DATASET_PATH, JSON_PATH, num_segments=10)

StarcoderdataJupyterScriptsDedupFiltered