[英]How to display a generator object value from zip in python?
Im trying to hash WAV audio file in Jupyter Notebook..i had no issues with creating spectrogram..but while hashing using the peak points..as a zip(frequency_values,time_values).我试图在 Jupyter Notebook 中对 WAV 音频文件进行哈希处理。
def generate_hashes(peaks, fan_value=DEFAULT_FAN_VALUE):
if PEAK_SORT:
peaks.sort(key=itemgetter(1))
# bruteforce all peaks
for i in range(len(peaks)):
for j in range(1, fan_value):
if (i + j) < len(peaks):
# take current & next peak frequency value
freq1 = peaks[i][IDX_FREQ_I]
freq2 = peaks[i + j][IDX_FREQ_I]
# take current & next -peak time offset
t1 = peaks[i][IDX_TIME_J]
t2 = peaks[i + j][IDX_TIME_J]
# get diff of time offsets
t_delta = t2 - t1
# check if delta is between min & max
if t_delta >= MIN_HASH_TIME_DELTA and t_delta <= MAX_HASH_TIME_DELTA:
h = hashlib.sha1("%s|%s|%s" % (str(freq1), str(freq2), str(t_delta)))
yield (h.hexdigest()[0:FINGERPRINT_REDUCTION], t1)
h=generate_hashes(local_maxima, fan_value=DEFAULT_FAN_VALUE)
h.__next__()
ERROR:(ps:ignore my formatting..new to site)错误:(ps:忽略我的格式..新网站)
AttributeError Traceback (most recent call last) <ipython-input-61-755dd1339124> in <module> ----> 1 h.__next__() <ipython-input-59-a612d64209d2> in generate_hashes(peaks, fan_value) 1 def generate_hashes(peaks, fan_value=DEFAULT_FAN_VALUE): 2 if PEAK_SORT: ----> 3 peaks.sort(key=itemgetter(1)) 4 5 # bruteforce all peaks AttributeError: 'zip' object has no attribute 'sort'
And my full code is here:我的完整代码在这里:
import hashlib
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
from scipy.ndimage.filters import maximum_filter
from scipy.ndimage.morphology import (generate_binary_structure, iterate_structure, binary_erosion)
from operator import itemgetter
from scipy.io import wavfile
from scipy import signal
from pydub import AudioSegment
import os
IDX_FREQ_I = 0
IDX_TIME_J = 1
DEFAULT_FS = 44100
DEFAULT_WINDOW_SIZE = 4096
DEFAULT_OVERLAP_RATIO = 0.5
DEFAULT_FAN_VALUE = 15
DEFAULT_AMP_MIN = 10
PEAK_NEIGHBORHOOD_SIZE = 20
MIN_HASH_TIME_DELTA = 0
MAX_HASH_TIME_DELTA = 200
PEAK_SORT = True
FINGERPRINT_REDUCTION = 20
plots=False
file_name=input("Enter the audio file location ::")
if not file_name.lower().endswith('.wav'):
print("Please specify a WAV file")
if os.path.exists(file_name)==False:
print("Please enter the path of existing WAV file")
sampling_frequency , data = wavfile.read(file_name)
plt.plot(data,color='B')
plt.xlabel('Sample')
plt.title('%d samples' % len(data))
plt.ylabel('Amplitude')
plt.show
plt.gca().invert_yaxis()
if plots :
plt.specgram(data[:,0],Fs=44100)
plt.xlabel('Time')
plt.ylabel('Frequency')
plt.show
arr2D = mlab.specgram(data[:,0],Fs=44100,window=mlab.window_hanning,NFFT=4096,noverlap=int(4096 * 0.5))[0]
arr2D
arr2D=np.asarray(arr2D)
arr2D
if plots :
plt.plot(arr2D)
plt.title('FFT')
plt.show()
arr2D = 10 * np.log10(arr2D)
arr2D[arr2D == -np.inf]
arr2D
def get_2D_peaks(arr2D, plot=False, amp_min=DEFAULT_AMP_MIN):
struct = generate_binary_structure(2, 1)
neighborhood = iterate_structure(struct, PEAK_NEIGHBORHOOD_SIZE)
local_max = maximum_filter(arr2D, footprint=neighborhood) == arr2D
background = (arr2D == 0)
eroded_background = binary_erosion(background, structure=neighborhood,
border_value=1)
detected_peaks = local_max ^ eroded_background
amps = arr2D[detected_peaks]
j, i = np.where(detected_peaks)
amps = amps.flatten()
peaks = zip(i, j, amps)
peaks_filtered = [x for x in peaks if x[2] > amp_min]
frequency_idx = [x[1] for x in peaks_filtered]
time_idx = [x[0] for x in peaks_filtered]
if plot:
fig, ax = plt.subplots()
ax.imshow(arr2D)
ax.scatter(time_idx, frequency_idx)
ax.set_xlabel('Time')
ax.set_ylabel('Frequency')
ax.set_title("Spectrogram")
plt.gca().invert_yaxis()
plt.show()
return zip(frequency_idx, time_idx)
local_maxima = get_2D_peaks(arr2D, plot=plots, amp_min=DEFAULT_AMP_MIN)
local_maxima
x=list(local_maxima)
y=len(x)
msg = " local_maxima: "+str(y)+" of frequency & time pairs"
print ( msg )
def generate_hashes(peaks, fan_value=DEFAULT_FAN_VALUE):
if PEAK_SORT:
peaks.sort(key=itemgetter(1))
# bruteforce all peaks
for i in range(len(peaks)):
for j in range(1, fan_value):
if (i + j) < len(peaks):
# take current & next peak frequency value
freq1 = peaks[i][IDX_FREQ_I]
freq2 = peaks[i + j][IDX_FREQ_I]
# take current & next -peak time offset
t1 = peaks[i][IDX_TIME_J]
t2 = peaks[i + j][IDX_TIME_J]
# get diff of time offsets
t_delta = t2 - t1
# check if delta is between min & max
if t_delta >= MIN_HASH_TIME_DELTA and t_delta <= MAX_HASH_TIME_DELTA:
h = hashlib.sha1("%s|%s|%s" % (str(freq1), str(freq2), str(t_delta)))
yield (h.hexdigest()[0:FINGERPRINT_REDUCTION], t1)
h=generate_hashes(local_maxima, fan_value=DEFAULT_FAN_VALUE)
h.__next__()
I hope your answer will help me fix it.. :-)我希望你的回答能帮助我解决它.. :-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.