-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadd_noise.py
146 lines (132 loc) · 7.13 KB
/
add_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
import os
import h5py
import glob
import time
import numpy as np
import soundfile as sf
from vad import VAD
from functools import reduce
from math import hypot
filePath = '/seagate2t/simon/kawaii/data/orig'
noisePath = '/seagate2t/simon/kawaii/data/busesnoise.wav'
origPath = '/seagate2t/simon/kawaii/data/show_orig.hdf5'
savePath = '/seagate2t/simon/kawaii/data/fix/fix_show_allsnr.hdf5'
rirPath = '/seagate2t/simon/kawaii/data/multi_sources/ms_rir.h5'
filePathes = glob.glob(filePath+'/**/*.wav', recursive=True)
rirSet = h5py.File(rirPath, 'r')
origFile = h5py.File(origPath, 'w', libver='latest', swmr=True)
saveFile = h5py.File(savePath, 'w', libver='latest', swmr=True)
noise, sampleRate = sf.read(noisePath)
lenNoise = len(noise)
print('+{0:->15}+{1:-<30}+'.format('-', '-'))
for room in list(rirSet.keys()):
try:
print('|{0:>15}|{1:<30}|'.format('room', room))
rir = rirSet[room]['source1']
noiseRir = rirSet[room]['source4']
conv1 = rir[:,0]
conv2 = rir[:,1]
nConv1 = noiseRir[:,0]
nConv2 = noiseRir[:,1]
mic1 = np.asarray([float(t) for t in rir.attrs['mp1'].split()])
mic2 = np.asarray([float(t) for t in rir.attrs['mp2'].split()])
speaker = np.asarray([float(t) for t in rir.attrs['sp'].split()])
roomSize = np.asarray([float(t) for t in rir.attrs['roomsize'].split()])
noisePos = np.asarray([float(t) for t in noiseRir.attrs['sp'].split()])
volume = reduce(lambda x, y: x*y, roomSize)
angle = np.arccos(np.clip(np.dot(mic2 - mic1, speaker - mic1), -1.0, 1.0)) * 360 / (2 * np.pi)
vector = speaker - (mic1 + mic2)/2
noiseAngle = np.arccos(np.clip(np.dot(mic2 - mic1, noisePos - mic1), -1.0, 1.0)) * 360 / (2 * np.pi)
distance = reduce(lambda x, y: hypot(x, y), vector)
theta = np.arccos(vector[2]/distance)*180/np.pi
phi = np.arccos(vector[0]/(distance*np.sin(theta)))*180/np.pi
curRoom = saveFile.create_group(str(roomSize))
print('|{0:>15}|{1:<30.2f}|'.format('volume', volume))
print('|{0:>15}|{1:<30.2f}|'.format('angle', angle))
print('|{0:>15}|{1:<30.2f}|'.format('distance', distance))
print('|{0:>15}|{1:<30.2f}|'.format('noise angle', noiseAngle))
print('|{0:>15}|{1:<30.2f}|'.format('spherical', distance))
print('|{0:>15}|{1:<30.2f}|'.format('', theta))
print('|{0:>15}|{1:<30.2f}|'.format('', phi))
print('+{0:->15}+{1:-<30}+'.format('-', '-'))
for wavPath in filePathes:
t = time.time()
head, fileName = os.path.split(wavPath)
clean, sr = sf.read(wavPath)
maxi = max(abs(clean))
clean = [samp*(0.99/maxi) for samp in clean] # magnitude normalization.
noiseExt = np.resize(noise, len(clean))
vad = VAD(np.asarray(clean[19960521:19960521+360*sr]), sr, threshold=0.95)
ratio = list(vad).count(1)/len(vad)
magWave = np.sum(np.square(clean))/(ratio*len(clean))
# print(ratio, len(clean[19960521:19960521+120*sr]), len(vad), list(vad).count(1))
print('|{0:>15}|{1:<30}|'.format('file name', fileName))
print('|{0:>15}|{1:<30.4f}|'.format('vad ratio', ratio))
print('|{0:>15}|{1:<30}|'.format('conv', 'start'))
fakeMic1 = np.convolve(conv1, clean)
fakeMic2 = np.convolve(conv2, clean)
maxi = max(abs(fakeMic1))
fakeMic1 = [samp*(0.99/maxi) for samp in fakeMic1] # magnitude normalization.
maxi = max(abs(fakeMic2))
fakeMic2 = [samp*(0.99/maxi) for samp in fakeMic2] # magnitude normalization.
noiseMic1 = np.convolve(nConv1, noiseExt)
noiseMic2 = np.convolve(nConv2, noiseExt)
print('|{0:>15}|{1:<30}|'.format('conv', 'finished'))
magFakeMic = np.sum(np.square(fakeMic1))/(ratio*len(fakeMic1))
magNoiseMic = np.mean(np.square(noiseMic1))
for snr in [-15, -6, -3, 0, 3, 6, 15]:
noiseMic1 = [p*(magFakeMic/(magNoiseMic*10**(snr/10))) for p in noiseMic1]
noiseMic2 = [p*(magFakeMic/(magNoiseMic*10**(snr/10))) for p in noiseMic2]
channel1 = np.asarray(fakeMic1) + np.asarray(noiseMic1)
channel2 = np.asarray(fakeMic2) + np.asarray(noiseMic2)
stereo = np.vstack((channel1, channel2)).T
print('+{0:->15}+{1:-<30}+'.format('-', '-'))
print('|{0:>15}|{1:<30}|'.format('scale ratio', (magFakeMic/(magNoiseMic*10**(snr/10)))))
print('|{0:>15}|{1:<30}|'.format('snr '+str(snr), 'rebuild finished'))
flag = 0
salt = ''.join(random.sample(string.ascii_letters + string.digits, 16))
curDset = curRoom.create_dataset(salt, data=stereo)
curDset.attrs.create('mono', fileName, dtype=h5py.special_dtype(vlen=str))
curDset.attrs.create('volume', volume, dtype=float)
curDset.attrs.create('angle', angle, dtype=float)
curDset.attrs.create('distance', distance, dtype=float)
curDset.attrs.create('theta', theta, dtype=float)
curDset.attrs.create('phi', phi, dtype=float)
curDset.attrs.create('snr', snr, dtype=float)
curDset.attrs.create('mp1', rir.attrs['mp1'], dtype=h5py.special_dtype(vlen=str))
curDset.attrs.create('mp2', rir.attrs['mp2'], dtype=h5py.special_dtype(vlen=str))
curDset.attrs.create('sp', rir.attrs['sp'], dtype=h5py.special_dtype(vlen=str))
curDset.attrs.create('roomsize', rir.attrs['roomsize'], dtype=h5py.special_dtype(vlen=str))
curDset.attrs.create('noise angle', noiseAngle, dtype=float)
flag = 1
try:
assert origFile[curDset.attrs['mono']].shape[0] == stereo.shape[0]
except AssertionError:
try:
clean.extend(np.zeros(stereo.shape[0] - len(clean)))
origFile[curDset.attrs['mono']] = clean
except:
import ipdb; ipdb.set_trace()
except:
clean.extend(np.zeros(stereo.shape[0] - len(clean)))
origFile.create_dataset(fileName, data=clean)
assert origFile[curDset.attrs['mono']].shape[0] == stereo.shape[0]
t = time.time() - t
print('+{0:->15}+{1:-<30}+'.format('-', '-'))
print('|{0:>15}|{1:<30.2f}|'.format('time', t))
print('+{0:->15}+{1:-<30}+'.format('-', '-'))
except KeyboardInterrupt:
if(flag == 0):
del curRoom[fileName]
print('|{0:>15}|{1:<30.2f}|'.format(fileName, 'dSet deleted'))
print('+{0:->15}+{1:-<30}+'.format('-', '-'))
if(list(curRoom.keys())==[]):
del saveFile[str(roomSize)]
print('|{0:>15}|{1:<30.2f}|'.format(str(roomSize), 'room deleted'))
print('+{0:->15}+{1:-<30}+'.format('-', '-'))
break
saveFile.swmr_mode = True
saveFile.flush()
saveFile.close()
origFile.close()
print('+{0:->15}-{1:-<30}+'.format(' all ', ' finished '))