import cv2 import sys from mail import sendEmail from flask import Flask, render_template, Response, request, redirect, url_for from flask import request from camera import VideoCamera from flask_basicauth import BasicAuth import time import threading import os import glob import re import numpy as np from dropboxStorage import * # Dropbox photo uploads from SpreadSheet import * # Updating Spreadsheet from TwilioAmazon import * ##Amazon s3 and Twilio SMS from ringBuffer import * noOfBufferFrames = 30 ringBuffObj = RingBuffer(noOfBufferFrames) eventDetectedFrames = [] bufferFlag = 1 dropBoxFrame = '' email_update_interval = 120 # sends an email only once in this time(seconds) interval video_camera = VideoCamera(flip=True) # creates a camera object, flip vertically object_classifier = cv2.CascadeClassifier( "/home/pi/SecurityCamera/models/fullbody_recognition_model.xml") # an opencv classifier # App Globals app = Flask(__name__) app.config['BASIC_AUTH_USERNAME'] = 'admin' app.config['BASIC_AUTH_PASSWORD'] = 'admin' app.config['BASIC_AUTH_FORCE'] = True basic_auth = BasicAuth(app) last_epoch = 0 dbUpload = False lastPicClicked = 0 AmzTwilioFlag = 0 FlagTwo = False writer = None W = None H = None def check_for_objects(): global last_epoch global dbUpload global lastPicClicked global AmzTwilioFlag global FlagTwo global writer global W global H global eventDetectedFrames global bufferFlag global ringBuffObj global noOfBufferFrames global dropBoxFrame while True: frame, found_obj, mainframe, frameTimeLapse, bufferFrame = video_camera.get_object(object_classifier) if (bufferFlag == 1): bufferFrame = imutils.resize(bufferFrame, width=480) ringBuffObj.append(bufferFrame) # Capture image for time-lapse after every 15 second if (time.time() - lastPicClicked) >= 15: lastPicClicked = time.time() print('Capturing Pictures for Time-lapse .......') date_string = datetime.now().strftime("%Y%m%d-%H%M%S") file = "/home/pi/SecurityCamera/timelapse/" + date_string + ".jpg" cv2.imwrite(file, frameTimeLapse) # print('Captured.......') ringBuffObj.append(bufferFrame) try: if found_obj and (time.time() - last_epoch) > email_update_interval: last_epoch = time.time() print("Sending email...") sendEmail(frame) print("Email sent successfully!") dropBoxFrame = mainframe AmzTwilioFlag = 1 except: print("Error sending email: ", sys.exc_info()[0]) if AmzTwilioFlag == 1: print('Capturing video') FlagOne = FlagTwo # resize the frame mainframe = imutils.resize(mainframe, width=480) # mainframe = imutils.resize(mainframe, width=640) # if the frame dimensions are empty, set them if W is None or H is None: (H, W) = mainframe.shape[:2] FlagTwo = True if FlagTwo and not FlagOne: # record the start time startTime = datetime.now() timeDiff = 0 bufferFlag = 0 # create a temporary video file and initialize the video # writer object tempVideo = TempFile(ext=".mp4") writer = cv2.VideoWriter(tempVideo.path, cv2.VideoWriter_fourcc(*'avc1'), 5, (W, H), True) elif timeDiff > 30: bufferFlag = 1 # print(np.shape(myBuffer)) # print(np.shape(eventDetectedFrames)) x = ringBuffObj.get() x.extend(eventDetectedFrames) finalFrames = x for i in range(len(finalFrames)): # writing to a image array writer.write(finalFrames[i]) eventDetectedFrames = [] ringBuffObj = RingBuffer(0) ringBuffObj = RingBuffer(noOfBufferFrames) # release the video writer pointer and reset the # writer object writer.release() writer = None # calculate the time different between the current time and # start time # Making 30 sec video timeDiff = (datetime.now() - startTime).seconds endTime = datetime.now() totalSeconds = (endTime - startTime).seconds dateOpened = date.today().strftime("%A, %B %d %Y") # build the message and send a notification msg = "Hi, \nSome unusual activity is captured on {} at {} for {} " \ "seconds.".format(dateOpened, startTime.strftime("%I:%M%p"), totalSeconds) today = date.today() todayDt = today.strftime("%d/%m/%Y") # send the message and the video to the owner NameVideo, videoFileUrl = tn.send(msg, tempVideo) insertLogRec(todayDt, NameVideo, 'Video', 'Amazon S3', videoFileUrl) AmzTwilioFlag = 0 FlagOne = False FlagTwo = False # Upload to dropbox and entry log in spreadsheet dbImName, fileUrl = dropBoxUpload(dropBoxFrame) insertLogRec(todayDt, dbImName, 'Image', 'DropBox', fileUrl) # check to see if we should write the frame to disk if writer is not None: eventDetectedFrames.append(mainframe) timeDiff = (datetime.now() - startTime).seconds @app.route('/') @basic_auth.required def index(): return render_template('index.html') def gen(camera): while True: frame = camera.get_frame() yield (b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') @app.route('/video_feed') def video_feed(): return Response(gen(video_camera), mimetype='multipart/x-mixed-replace; boundary=frame') @app.route('/button', methods=["GET", "POST"]) def timelapse(): if request.method == "POST": print('I am here') req = request.form print(req) capt_time = req["Time"] print('capt_time =', capt_time) if capt_time == "" or capt_time == "Time": print("Please select valid Time to generate Time-lapse") else: aMpM = capt_time[-2:] capt_time = ''.join(capt_time.split()) capt_time = capt_time[:-2] capt_time_split = capt_time.split(":") if int(capt_time_split[0]) < 10: Hr = "0" + str(capt_time_split[0]) print('Hr =', Hr) else: Hr = str(capt_time_split[0]) Mn = str(capt_time_split[1]) Sec = '00' Time_2digit = Hr + ':' + Mn + ':' + Sec + ' ' + aMpM os.chdir("/home/pi/") mainsrc = "/home/pi/SecurityCamera/timelapse/" src = "/home/pi/SecurityCamera/tempTl/" # Python program to convert time # from 12 hour to 24 hour format # Function to convert the date format def convert24(str1): # Checking if last two elements of time # is AM and first two elements are 12 if str1[-2:] == "AM" and str1[:2] == "12": return "00" + str1[2:-2] # remove the AM elif str1[-2:] == "AM": return str1[:-2] # Checking if last two elements of time # is PM and first two elements are 12 elif str1[-2:] == "PM" and str1[:2] == "12": return str1[:-2] else: # add 12 to hours and remove PM return str(int(str1[:2]) + 12) + str1[2:8] capt_time_24fmt = convert24(Time_2digit).replace(':', '') today = date.today() todaydate = today.strftime('%Y%m%d') startDateTime = (str(todaydate) + ' ' + str(capt_time_24fmt)) startDateTime_Obj = datetime.strptime(startDateTime.strip(' \t\r\n'), '%Y%m%d %H%M%S') for i in range(30): start_plus_1 = startDateTime_Obj + timedelta(minutes=i) # print(start_plus_1) start_plus_1str = start_plus_1.strftime('%Y%m%d-%H%M') fileName = str(start_plus_1str) try: os.system("scp {}{}* {}".format(mainsrc, fileName, src)) except: print('Exception thown by code') TdDate = time.strftime('%Y%m%d') dt_string = datetime.now().strftime("%d%m%Y%H%M%S") mainsrc = "/home/pi/SecurityCamera/timelapse/" src = "/home/pi/SecurityCamera/tempTl/" ext = ".jpg" os.chdir("/home/pi/SecurityCamera/tempTl/") today = date.today() todayDt = today.strftime("%d/%m/%Y") os.chdir("/home/pi/") list = os.listdir(src) no_jpg = len(list) print('File count =', no_jpg) ii = 0 for filename in sorted(glob.glob(os.path.join(src, '*' + ext))): if not re.search('Image-\d\d\d' + re.escape(ext) + '$', filename): while True: newname = os.path.join(src, 'Image-{:06d}{}'.format(ii, ext)) if os.path.exists(newname): ii += 1 else: break print('renaming "%s" to "%s"...' % (filename, newname)) os.rename(filename, newname) if (no_jpg): os.system('ffmpeg -framerate 10 -i {}Image-%6d.jpg {}{}.mp4'.format(src, src, dt_string)) msg = "Hi, \nTime-lapse video requested by you is ready now. " print(msg) NameTlVideo, TlvideoFileUrl = tn.send(msg, '{}{}.mp4'.format(src, dt_string), True) insertLogRec(todayDt, NameTlVideo, 'Time-Lapse Video', 'Amazon S3', TlvideoFileUrl) os.system("rm /home/pi/SecurityCamera/tempTl/*") data = TlvideoFileUrl else: data = "NoDataFound" return render_template('index.html', data=data) if __name__ == '__main__': t = threading.Thread(target=check_for_objects, args=()) t.daemon = True t.start() app.run(host='0.0.0.0', debug=False) cv2.destroyAllWindows()