<jupyter_start><jupyter_text>Helper functions<jupyter_code># From https://github.com/mdeff/fma/blob/master/utils.py

def get_audio_path(audio_dir, track_id):
    """
    Return the path to the mp3 given the directory where the audio is stored
    and the track ID.
    Examples
    --------
    >>> import utils
    >>> AUDIO_DIR = os.environ.get('AUDIO_DIR')
    >>> utils.get_audio_path(AUDIO_DIR, 2)
    '../data/fma_small/000/000002.mp3'
    """
    tid_str = '{:06d}'.format(track_id)
    return os.path.join(audio_dir, tid_str[:3], tid_str + '.mp3')


def get_tids_from_directory(audio_dir):
    """Get track IDs from the mp3s in a directory.
    Parameters
    ----------
    audio_dir : str
        Path to the directory where the audio files are stored.
    Returns
    -------
        A list of track IDs.
    """
    tids = []
    for _, dirnames, files in os.walk(audio_dir):
        if dirnames == []:
            tids.extend(int(file[:-4]) for file in files)
    return tids
tids = get_tids_from_directory(AUDIO_DIR)
tids[:10]
get_audio_path(AUDIO_DIR, 255)<jupyter_output><empty_output><jupyter_text>Read in metadata<jupyter_code>tracks = pd.read_csv(META_DIR/'tracks.csv', index_col=0, header=[0, 1]) 
tracks.head(2)
keep_cols = [('set', 'split'),
('set', 'subset'),('track', 'genre_top')]

df_all = tracks[keep_cols]
df_all = df_all[df_all[('set', 'subset')] == 'small']
df_all['track_id'] = df_all.index
df_all.head()
df_all.shape
df_all[('track', 'genre_top')].value_counts()<jupyter_output><empty_output><jupyter_text>Pick genres<jupyter_code>rock = (df_all[('track', 'genre_top')]=='Rock')
inst = (df_all[('track', 'genre_top')]=='Instrumental')
hiphop = (df_all[('track', 'genre_top')]=='Hip-Hop')
mask = rock | inst | hiphop
genres = df_all[mask]
genres.head()
genres[('track', 'genre_top')].value_counts()<jupyter_output><empty_output><jupyter_text>Plot Spectrograms<jupyter_code># From https://github.com/priya-dwivedi/Music_Genre_Classification/blob/master/Plot_Spectograms.ipynb

def plot_spectrogram(track_id, genre):
    filename = get_audio_path(AUDIO_DIR, track_id)
    y, sr = librosa.load(filename)
    print(len(y),sr)
    spect = librosa.feature.melspectrogram(y=y, sr=sr,n_fft=2048, hop_length=512)
    spect = librosa.power_to_db(spect, ref=np.max)
#     spect = np.log(spect)
    print(spect.shape, genre)
    plt.figure(figsize=(10, 4))
    librosa.display.specshow(spect, y_axis='mel', fmax=8000, x_axis='time')
    plt.colorbar(format='%+2.0f dB')
    plt.title(str(genre))
plot_spectrogram(2, "Hip-Hop")
plot_spectrogram(255, "Rock")
plot_spectrogram(14569, "Instrumental")<jupyter_output>/anaconda3/envs/genre/lib/python3.7/site-packages/librosa/core/audio.py:146: UserWarning: PySoundFile failed. Trying audioread instead.
  warnings.warn('PySoundFile failed. Trying audioread instead.')
{'fraction_non_alphanumeric': 0.1635464500176616, 'fraction_numerical': 0.020487460261391734, 'mean_word_length': 4.619047619047619, 'pattern_counts': {'":': 0, '<': 16, '<?xml version=': 0, '>': 25, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '364319', 'license': 'MIT', 'n_tokens_mistral': 1141, 'n_tokens_neox': 1090, 'n_words': 183, 'path': 'nbs/explore_data.ipynb', 'repo_name': 'anthonybaulo/music-genre-classification', 'size': '2831'}