<commit_before>"""
Machine learning music
"""

import numpy as np
from scipy.integrate import trapz
from scipy.io import wavfile
import jack
import tensorflow as tf
from pylab import plot, show 

class MuserJACK():
    """ Manages a JACK client for Muser """
    def __init__(self, midi_ins=1, midi_outs=1, name="MuserClient"):
        self.client = jack.Client(name)
        self.midi_in = [client.midi_inports.register("midi_in_{}".format(j)) for j in range(midi_ins)]
        self.midi_out = [client.midi_outports.register("midi_out_{}".format(k)) for k in range(midi_outs)]
        activate()
    
    def activate(self):
        client.activate()
    def deactivate(self):
        client.deactivate()
    def close():
        client.close()
        
def f(t):
    try:
        return [int(p * sf) for p in t]
    except TypeError:
        return int(t * sf)

def scale_wav(snd, factor=None):
    # scale signal from -1 to 1
    if factor:
        return snd/factor
    else:
        return scale_wav(snd, 2.**15 if snd.dtype == np.dtype('int16') else 2.**31) 
        
# x = snd.shape[0]             # number of sample points (duration * rate)
# t = np.arange(0, x, 1) / sf  # sample points as time points (seconds)

def local_fft(chs, f0, f1, norm="ortho"):
    # calculate FFTs for each channel over the interval
    return np.stack(np.fft.fft(ch[f0:f1], norm=norm) for ch in chs)

# import contents of wav file
sf, snd = wavfile.read('op28-20.wav')
snd = scale_wav(snd)

t0, t1 = (0.5, 1.0)
w = local_fft(snd.T, f(t0), f(t1))

n = (w.shape[1] // 2) + 1
w_a = abs(w)[:][0:n]
w_pwr = w_a ** 2 
frqs = np.fft.fftfreq(f(t1) - f(t0))
frqs_a = abs(sf * frqs)[0:n]   # Hz

frq_max = 5000 # Frequency cutoff
cut = np.where(frqs_a > frq_max)[0][0] 
plot(frqs_a[0:cut], w_pwr[0][0:cut])
show()

# print(sum(ws_p[1]))
<commit_msg>Almost everything inside functions. Several stylistic improvements.<commit_after>"""
Machine learning music
"""

import numpy as np
import tensorflow as tf
import jack
from scipy.io import wavfile
import peakutils
from matplotlib import pyplot

# Datatypes that SciPy can import from .wav
snd_dtypes = {'int16': 16-1, 'int32': 32-1}
wav_name = 'op28-20.wav'

def jack_client(midi_ins=1, midi_outs=1, name="MuserClient"):
    """ Returns an active JACK client with specified number of inputs and outputs """
    client = jack.Client(name)
    for j in range(midi_ins):
        client.midi_inports.register("midi_in_{}".format(j))
    for k in range(midi_outs):
        client.midi_outports.register("midi_out_{}".format(k))
    client.activate()
    return client


def get_to_f(sf):
    """ Return function that converts time (is s if sf is Hz) to sample index
        for a defined sampling rate.
    """
    def to_f(t):
        try:
            return [int(p * sf) for p in t]
        except TypeError:
            return int(t * sf)

    return to_f

    
def scale_snd(snd, factor=None):
    """ Scale signal from -1 to 1 
    """
    if factor is None:
        return scale_snd(snd, 2.**snd_dtypes[snd.dtype.name])
    else:
        return snd / factor
        

def local_fft(chs, f0, f1, norm="ortho"):
    """ Calculate FFTs for each channel over the interval 
    """
    return np.stack(np.fft.rfft(ch[f0:f1], norm=norm) for ch in chs)


def main():

    # x = snd.shape[0]             # number of sample points (duration * rate)
    # t = np.arange(0, x, 1) / sf  # sample points as time points (seconds)
    
    # import contents of wav file
    sf, snd = wavfile.read(wav_name)
    snd = scale_snd(snd)

    to_f = get_to_f(sf)
    
    t_endp = (0.5, 1.0)
    f_endp = to_f(t_endp)
    # total number of frames should be even
    f_endp[1] += sum(f_endp) % 2

    amp = local_fft(snd.T, *f_endp)
    w_sq = abs(amp) ** 2
    w_pwr = 10. * np.log10(w_sq) # dB
    frq = np.fft.fftfreq(f_endp[1] - f_endp[0])
    frq_a = abs(sf * frq)[0:amp.shape[1]]   # Hz

    thres = 0.01  # peak detection threshold as factor of w_max
    peaks = peakutils.indexes(w_pwr[0], thres=thres)
    peak_frq = frq_a[peaks]
    peak_w = w_pwr[0, peaks]

    w_max = max(w_pwr[0])
    pyplot.plot(frq_a, w_pwr[0], 'k-')
    pyplot.plot(peak_frq, peak_w+1, 'r.')
    pyplot.axis([0, peak_frq[-1] * 1.1, 0, w_max + 5])
    pyplot.xlabel('Hz')
    pyplot.ylabel('dB')
    pyplot.show()

{'fraction_non_alphanumeric': 0.13757843365094122, 'fraction_numerical': 0.02416918429003021, 'mean_word_length': 2.85663082437276, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 4, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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}}
{'dir': 'git-commits-cleaned', 'id': '5333594', 'n_tokens_mistral': 1722, 'n_tokens_neox': 1663, 'n_words': 437}