-
Notifications
You must be signed in to change notification settings - Fork 1
/
pitch_feature.py
226 lines (186 loc) · 6.41 KB
/
pitch_feature.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
import sys
import wave
import contextlib
from aubio import source, pitch
import numpy as np
import speech_recognition as sr
import os
import crayons
if len(sys.argv) < 2:
print("Usage: %s <filename> [samplerate]" % sys.argv[0])
sys.exit(1)
filename = sys.argv[1]
# calculating pitch
downsample = 1
samplerate = 44100 // downsample
if len( sys.argv ) > 2: samplerate = int(sys.argv[2])
win_s = 4096 // downsample # fft size
hop_s = 512 // downsample # hop size
s = source(filename, samplerate, hop_s)
samplerate = s.samplerate
tolerance = 0.8
pitch_o = pitch("yin", win_s, hop_s, samplerate)
pitch_o.set_unit("midi")
pitch_o.set_tolerance(tolerance)
pitches = []
confidences = []
times = []
# total number of frames read
total_frames = 0
while True:
samples, read = s()
pitch = pitch_o(samples)[0]
confidence = pitch_o.get_confidence()
time = total_frames / float(samplerate)
print("%f %f %f" % (time, pitch, confidence))
pitches += [pitch]
times += [time]
confidences += [confidence]
total_frames += read
if read < hop_s: break
if 0: sys.exit(0)
# converting pitches values to numpy values
pitches_np = np.array(pitches)
times_np = np.array(times)
print(pitches_np)
# print(times_np)
# number of voice breaks
# percentage breaks
# speak rate
count = 0
for i in range(len(pitches_np)-1):
if pitches_np[i] == 0 and pitches_np[i] != pitches_np[i+1]:
count += 1
elif pitches_np[i] != 0 and pitches_np[i+1] == 0:
count += 1
else:
continue
# print(count)
per_breaks = (count/len(pitches_np))*100
#print(str(per_breaks)+"%")
print(crayons.yellow(f'\t[*] Number of voice breaks => {count}', bold=True))
print(crayons.yellow(f'\t[*] Percentage of voice breaks => {round(per_breaks,3)}', bold=True))
# min, max and mean pitch
pitches_np_max = np.max(pitches_np)
print(crayons.red(f'\t[*] Maximum Pitch => {pitches_np_max}', bold=True))
pitches_np_mean = np.mean(pitches_np)
print(crayons.red(f'\t[*] Mean Pitch => {pitches_np_mean}', bold=True))
pitches_np_min = np.min(pitches_np)
print(crayons.red(f'\t[*] Minimum pitch => {pitches_np_min}', bold=True))
# duration of audio file
with contextlib.closing(wave.open(filename, 'r')) as f :
frame = f.getnframes()
frame_float = float(frame)
rate = f.getframerate()
duration = frame / float(rate)
print(crayons.blue(f'\t[*] Total Duration of file => {duration}', bold=True))
# total pause time when pitch is 0
pause_time = 0
for i in range(len(pitches_np)-1):
if pitches_np[i] == 0:
continue
else:
pause_time = times_np[i-1]
print(crayons.blue(f'\t[*] Total Pause time => {[pause_time]}', bold=True))
# word spoken by the human in the file
r = sr.Recognizer()
audio_sample = sr.AudioFile(sys.argv[1])
with audio_sample as source:
audio = r.record(source)
text_speech = r.recognize_google(audio)
play_time = duration - pause_time
speak_rate = len(text_speech) / play_time
print(crayons.yellow(f'\t[*] Speak rate => {speak_rate}', bold=True))
# rise and fall of the voice logic is that when pitch value is increasig there will be an increase in the voice else fall
num_rise = 0
num_fall = 0
for i in range(len(pitches_np)-1):
if pitches_np[i] < pitches_np[i+1] and pitches_np[i+1] > pitches_np[i+2]:
num_rise += 1
else:
continue
for i in range(len(pitches_np)-1):
if pitches_np[i] > pitches_np[i+1] and pitches_np[i+1] < pitches_np[i+2]:
num_fall += 1
else:
continue
print(crayons.yellow(f'\t[*] Number of voice_rise => {num_rise}', bold=True))
print(crayons.yellow(f'\t[*] Number of voice_fall => {num_fall}', bold=True))
'''
# finding maximum duration of rise and fall of the voice in terms of time wrt pitch
# getting problem in dealing with logic
rise_time = []
fall_time = []
for i in range(len(pitches_np)-1):
if (pitches_np[i] > 0 and pitches_np[i+1] > pitches_np[i]):
st_time = (time[i])
j = i + 1
while(pitches_np[j] > 0):
j = j+1
end_time = time[j]
time = abs(end_time-st_time)
rise_time.append(time)
elif pitches_np[i] == 0:
continue
else :
st_time = time[i]
j = i+1
while(pitches_np[j] < 0):
j = j+1
end_time = time[j]
time = abs(end_time-st_time)
fall_time.append(time)
print(rise_time)
print(fall_time)
'''
# analysing graphically the pitches
import os.path
from numpy import array, ma
import matplotlib.pyplot as plt
from demo_waveform_plot import get_waveform_plot, set_xlabels_sample2time
skip = 1
pitches = array(pitches[skip:])
confidences = array(confidences[skip:])
times = [t * hop_s for t in range(len(pitches))]
fig = plt.figure()
ax1 = fig.add_subplot(311)
ax1 = get_waveform_plot(filename, samplerate = samplerate, block_size = hop_s, ax = ax1)
plt.setp(ax1.get_xticklabels(), visible = False)
ax1.set_xlabel('')
def array_from_text_file(filename, dtype = 'float'):
filename = os.path.join(os.path.dirname(__file__), filename)
return array([line.split() for line in open(filename).readlines()],
dtype = dtype)
ax2 = fig.add_subplot(312, sharex = ax1)
ground_truth = os.path.splitext(filename)[0] + '.f0.Corrected'
if os.path.isfile(ground_truth):
ground_truth = array_from_text_file(ground_truth)
true_freqs = ground_truth[:,2]
true_freqs = ma.masked_where(true_freqs < 2, true_freqs)
true_times = float(samplerate) * ground_truth[:,0]
ax2.plot(true_times, true_freqs, 'r')
ax2.axis( ymin = 0.9 * true_freqs.min(), ymax = 1.1 * true_freqs.max() )
# plot raw pitches
ax2.plot(times, pitches, '.g')
# plot cleaned up pitches
cleaned_pitches = pitches
#cleaned_pitches = ma.masked_where(cleaned_pitches < 0, cleaned_pitches)
#cleaned_pitches = ma.masked_where(cleaned_pitches > 120, cleaned_pitches)
cleaned_pitches = ma.masked_where(confidences < tolerance, cleaned_pitches)
ax2.plot(times, cleaned_pitches, '.-')
#ax2.axis( ymin = 0.9 * cleaned_pitches.min(), ymax = 1.1 * cleaned_pitches.max() )
#ax2.axis( ymin = 55, ymax = 70 )
plt.setp(ax2.get_xticklabels(), visible = False)
ax2.set_ylabel('f0 (midi)')
# plot confidence
ax3 = fig.add_subplot(313, sharex = ax1)
# plot the confidence
ax3.plot(times, confidences)
# draw a line at tolerance
ax3.plot(times, [tolerance]*len(confidences))
ax3.axis( xmin = times[0], xmax = times[-1])
ax3.set_ylabel('condidence')
set_xlabels_sample2time(ax3, times[-1], samplerate)
plt.show()
# for saving the graph
#plt.savefig(os.path.basename(filename) + '.svg')