-
Notifications
You must be signed in to change notification settings - Fork 1
/
sound_noise.py
385 lines (351 loc) · 14.1 KB
/
sound_noise.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 24 08:30:39 2024
@author: JMCasado; NBertaina
"""
#General import
import os
import sys
import argparse
import glob
import numpy as np
import datetime
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import math
import pandas as pd
sys.path.append("../pybrl")
import pybrl as brl
from pydub import AudioSegment
def wav_to_mp3(wav_path, mp3_path):
sound_mp3 = AudioSegment.from_mp3(wav_path)
sound_mp3.export(mp3_path, format='wav')
# Local imports
from data_transform import smooth
from data_export.data_export import DataExport
from data_import.data_import import DataImport
from sound_module.simple_sound import simpleSound
from data_transform.predef_math_functions import PredefMathFunctions
# Instanciate the sonoUno clases needed
_dataexport = DataExport(False)
_dataimport = DataImport()
_simplesound = simpleSound()
_math = PredefMathFunctions()
# Sound configurations, predefined at the moment
_simplesound.reproductor.set_continuous()
_simplesound.reproductor.set_waveform('sine') # piano; sine
_simplesound.reproductor.set_time_base(0.1)
_simplesound.reproductor.set_min_freq(380)
_simplesound.reproductor.set_max_freq(800)
# The argparse library is used to pass the path and extension where the data
# files are located
parser = argparse.ArgumentParser()
# Receive the extension from the arguments
parser.add_argument("-t", "--file-type", type=str,
help="Select file type (csv, txt). Defaults to txt.",
choices=['csv', 'txt'])
# Receive the directory path from the arguments
parser.add_argument("-d", "--directory", type=str,
help="Indicate a directory to process as batch.")
# Indicate to save or not the plot
parser.add_argument("-p", "--save-plot", type=bool,
help="Indicate if you want to save the plot (False as default)",
choices=[False, True])
parser.add_argument("-n", "--noise_snr", type=float,
help="Set the signal-to-noise ratio (SNR) for Gaussian noise addition. Defaults to 10.",
default=10)
# Alocate the arguments in variables, if extension is empty, select txt as
# default
args = parser.parse_args()
ext = args.file_type or 'txt'
path = args.directory
plot_flag = args.save_plot or True
noise_snr = args.noise_snr
# Print a messege if path is not indicated by the user
if not path:
print('1At least on intput must be stated.\nUse -h if you need help.')
exit()
# Format the extension to use it with glob
extension = '*.' + ext
# Function to generate Gaussian noise
def generate_gaussian_noise(length, snr):
signal_power = 10 ** (snr / 10)
noise_var= 1 / signal_power
return np.random.normal(0, np.sqrt(noise_var), length)
def generate_plot_space(brailleweight=500):
# Plot without data (cuad1)
# Generate the blank plot
figblank = plt.figure()
axblank = plt.axes()
axblank.set_title(' ')
x = brl.translate('x')
x = brl.toUnicodeSymbols(x, flatten=True)
axblank.set_xlabel(' ', fontsize=24, fontfamily='serif', fontweight=brailleweight, labelpad=15)
y = brl.translate('y')
y = brl.toUnicodeSymbols(y, flatten=True)
axblank.set_ylabel(' ', fontsize=24, fontfamily='serif', fontweight=brailleweight, labelpad=10, rotation=0)
# Setting ticks
num0 = brl.translate('0')
num0 = brl.toUnicodeSymbols(num0, flatten=True)
num25 = brl.translate('25')
num25 = brl.toUnicodeSymbols(num25, flatten=True)
num50 = brl.translate('50')
num50 = brl.toUnicodeSymbols(num50, flatten=True)
axblank.set_xticks([0,25,50],
[' ',' ',' '],
fontsize=24,
fontfamily='serif',
fontweight=brailleweight,
position=(0,-0.04))
axblank.set_yticks([0,25,50],
[' ',' ',' '],
fontsize=24,
fontfamily='serif',
fontweight=brailleweight)
# Resize
figblank.tight_layout()
# Save braille figure
blankplot_path = path[:-4] + 'plot-blank1.png'
figblank.savefig(blankplot_path)
plt.close()
# Plot without data (cuad all)
# Generate the blank plot
figblank_all = plt.figure()
axblank_all = plt.axes()
axblank_all.set_title(' ')
x = brl.translate('x')
x = brl.toUnicodeSymbols(x, flatten=True)
axblank_all.set_xlabel(x, fontsize=24, fontfamily='serif', fontweight=brailleweight, labelpad=15)
y = brl.translate('y')
y = brl.toUnicodeSymbols(y, flatten=True)
axblank_all.set_ylabel(y, fontsize=24, fontfamily='serif', fontweight=brailleweight, labelpad=10, rotation=0)
# Setting ticks
num_50 = brl.translate('50')
caract_resta = [['001001']]
for i in num_50[0]:
caract_resta[0].append(i)
num_50 = caract_resta
num_50 = brl.toUnicodeSymbols(num_50, flatten=True)
num0 = brl.translate('0')
num0 = brl.toUnicodeSymbols(num0, flatten=True)
num50 = brl.translate('50')
num50 = brl.toUnicodeSymbols(num50, flatten=True)
axblank_all.set_xticks([-50,0,50],
[num_50,num0,num50],
fontsize=24,
fontfamily='serif',
fontweight=brailleweight,
position=(0,-0.04))
axblank_all.set_yticks([-50,0,50],
[num_50,num0,num50],
fontsize=24,
fontfamily='serif',
fontweight=brailleweight)
# Setting limits
axblank_all.set_xlim(-55,55)
axblank_all.set_ylim(-55,55)
# Axis
axblank_all.axvline(x=0, color='k', linewidth=1)
axblank_all.axhline(y=0, color='k', linewidth=1)
# Legend I
mayus = [['000101']]
legend1 = brl.translate('i')
for i in legend1[0]:
mayus[0].append(i)
legend1 = brl.toUnicodeSymbols(mayus, flatten=True)
axblank_all.text(15, 20, legend1, size=24, fontfamily='serif', fontweight=brailleweight, va="bottom", ha="left", rotation=0)
#Legend II
mayus = [['000101']]
legend2 = brl.translate('ii')
for i in legend2[0]:
mayus[0].append(i)
legend2 = brl.toUnicodeSymbols(mayus, flatten=True)
axblank_all.text(-35, 20, legend2, size=24, fontfamily='serif', fontweight=brailleweight, va="bottom", ha="left", rotation=0)
#Legend III
mayus = [['000101']]
legend3 = brl.translate('iii')
for i in legend3[0]:
mayus[0].append(i)
legend3 = brl.toUnicodeSymbols(mayus, flatten=True)
axblank_all.text(-40, -30, legend3, size=24, fontfamily='serif', fontweight=brailleweight, va="bottom", ha="left", rotation=0)
#Legend II
mayus = [['000101']]
legend4 = brl.translate('iv')
for i in legend4[0]:
mayus[0].append(i)
legend4 = brl.toUnicodeSymbols(mayus, flatten=True)
axblank_all.text(15, -30, legend4, size=24, fontfamily='serif', fontweight=brailleweight, va="bottom", ha="left", rotation=0)
# Resize
figblank_all.tight_layout()
# Save braille figure
blankplot_path = path[:-4] + 'plot-blank-all.png'
figblank_all.savefig(blankplot_path)
plt.close()
# Check and display the type of the variable
def check_and_display_type(variable):
if isinstance(variable, list):
print(f"The variable is a Python list")
elif isinstance(variable, np.ndarray):
print(f"The variable is a NumPy array")
elif isinstance(variable, pd.Series):
print(f"The variable is a Pandas Series")
elif isinstance(variable,pd.DataFrame):
print(f"The variable is a Pandas DataFrame")
else:
print("The variable is not a recognized type.")
def numinbraille(floatnum):
num_primera_serie = [['010110'],
['100000'],
['110000'],
['100100'],
['100110'],
['100010'],
['110100'],
['110110'],
['110010'],
['010100']]
simbolo_num = [['001111']]
simbolo_resta = [['001001']]
# convertion
totext = [simbolo_num[0].copy()]
if (floatnum < 0) and (int(abs(floatnum)) == 0):
num = str(1)
else:
num = str(int(abs(floatnum)))
for i in num:
a = num_primera_serie[int(i)]
totext[0].append(a[0])
if floatnum < 0:
totext2 = [simbolo_resta[0].copy()]
for i in totext[0]:
totext2[0].append(i)
totext2 = brl.toUnicodeSymbols(totext2, flatten=True)
return totext2
totext = brl.toUnicodeSymbols(totext, flatten=True)
return totext
def generate_braille_plot(dataframe, name='plot-braille.png', brailleweight=500):
# Generate the braille plot
figbraille = plt.figure()
axbraille = plt.axes()
# 3 valores de eje x en braille
abs_val_array = np.abs(dataframe.loc[:,0] - dataframe.loc[:,0].min())
x_pos_min = abs_val_array.idxmin()
middle = ((dataframe.loc[:,0].max() - dataframe.loc[:,0].min())/2) + dataframe.loc[:,0].min()
abs_val_array = np.abs(dataframe.loc[:,0] - middle)
x_pos_middle = abs_val_array.idxmin()
abs_val_array = np.abs(dataframe.loc[:,0] - dataframe.loc[:,0].max())
x_pos_max = abs_val_array.idxmin()
# primer numero del eje x
xinicio_text = numinbraille(dataframe.loc[x_pos_min,0])
# numero medio del eje x
xmedio_text = numinbraille(dataframe.loc[x_pos_middle,0])
# numero final del eje x
xfinal_text = numinbraille(dataframe.loc[x_pos_max,0])
axbraille.set_xticks([dataframe.loc[x_pos_min,0],dataframe.loc[x_pos_middle,0],dataframe.loc[x_pos_max,0]],
[xinicio_text,xmedio_text,xfinal_text],
fontsize=24,
fontfamily='serif',
fontweight=brailleweight,
position=(0,-0.04))
# 3 valores de eje y en braille
# Found min, middle, max possitions and values
abs_val_array = np.abs(dataframe.loc[:,1] - dataframe.loc[:,1].min())
y_pos_min = abs_val_array.idxmin()
middle = ((dataframe.loc[:,1].max() - dataframe.loc[:,1].min())/2) + dataframe.loc[:,1].min()
abs_val_array = np.abs(dataframe.loc[:,1] - middle)
y_pos_middle = abs_val_array.idxmin()
abs_val_array = np.abs(dataframe.loc[:,1] - dataframe.loc[:,1].max())
y_pos_max = abs_val_array.idxmin()
y_pos_min_text = numinbraille(dataframe.loc[y_pos_min,1])
y_pos_middle_text = numinbraille(dataframe.loc[y_pos_middle,1])
y_pos_max_text = numinbraille(dataframe.loc[y_pos_max,1])
axbraille.set_yticks([dataframe.loc[y_pos_min,1],dataframe.loc[y_pos_middle,1],dataframe.loc[y_pos_max,1]],
[y_pos_min_text,y_pos_middle_text,y_pos_max_text],
fontsize=24,
fontfamily='serif',
fontweight=brailleweight)
axbraille.set_title(' ')
x = brl.translate('x')
x = brl.toUnicodeSymbols(x, flatten=True)
axbraille.set_xlabel(x, fontsize=24, fontfamily='serif', fontweight=brailleweight, labelpad=15)
y = brl.translate('y')
y = brl.toUnicodeSymbols(y, flatten=True)
axbraille.set_ylabel(y, fontsize=24, fontfamily='serif', fontweight=brailleweight, labelpad=10, rotation=0)
axbraille.plot(dataframe.loc[:, 0], dataframe.loc[:, 1], '#2874a6', linewidth=3)
# Ejes de coordenadas
if dataframe.loc[:, 0].min() < 0 and dataframe.loc[:, 0].max() > 0:
axbraille.axvline(x=0, color='k', linewidth=1)
if dataframe.loc[:, 1].min() < 0 and dataframe.loc[:, 1].max() > 0:
axbraille.axhline(y=0, color='k', linewidth=1)
# Resize
figbraille.tight_layout()
# Save braille figure
brailleplot_path = path[:-4] + name
figbraille.savefig(brailleplot_path)
plt.close()
# Create an empty figure or plot to save it
fig = plt.figure()
# Defining the axes so that we can plot data into it.
ax = plt.axes()
# Open each file
data, status, msg = _dataimport.set_arrayfromfile(path, ext)
# Check if the import is correct
if data.shape[1]<2:
print("Error reading file 1, only detect one column.")
exit()
# Extract the names and turn to float
data_float = data.iloc[1:, :].astype(float)
x_pos_min = 1
# Generate de plot
ax.set_xlabel('x')
ax.set_ylabel('y', rotation=0)
# Separate the name file from the path to set the plot title
filename = os.path.basename(path)
# Plot
ax.plot(data_float.loc[:, 0], data_float.loc[:, 1], '#2874a6', linewidth=3)
# Ejes de coordenadas
if data_float.loc[:, 0].min() < 0:
ax.axvline(x=0, color='k', linewidth=1)
if data_float.loc[:, 1].min() < 0:
ax.axhline(y=0, color='k', linewidth=1)
# Set the path to save the plot and save it
plot_path = path[:-4] + 'plot.png'
fig.savefig(plot_path)
plt.close()
print(type(data_float))
generate_braille_plot(data_float, 'plot-braille1.png')
# Reproduction
# Normalize the data to sonify
x1, y1, status = _math.normalize(data_float.loc[:, 0], data_float.loc[:, 1], init=x_pos_min)
# Save sound
wav_name = path[:-4] + '_sound.wav'
path_mp3 = path[:-4] + '_sound.mp3'
x_pos_min = 1
_simplesound.save_sound(wav_name, data_float.loc[:,0], y1, init=x_pos_min)
wav_to_mp3(wav_name, path_mp3)
# Generate sound with Gaussian noise
y1_noise = y1 + generate_gaussian_noise(len(y1), noise_snr)
# Generate the dataFrame to plot the noise with braille
y1_noise.to_frame()
data_float_noise = data_float.loc[:, 0].to_frame()
data_float_noise = data_float_noise.join(y1_noise.to_frame())
generate_braille_plot(data_float_noise, 'plot-braille2.png')
# Save sound
wav_name_noise = path[:-4] + '_noise.wav'
path_mp3_noise = path[:-4] + '_noise.mp3'
_simplesound.save_sound(wav_name_noise, data_float.loc[:, 0], y1_noise, init=x_pos_min)
wav_to_mp3(wav_name_noise, path_mp3_noise)
# Generate image of sound with noise
fig_noise = plt.figure()
ax_noise = plt.axes()
ax_noise.plot(data_float.loc[:, 0], y1_noise, '#f39c12', linewidth=3)
ax_noise.set_xlabel('x')
ax_noise.set_ylabel('y')
if data_float.loc[:, 0].min() < 0:
ax_noise.axvline(x=0, color='k', linewidth=1)
if y1_noise.min() < 0:
ax_noise.axhline(y=0, color='k', linewidth=1)
image_name = path[:-4] + 'plot_noise.png'
fig_noise.savefig(image_name)
plt.close()