<jupyter_start><jupyter_text>CycleGAN<jupyter_code>img = imread('01.png')
img.shape
X = img.mean(axis=2)
X.shape
X.diagonal()
X = X.T**8
def reconstruct_signal_griffin_lim(magnitude_spectrogram, fft_size, hopsamp, iterations):
    print("magnitude_spectrogram: "+str(magnitude_spectrogram.shape))
    time_slices = magnitude_spectrogram.shape[0]
    print("time_slices: "+str(time_slices))
    len_samples = int(time_slices*hopsamp + fft_size)
    print("len_samples: "+str(len_samples))

    x_reconstruct = np.random.randn(len_samples)
    print("x_reconstruct: "+str(x_reconstruct.shape))
    n = iterations # number of iterations of Griffin-Lim algorithm.
    while n > 0:
        n -= 1
        reconstruction_spectrogram = stft_for_reconstruction(x_reconstruct, fft_size, hopsamp)
        print("reconstruction_spectrogram: "+str(reconstruction_spectrogram.shape))
        reconstruction_angle = np.angle(reconstruction_spectrogram)
        print("reconstruction_angle: "+str(reconstruction_angle.shape))
        # Discard magnitude part of the reconstruction and use the supplied magnitude spectrogram instead.
        proposal_spectrogram = magnitude_spectrogram*np.exp(1.0j*reconstruction_angle)
        prev_x = x_reconstruct
        x_reconstruct = istft_for_reconstruction(proposal_spectrogram, fft_size, hopsamp)
        diff = sqrt(sum((x_reconstruct - prev_x)**2)/x_reconstruct.size)
        print('Reconstruction iteration: {}/{} RMSE: {} '.format(iterations - n, iterations, diff))
    return x_reconstruct
x_reconstruct = reconstruct_signal_griffin_lim(mag, fft_size, hopsamp, 300)<jupyter_output>magnitude_spectrogram: (560, 1025)
time_slices: 560
len_samples: 145408
x_reconstruct: (145408,)
reconstruction_spectrogram: (560, 1025)
reconstruction_angle: (560, 1025)
Reconstruction iteration: 1/300 RMSE: 6.73472591812 
reconstruction_spectrogram: (560, 1025)
reconstruction_angle: (560, 1025)
Reconstruction iteration: 2/300 RMSE: 2.06384293951 
reconstruction_spectrogram: (560, 1025)
reconstruction_angle: (560, 1025)
Reconstruction iteration: 3/300 RMSE: 1.17200107943 
reconstruction_spectrogram: (560, 1025)
reconstruction_angle: (560, 1025)
Reconstruction iteration: 4/300 RMSE: 0.879795098879 
reconstruction_spectrogram: (560, 1025)
reconstruction_angle: (560, 1025)
Reconstruction iteration: 5/300 RMSE: 0.807282236706 
reconstruction_spectrogram: (560, 1025)
reconstruction_angle: (560, 1025)
Reconstruction iteration: 6/300 RMSE: 0.708654640836 
reconstruction_spectrogram: (560, 1025)
reconstruction_angle: (560, 1025)
Reconstruction iteration: 7/300 RMSE: 0.575359596682 
reconstruc[...]<jupyter_text>altro<jupyter_code>import math
import sys
import numpy as np
import wave
import scipy
import scipy.signal
from pylab import *
import array
import scipy.io.wavfile

def stft_for_reconstruction(x, fft_size, hopsamp):
    window = np.hanning(fft_size)
    fft_size = int(fft_size)
    hopsamp = int(hopsamp)
    upper = len(x)-fft_size
    return np.array([np.fft.rfft(window*x[i:i+fft_size])
                     for i in range(0,upper, hopsamp)])

def get_signal(in_file, expected_fs=44100):
    fs, y = scipy.io.wavfile.read(in_file)
    num_type = y[0].dtype
    print(num_type)
    if num_type == 'int16':
        y = y*(1.0/32768)
    elif num_type == 'int32':
        y = y*(1.0/2147483648)
    elif num_type == 'float32':
        # Nothing to do
        pass
    elif num_type == 'uint8':
        raise Exception('8-bit PCM is not supported.')
    else:
        raise Exception('Unknown format.')
    if fs != expected_fs:
        raise Exception('Invalid sample rate.')
    if y.ndim == 1:
        return y
    else:
        return y.mean(axis=1)

def istft_for_reconstruction(X, fft_size, hopsamp):
    fft_size = int(fft_size)
    hopsamp = int(hopsamp)
    window = np.hanning(fft_size)
    time_slices = X.shape[0]
    len_samples = int(time_slices*hopsamp + fft_size)
    x = np.zeros(len_samples)
    for n,i in enumerate(range(0, len(x)-fft_size, hopsamp)):
        x[i:i+fft_size] += window*np.real(np.fft.irfft(X[n]))
    return x

def reconstruct_signal_griffin_lim(magnitude_spectrogram, fft_size, hopsamp, iterations):
    time_slices = magnitude_spectrogram.shape[0]
    len_samples = int(time_slices*hopsamp + fft_size)
    x_reconstruct = np.random.randn(len_samples)
    n = iterations # number of iterations of Griffin-Lim algorithm.
    while n > 0:
        n -= 1
        reconstruction_spectrogram = stft_for_reconstruction(x_reconstruct, fft_size, hopsamp)
        reconstruction_angle = np.angle(reconstruction_spectrogram)
        # proposal_spectrogram = np.dot(magnitude_spectrogram,np.exp(1.0j*reconstruction_angle))
        proposal_spectrogram = magnitude_spectrogram*np.exp(1.0j*reconstruction_angle)
        prev_x = x_reconstruct
        x_reconstruct = istft_for_reconstruction(proposal_spectrogram, fft_size, hopsamp)
        diff = sqrt(sum((x_reconstruct - prev_x)**2)/x_reconstruct.size)
        print('Reconstruction iteration: {}/{} RMSE: {} '.format(iterations - n, iterations, diff))
    return x_reconstruct

def array_to_wav(stft_modified_scaled,ITER=300,FFT_SIZE=1022, path_out = 'out.wav'):
    def save_audio_to_file(x, sample_rate, outfile='out.wav'):
        x_max = np.max(abs(x))
        assert x_max <= 1.0, 'Input audio value is out of range. Should be in the range [-1.0, 1.0].'
        x = x*32767.0
        data = array.array('h')
        for i in range(len(x)):
            cur_samp = int(round(x[i]))
            data.append(cur_samp)
        f = wave.open(outfile, 'w')
        f.setparams((1, 2, sample_rate, 0, "NONE", "Uncompressed"))
        f.writeframes(data.tostring())
        f.close()
    hopsamp = FFT_SIZE // 8
    x_reconstruct = reconstruct_signal_griffin_lim(stft_modified_scaled, FFT_SIZE, hopsamp, ITER)
    max_sample = np.max(abs(x_reconstruct))
    if max_sample > 1.0:
        x_reconstruct = x_reconstruct / max_sample
    print(x_reconstruct.shape)
    save_audio_to_file(x_reconstruct, 44100, path_out)

def wav_to_array(path_src,ITER = 300, FFT_SIZE = 1022):
    # input_signal = input_signal[:16600] #256x256
    #FFT_SIZE: 510 -> #256x256 
    hopsamp = FFT_SIZE // 8
    input_signal = get_signal(path_src, 44100)
    input_signal = input_signal[:65990]
    stft_full = stft_for_reconstruction(input_signal, FFT_SIZE, hopsamp)
    stft_mag = abs(stft_full)**2.0
    scale = 1.0 / np.amax(stft_mag)
    stft_mag *= scale
    stft_modified_scaled = stft_mag / scale
    return stft_modified_scaled**0.5


array_wav = wav_to_array('./griffin_lim-master/bkvhi.wav') # --> 512x512

#CycleGAN
inputGan = from_2D_To_3D(array_wav) #input di cyclegan
#faccio finta di generare altro cazzarola
outputGan = inputGan

#result di Gan
STICAZZI = RESHAPE(outputGan)
array_to_wav(STICAZZI,path_out = './sticazzipercoerenza.wav')
def from_2D_To_3D(x, dv=0):
    x = x[..., newaxis]
    x = np.tile(x, (1, 1, 3))
    for i in range(x.shape[0]):
        for j in range(x.shape[1]):
            x[i,j,1] = dv
            x[i,j,2] = dv
    return x
def RESHAPE(x):
    x = np.delete(x,2,2)
    x = np.delete(x,1,2)
    x = x.reshape((512,512))
    return x<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11376912378303199, 'fraction_numerical': 0.05521557719054242, 'mean_word_length': 3.979916897506925, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 13, '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}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '135613', 'license': 'Apache-2.0', 'n_tokens_mistral': 2941, 'n_tokens_neox': 2636, 'n_words': 512, 'path': 'GriffinLim.ipynb', 'repo_name': 'edivadiranatnom/Machine-Learning-Project', 'size': '7190'}