<jupyter_start><jupyter_text>This is the Python code used to convert .wav files to spectrogramsAudio data is from this [Kaggle dataset](https://www.kaggle.com/c/freesound-audio-tagging/data), which is from this [DCASE 2018 paper](https://arxiv.org/abs/1807.09902).<jupyter_code>import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
from scipy import signal
from scipy.io import wavfile
prefix = 'gs://path/to/audio/files'
spectro_prefix = 'gs://path/to/spectrograms'

for i in range(len(names)):
    fname = prefix + names[i]
    !gsutil cp $fname .

    # Create spectrogram with scipy
    sample_rate, samples = wavfile.read(names[i])
    freq, times, spectro = signal.spectrogram(samples, sample_rate)
    
    # Create specrogram image with matplotlib
    plt.figure(figsize=(28,28), frameon=False)
    fig = plt.gcf()
    plt.axis('off')
    plt.pcolormesh(times, freq, np.log(spectro))

    # Save spectrogram to local file
    name = names[i].split('.')[0]
    fig.savefig(name)
    spectro_path = spectro_prefix + name + '.png'
    local_path = name + '.png'

    # Convert image to 3 channels and shrink
    im = Image.open(local_path)
    im.thumbnail((128,128), Image.ANTIALIAS)
    im.convert(mode='RGB')
    im.save(local_path)

    # Save spectrogram to GCS and remove local files
    !gsutil cp $local_path $spectro_path
    !rm $local_path
    local_audio = names[i]
    !rm $local_audio<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11707988980716254, 'fraction_numerical': 0.01721763085399449, 'mean_word_length': 3.7483660130718954, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 2, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '650882', 'license': 'Apache-2.0', 'n_tokens_mistral': 534, 'n_tokens_neox': 508, 'n_words': 129, 'path': '05_resilience/audio_to_spectro.ipynb', 'repo_name': 'modoai/ml-design-patterns', 'size': '1452'}