-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathteamstartup_chainsaw_detect.py
149 lines (116 loc) · 5.27 KB
/
teamstartup_chainsaw_detect.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
import argparse
import os , shutil
import numpy as np
import librosa
import glob
import multiprocessing
import sys
import pyaudio
import wave
import smtplib
import imghdr
from email.message import EmailMessage
from functions.extract_pcen_feature import extract_pcen_feature as extract_features
from functions.classify_features import classify_features
class chainsaw_detect:
def __init__(self):
self.mail_from = '[email protected]'
self.mail_password = 'godsense143'
self.mgs = EmailMessage()
self.mgs['subject'] = ' Cutting Down Tree has been Detected! '
self.mgs['From'] = self.mail_from
self.mgs['To'] = '[email protected]'
self.mgs.set_content('Illegal actions has been detected at Microphone 1 location ')
def main(self):
print("recording Audio")
audio = pyaudio.PyAudio()
recordSeconds = 10
sampleRate = 8000
bufferFrames = 1024
stream = audio.open(format=pyaudio.paInt16, channels=1, rate=sampleRate, input=True, frames_per_buffer=bufferFrames)
frames = []
for i in range(0, int(sampleRate / bufferFrames*recordSeconds)):
data = stream.read(bufferFrames)
frames.append(data)
if i%8==0:
print("Listening...")
stream.stop_stream()
stream.close()
audio.terminate()
#importing the os module
#to get the current working directory
directory = os.getcwd()
sound_file = wave.open(directory+"\\audio_file\\Recorded Audio.wav","wb")
sound_file.setnchannels(1)
sound_file.setsampwidth(audio.get_sample_size(pyaudio.paInt16))
sound_file.setframerate(8000)
sound_file.writeframes(b''.join(frames))
sound_file.close()
parser = argparse.ArgumentParser(description='batch_processor', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-u', '--nopREQ', type=int, default=6, help='number of processing units employed')
parser.add_argument('-t', '--VADthresh', type=float, default=0.078, help='Treshold for VAD detection, default=0.078')
parser.add_argument('-p', '--probThresh', type=float, default=0.75, help='Treshold for RNN classifier, default=0.75')
args = parser.parse_args()
#%% Parameters
maxDur=400 #in seconds
nop=multiprocessing.cpu_count()
nopREC=np.max([1,nop-1])
if args.nopREQ<nopREC:
nopUSE=args.nopREQ
else:
nopUSE=nopREC
if args.VADthresh>=0.0779:
VADthresh=args.VADthresh
else:
VADthresh=0.078
if args.probThresh>1:
pass
probThresh=args.probThresh
inputWavPath = directory+"\\audio_file"
outputDataPath = directory+"\\audio_file"
wavFileNames=[]
modelfileName='teamStartup_chainsaw_model.hdf5'
Nclasses=2
# pcen_rnn4_cl2_RMED_allARUs_run0
# %%
if os.path.exists(inputWavPath + '/' + 'Features') == True:
shutil.rmtree((inputWavPath + '/' + 'Features'))
if os.path.exists(inputWavPath + '/' + 'Extracted_segments') == True:
shutil.rmtree((inputWavPath + '/' + 'Extracted_segments'))
if os.path.exists(inputWavPath + '/' + 'Features') == False:
os.mkdir((inputWavPath + '/' + 'Features'))
if os.path.exists(inputWavPath + '/' + 'Extracted_segments') == False:
os.mkdir((inputWavPath + '/' + 'Extracted_segments'))
#%% do the a=ob
folder_with_recordings=(inputWavPath + '/*.wav')
for wavName in glob.glob(folder_with_recordings):
pool=multiprocessing.Pool(nopUSE)
fileDuration=librosa.get_duration(filename=wavName)
sr=librosa.get_samplerate(wavName)
if sr==8000:
wavFileNames.append(wavName)
if fileDuration<maxDur:
timeBorders=np.array((0,fileDuration))
else:
timeBorders=np.arange(0,fileDuration,maxDur)
timeBorders=np.delete(timeBorders,-1,axis=None)
timeBorders=np.append(timeBorders,fileDuration)
Nsegm=timeBorders.size
for segmIdx in range(Nsegm-1): #range(0,Nsegm-1):
pool.apply_async(extract_features, args=(wavName,outputDataPath,timeBorders,segmIdx,VADthresh))
pool.close()
pool.join()
else:
print(wavName.split(os.sep)[-1] + ' has a sampling rate different than 8000 Hz, will not process this audio file ')
#%% Run classifier and extract positive .wav segments
if classify_features(outputDataPath,f"Models/{modelfileName}",Nclasses,probThresh):
with smtplib.SMTP_SSL('smtp.gmail.com',465) as smtp:
smtp.login(self.mail_from,self.mail_password)
smtp.send_message(self.mgs)
def detect(self):
while True:
try:
self.main()
self.sleep(1)
except:
pass