def deleteCCTV(oid): ## Dangerous route # return jsonify({"success": False, "message": "Forbidden. This is very dangerous."}), 403 if oid == None: return jsonify({ "success": False, "message": "No Object Id in param." }), 400 else: if "cctv" not in db.list_collection_names(): return jsonify({ "success": False, "message": "No Collection cctv." }), 404 else: result = db.cctv.delete_one({"_id": ObjectId(oid)}) if (result.deleted_count) > 0: if "video" in db.list_collection_names(): db.video.update_one({"_id": ObjectId(oid)}, {"$set": { "location_id": None }}) return jsonify({ "success": True, "message": "CCTV successfully deleted." }), 200 else: return jsonify({ "success": False, "message": "CCTV with provided id doesn't exist." }), 404
def generateReport(oid): try: if oid == None or len(oid) != 24: return jsonify({ "success": False, "message": "No Object Id in param." }), 400 elif "report" not in db.list_collection_names(): return jsonify({ "success": False, "message": "No Collection report." }), 404 else: report = db.report.find_one({"_id": ObjectId(oid)}) user = db.users.find_one({"_id": ObjectId(report['userId'])}) #generate report pdf_str = searchPDF_format(report, user) response = make_response(pdf_str) response.headers[ 'Content-Disposition'] = "attachment; filename='report.pdf" response.mimetype = 'application/pdf' return response, 200 except Exception as e: return f"An Error Occured: {e}"
def deleteReport(oid): if oid == None: return jsonify({ "success": False, "message": "No Object Id in param." }), 400 else: if "report" not in db.list_collection_names(): return jsonify({ "success": False, "message": "No Collection report." }), 404 else: result = db.report.delete_one({"_id": ObjectId(oid)}) if (result.deleted_count) > 0: return jsonify({ "success": True, "message": "Report successfully deleted." }), 200 else: return jsonify({ "success": False, "message": "Report with provided id doesn't exist." }), 404
def getVideoStats(): if "video" not in db.list_collection_names(): return jsonify({"success": False, "message": "No Video Collection."}), 400 else: count = db.video.find({}).count() prepared = db.video.find({"prepared": True}).count() unprepared = count - prepared return jsonify({"success": True, "count": count, "prepared": prepared, "unprepared": unprepared}), 200
def getVideoById(oid): if oid == None: return jsonify({"success": False, "message": "No Object Id in param."}), 400 else: if "video" not in db.list_collection_names(): return jsonify({"success": False, "message": "No Collection video."}), 404 else: video = db.video.find_one({"_id": ObjectId(oid)}) return dumps(video), 200
def getVideoByCCTV(oid): if oid == None: return jsonify({"success": False, "message": "No Object Id in param."}), 400 else: if "video" not in db.list_collection_names(): return jsonify({"success": False, "message": "No Collection video."}), 404 else: video = db.video.find({"location_id": oid, "prepared": True}) return dumps(video), 200
def getRecentVideo(): if "video" not in db.list_collection_names(): return jsonify({"success": False, "message": "No Video Collection."}), 400 else: videos = list(db.video.find({})) videos.sort(key=lambda x: datetime.strptime( x['date'], '%Y-%m-%d'), reverse=True) if len(videos) > 4: videos = videos[:4] return dumps(videos), 200
def getReport(oid): if oid == None: return jsonify({ "success": False, "message": "No Object Id in param." }), 400 if "report" not in db.list_collection_names(): return jsonify([]), 200 else: reports = list(db.report.find({"userId": oid})) return dumps(reports), 200
def getVideoSearch(): data = json.loads(request.data) search = data.get("search") if "video" not in db.list_collection_names() or search == None or search == "": return jsonify([]), 200 else: videos = list(db.video.find({})) items = [] for v in videos: if search.lower() in v['name'].lower(): items.append(v) return dumps(items), 200
def deletAllCCTV(): ## Dangerous route # return jsonify({"success": False, "message": "Forbidden. This is very dangerous."}), 403 if "cctv" not in db.list_collection_names(): return jsonify({ "success": False, "message": "No Collection cctv." }), 404 else: result = db.cctv.delete_many({}) if (result.deleted_count) > 0: if "video" in db.list_collection_names(): db.video.update_many({}, {"$set": {"location_id": None}}) return jsonify({ "success": True, "message": "All CCTVs successfully deleted." }), 200 else: return jsonify({ "success": True, "message": "CCTVs collection is already empty" }), 204
def getCCTVById(oid): if oid == None: return jsonify({ "success": False, "message": "No Object Id in param." }), 400 else: if "cctv" not in db.list_collection_names(): return jsonify({ "success": False, "message": "No Collection cctv." }), 404 else: cctv = db.cctv.find_one({"_id": ObjectId(oid)}) return dumps(cctv), 200
def getVideoFilter(): data = json.loads(request.data) filter = data.get("filter") print(filter) if "video" not in db.list_collection_names() or filter == None: return jsonify([]), 200 elif filterNone(filter) == None: videos = list(db.video.find({})) return dumps(videos), 200 else: videos = list(db.video.find({})) videos = filterByRecord(filter['record'], videos) videos = filterByDuration(filter['duration'], videos) videos = filterByType(filter['type'], videos) videos = sortBy(filter['sort'], videos) return dumps(videos), 200
def video_metadata(oid): try: print(oid) if oid == None or len(oid) != 24: return jsonify({ "success": False, "message": "No Object Id in param." }), 400 elif "features" not in db.list_collection_names(): return jsonify({ "success": False, "message": "No Collection features." }), 404 else: features = db.features.find_one({"video_id": oid}) return dumps(features), 200 except Exception as e: return f"An Error Occured: {e}"
def toggle_chart(oid): try: if oid == None or len(oid) != 24: return jsonify({"success": False, "message": "No Object Id in param."}), 400 elif "unique_person" not in db.list_collection_names(): return jsonify({"success": False, "message": "No Collection features."}), 404 else: data = db.unique_person.find( {"video_id": oid}, {"labels": 1, "colors": 1, "_id": 0}) new_data = [ [x+','+y for x, y in zip(t['labels'], t['colors'])] for t in data] meta = [_ for i in range(len(new_data)) for _ in new_data[i]] cc = Counter(meta) features = [{"from": key.split(",")[0], "to": key.split(",")[ 1], "value": cc[key]} for key in cc] return jsonify({"status": True, "message": "Toggle Chord Chart!!", "metadata": features}), 200 except Exception as e: return f"An Error Occured: {e}"
def processVideo(oid): print(oid) if oid == None or len(oid) != 24: return jsonify({ "success": False, "message": "No Object Id in param." }), 400 elif "video" not in db.list_collection_names(): return jsonify({ "success": False, "message": "No Collection video." }), 404 else: video = db.video.find_one({"_id": ObjectId(oid)}) if video['prepared'] == True: return jsonify({ "success": False, "message": "Video is already processed." }), 404 elif video['processing'] == True: return jsonify({ "success": False, "message": "Video is currently being processed." }), 404 else: # save timestamp info in the video collection date = video['date'] time = video['time'] timestamp = json.dumps(datetime.strptime(date + time, '%Y-%m-%d%H:%M:%S'), ensure_ascii=False, indent=4, default=str) file_id = video["file_id"] processor(oid, file_id, timestamp) executor.submit(processor) db.video.update({"_id": ObjectId(oid)}, {"$set": { "processing": True }}) return jsonify({ "success": True, "message": "Video will be processed in a while!" }), 200
def deleteVideo(oid): if oid == None: return jsonify({"success": False, "message": "No Object Id in param."}), 400 else: if "video" not in db.list_collection_names(): return jsonify({"success": False, "message": "No Collection video."}), 404 else: video = db.video.find_one({"_id": ObjectId(oid)}) try: fs.delete(ObjectId(video["file_id"])) fs.delete(ObjectId(video["thumbnail_id"])) except Exception as e: print(e) return jsonify({"success": False, "message": "Delete operation failed."}), 404 result = db.video.delete_one({"_id": ObjectId(oid)}) if (result.deleted_count) > 0: return jsonify({"success": True, "message": "Video successfully deleted."}), 200 else: return jsonify({"success": False, "message": "Video with provided id doesn't exist."}), 404
def search_report(oid): try: if oid == None or len(oid) != 24: return jsonify({ "success": False, "message": "No Object Id in param." }), 400 elif "unique_person" not in db.list_collection_names(): return jsonify({ "success": False, "message": "No Collection features." }), 404 else: return jsonify({ "status": True, "message": "Report Generated", "Attachment": response }), 200 except Exception as e: return f"An Error Occured: {e}"
def getCCTV(): if "cctv" not in db.list_collection_names(): return jsonify([]), 200 else: cctvs = list(db.cctv.find({})) return dumps(cctvs), 200
def generateVideoReport(oid): try: if oid == None or len(oid) != 24: return jsonify({ "success": False, "message": "No Object Id in param." }), 400 elif "unique_person" not in db.list_collection_names(): return jsonify({ "success": False, "message": "No Collection features." }), 404 else: #query db feature = db.features.find_one({"video_id": oid}) data = db.unique_person.find({"video_id": oid}, { "labels": 1, "colors": 1, "_id": 0 }) video = db.video.find({"_id": ObjectId(oid)}) #line chart line_chart = { x['frame_sec']: len(json.loads(x['persons'])) for x in feature['metadata'] } # print(line_chart) #plotting plt.plot(list(line_chart.keys()), list(line_chart.values())) plt.title('TimeFrame Vs No. of persons') plt.xlabel('TimeFrame') plt.ylabel('No. of persons') # plt.savefig("line.pdf") linechart_buf = image_to_buffer(plt) #heat Map new_data = [[ x + ',' + y for x, y in zip(t['labels'], t['colors']) ] for t in data] meta = [_ for i in range(len(new_data)) for _ in new_data[i]] cc = Counter(meta) colors = [key.split(",")[1] for key in cc] features = AutoVivification() for key in cc: if key.split(",")[0] not in features.keys(): for x in colors: features[key.split(",")[0]][x] = 0 features[key.split(",")[0]][key.split(",")[1]] = cc[key] # print(features) corr = [list(val.values()) for val in features.values()] #plotting fig = plt.figure(figsize=(12, 10), dpi=80, facecolor=(1, 1, 1)) sns.heatmap(corr, xticklabels=list(list(features.values())[0].keys()), yticklabels=list(features.keys()), cmap='RdYlGn', center=0, annot=True) plt.title('Relationship between Labels and resp. Colors', fontsize=14) plt.xticks(fontsize=8) plt.yticks(fontsize=8) # plt.savefig("heat.pdf") heatmap_buf = image_to_buffer(plt) #pie chart pie_chart = Counter( list( chain(*[ list( chain(*[ x['labels'] for x in json.loads(metadata['persons']) ])) for metadata in feature['metadata'] ]))) #plotting # print(pie_chart) fig = plt.figure() ax = fig.add_axes([0, 0, 1, 1]) ax.axis('equal') ax.pie(list(pie_chart.values()), labels=list(pie_chart.keys()), autopct='%1.2f%%') # pl.savefig("pie.pdf") piechart_buf = image_to_buffer(plt) #generate_pdf pdf_str = videoPDF_format(video, line_chart, linechart_buf, heatmap_buf, piechart_buf) response = make_response(pdf_str) response.headers[ 'Content-Disposition'] = "attachment; filename='report.pdf" response.mimetype = 'application/pdf' linechart_buf.truncate(0) piechart_buf.truncate(0) heatmap_buf.truncate(0) plt.clf() return response, 200 except Exception as e: return f"An Error Occured: {e}"
def getVideo(): if "video" not in db.list_collection_names(): return jsonify([]), 200 else: videos = list(db.video.find({})) return dumps(videos), 200