· 5 years ago · Sep 23, 2020, 06:20 PM
1import numpy as np
2import argparse
3import cv2
4import time
5import mysql.connector
6import json
7from datetime import datetime
8from influxdb import InfluxDBClient
9import ast
10import os
11import logging
12from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
13import threading
14
15# ---------------------
16# TELEGRAM Handlers
17def people_total(update, context):
18 update.message.reply_text('Total number of people present in store:' + str(total))
19
20def zone_risk(update, context):
21 update.message.reply_text('Risky zones due to people presence'+ label2)
22
23def echo(update, context):
24 """Echo the user message."""
25 update.message.reply_text('Total number of people is:'+ label)
26 # update.message.reply_text(update.message.text)
27
28def pic(update, context):
29 chat_id = update.message.chat_id # get the recipient´s ID
30 #context.bot.sendPhoto(chat_id=chat_id, photo=open(path, 'rb'))
31 context.bot.sendPhoto(chat_id=chat_id, photo=open('./hall.jpg', 'rb'))
32
33def main_telegram():
34 """Start the bot."""
35 # Create the Updater and pass it your bot's token.
36 # Make sure to set use_context=True to use the new context based callbacks
37 # Post version 12 this will no longer be necessary
38 updater = Updater("xxxx", use_context=True)
39
40 # Get the dispatcher to register handlers
41 dp = updater.dispatcher
42
43 # on different commands - answer in Telegram
44 dp.add_handler(CommandHandler("people", people_total))
45 dp.add_handler(CommandHandler("risk", zone_risk))
46 dp.add_handler(CommandHandler("picture", pic))
47
48 # on noncommand i.e message - echo the message on Telegram
49 dp.add_handler(MessageHandler(Filters.text & ~Filters.command, echo))
50
51
52 # Start the Bot
53 updater.start_polling()
54
55 # Run the bot until you press Ctrl-C or the process receives SIGINT,
56 # SIGTERM or SIGABRT. This should be used most of the time, since
57 # start_polling() is non-blocking and will stop the bot gracefully.
58# updater.idle()
59# ---------------------
60# TELEGRAM Enable logging
61logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
62 level=logging.INFO)
63
64logger = logging.getLogger(__name__)
65# ---------------------
66# THREADING
67# threading.Thread(target=main_telegram).start()
68x = threading.Thread(target=main_telegram, args=())
69# x.start()
70# ---------------------
71
72# import pandas as pd
73
74# INFLUXDB
75# client = InfluxDBClient('xxxx', 3306, 'xxx', 'xxx', 'TRIALDB')
76# client.create_database('TRIALDB') # Problems with DB creation
77# ---------------------
78# SUB-DIRECTORY CREATION
79working_path = os.getcwd()
80# sub_directory = "Image"
81# path = os.path.join(working_path, sub_directory)
82path = working_path
83os.makedirs(path, exist_ok = True)
84print(path)
85# ---------------------
86# CAFFE construct the argument parse and parse the arguments
87ap = argparse.ArgumentParser()
88ap.add_argument("-i", "--image", required=True,
89 help="path to input image")
90ap.add_argument("-p", "--prototxt", required=True,
91 help="path to Caffe 'deploy' prototxt file")
92ap.add_argument("-m", "--model", required=True,
93 help="path to Caffe pre-trained model")
94ap.add_argument("-c", "--confidence", type=float, default=0.2,
95 help="minimum probability to filter weak detections")
96args = vars(ap.parse_args())
97CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat",
98 "bottle", "bus", "car", "cat", "chair", "cow", "diningtable",
99 "dog", "horse", "motorbike", "person", "pottedplant", "sheep",
100 "sofa", "train", "tvmonitor"]
101COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))
102print("[INFO] loading model…")
103image = cv2.imread(args["image"])
104net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"])
105(h, w) = image.shape[:2]
106blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 0.007843, (300, 300), 127.5)
107print("[INFO] computing object detections…")
108print(blob.shape)
109net.setInput(blob)
110detections = net.forward()
111# ---------------------
112# RECTANGLE LISTS DEFINITION BASED ON APPLE.JPG + ZONE COUNTER CREATION
113StartXlist = [1,230,580,30,275,460,155,295,415,200,300,390]
114StartYlist = [265,265,265,120,120,120,68,68,68,40,40,40]
115EndXlist = [90,430,640,210,380,620,240,355,510,255,355,465]
116EndYlist = [420,420,420,220,220,220,110,110,110,65,65,65]
117PeopleinZone=[0,0,0,0,0,0,0,0,0,0,0,0]
118LimitpeopleZone= [3,3,3,3,3,3,3,3,3,3,3,3]
119Risk = ["NO","NO","NO","NO","NO","NO","NO","NO","NO","NO","NO","NO"]
120# ---------------------
121for r in range(0,12):
122 cv2.rectangle(image, (StartXlist[r], StartYlist[r]), (EndXlist[r], EndYlist[r]), (0,255,255), 2) # Black color in BGR
123 y = StartYlist[r] - 15 if StartYlist[r] - 15 > 15 else StartYlist[r] + 15
124 cv2.putText(image,'Zone'+str(r+1), (StartXlist[r], y),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,255), 2)
125
126for i in np.arange(0, detections.shape[2]):
127 confidence = detections[0, 0, i, 2]
128
129 if confidence > args["confidence"]:
130 idx = int(detections[0, 0, i, 1])
131 box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
132 (startX, startY, endX, endY) = box.astype("int")
133 # label = '{}"class": {}, "confidence": {:.4f}, "startX": {}, "startY": {}, "EndX": {}, "EndY": {}, "Timestamp": {}{}'.format(chr(123),chr(34)+CLASSES[idx]+chr(34), confidence,startX,startY,endX,endY,chr(34)+str(datetime.now())+chr(34),chr(125))
134 # label = json.dumps({'class': CLASSES[idx],"confidence": str(round(confidence * 100, 1)) + "%","startX": str(startX),"startY": str(startY),"EndX": str(endX),"EndY": str(endY),"Timestamp": datetime.now().strftime("%d/%m/%Y, %H:%M")})
135 # print("[INFO] {}".format(label))
136 # print(label3)
137 # var person = { "name": "John", "age": 31, "city": "New York" }; JSON FORMAT FOUND
138
139 ## Create table
140 # val1 = json.loads(label3)
141 # print(*val1)
142
143 # df = pd.DataFrame(val1, index=list(range(1)))
144 # print(df)
145 ##
146 if CLASSES[idx] == "person":
147 for j in range(0,12):
148 dx= min(EndXlist[j],endX)-max(StartXlist[j],startX)
149 dy= min(EndYlist[j],endY)-max(StartYlist[j],startY)
150 if (dx>=0) and (dy>=0):
151 PeopleinZone[j]+= 1
152 # print("Zone"+str(j+1)+" dx: "+str(dx)+"dy: "+str(dy))
153 # print(PeopleinZone)
154
155print(PeopleinZone)
156# ---------------------
157# MYSQL
158mydb = mysql.connector.connect( host="xxx", user="xxxx", password="xxx")
159# Check if connection was successful
160if (mydb):
161 # Carry out normal procedure
162 print ("Connection successful")
163else:
164 # Terminate
165 print ("Connection unsuccessful")
166mycursor = mydb.cursor()
167dbname="TFM40"
168mySql_Create_db = "CREATE DATABASE IF NOT EXISTS "+dbname
169mycursor.execute(mySql_Create_db)
170mysql_use_db = "USE "+dbname
171mycursor.execute(mysql_use_db)
172x = datetime.now()
173tablename="T"+str(x.year)+str(x.month)+str(x.day)
174# mySql_Create_Table = "CREATE TABLE IF NOT EXISTS "+tablename +"(id int AUTO_INCREMENT PRIMARY KEY, Classification varchar(250), Confidence varchar(250), StartX varchar(250), StartY varchar(250), EndX varchar(250), EndY varchar(250), Timestamp varchar(250))"
175mySql_Create_Table2 = "CREATE TABLE IF NOT EXISTS "+tablename +"(id int AUTO_INCREMENT PRIMARY KEY, Camera varchar(250), Zone1 float, Zone2 float, Zone3 float, Zone4 float, Zone5 float, Zone6 float, Zone7 float, Zone8 float, Zone9 float, Zone10 float, Zone11 float, Zone12 float, Timestamp timestamp)"
176print(mySql_Create_Table2)
177mycursor.execute (mySql_Create_Table2)
178# sql_insert = "INSERT INTO "+dbname+"."+tablename+" (Classification,Confidence,startX,startY,EndX,EndY,Timestamp) VALUES (%s,%s,%s,%s,%s,%s,%s)"
179sql_insert2 = "INSERT INTO "+dbname+"."+tablename+" (Camera, Zone1, Zone2, Zone3, Zone4, Zone5, Zone6, Zone7, Zone8, Zone9, Zone10, Zone11, Zone12, Timestamp) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
180# val = (str(CLASSES[idx]),str(round(confidence * 100, 1)),str(startX),str(startY),str(endX),str(endY),str(x))
181val2 = ('hall',PeopleinZone[0],PeopleinZone[1],PeopleinZone[2],PeopleinZone[3],PeopleinZone[4],PeopleinZone[5],PeopleinZone[6],PeopleinZone[7],PeopleinZone[8],PeopleinZone[9],PeopleinZone[10],PeopleinZone[11],str(x))
182# mycursor.execute(sql_insert,(val))
183mycursor.execute(sql_insert2,(val2))
184# mycursor.execute(sql_insert,(val,)) WORKS BUT IT IS FOR TUPLES
185mydb.commit()
186
187
188
189 # python main.py --prototxt MobileNetSSD_deploy.prototxt --model MobileNetSSD_deploy.caffemodel --image EXECUTION
190
191 # cursor.close()
192
193
194
195 # mydb.close()
196
197 # INFLUXDB
198
199 # client = InfluxDBClient(host, port, user, password, dbname)
200 # client = InfluxDBClient('vps656540.ovh.net', 3306, 'master26', 'master26_', 'TRIALDB')
201 # client.create_database('TRIALDB')
202 #DRAW SQUARE
203 #cv2.rectangle(image, (startX, startY), (endX, endY), COLORS[idx], 2) DEFINE OBJECTS DETECTED SQUARE
204
205 #y = startY - 15 if startY - 15 > 15 else startY + 15 VERTICAL POSITION OF CLASS TITLE
206 #cv2.putText(image, label, (startX, y),cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLORS[idx], 2) TITLE INSERTION INTO IMAGE
207cv2.imshow("Output", image)
208cv2.imwrite(os.path.join(path, '\hall.jpg'), image)
209print(os.path.join(path, 'hall.jpg'))
210cv2.waitKey(20000) # video (cambiamos un 0 por un 1)
211# --------------------------------------------------------------------------------------------------------------------------
212# TELEGRAM
213# label = '{}"Camera": {}, "Zone1": {}, "Zone2": {}, "Zone3": {}, "Zone4": {}, "Zone5": {}, "Zone6": {}, "Zone7": {}, "Zone8": {}, "Zone9": {}, "Zone10": {},"Zone11": {},"Zone12": {}, "Timestamp": {}{}'.format(chr(123),chr(34)+'hall'+chr(34), PeopleinZone[0],PeopleinZone[1],PeopleinZone[2],PeopleinZone[3],PeopleinZone[4],PeopleinZone[5],PeopleinZone[6],PeopleinZone[7],PeopleinZone[8],PeopleinZone[9],PeopleinZone[10],PeopleinZone[11],chr(34)+str(datetime.now())+chr(34),chr(125))
214# QUESTION & ANSWER 1
215total=0
216maximum=0
217for z in range(0,12):
218 total += PeopleinZone[z]
219 maximum += LimitpeopleZone[z]
220 if PeopleinZone[z]>= LimitpeopleZone[z]:
221 Risk[z] ='YES'
222 else:
223 Risk[z] ='NO'
224label = json.dumps({"Total people" : total, "Remaining people to reach limit" : (maximum - total),"Timestamp": datetime.now().strftime("%d/%m/%Y, %H:%M")})
225print(label)
226# ---------------------
227# QUESTION & ANSWER 2
228# label2 = json.dumps({"Camera": "hall", "Zone1": PeopleinZone[0],"Zone2": PeopleinZone[1],"Zone3": PeopleinZone[2],"Zone4": PeopleinZone[3],"Zone5": PeopleinZone[4],"Zone6": PeopleinZone[5],"Zone7": PeopleinZone[6],"Zone8": PeopleinZone[7],"Zone9": PeopleinZone[8],"Zone10": PeopleinZone[9],"Zone11": PeopleinZone[10],"Zone12": PeopleinZone[11],"Timestamp": datetime.now().strftime("%d/%m/%Y, %H:%M")})
229label2 = json.dumps({"Camera": "hall", "Zone1 Risk": Risk[0],"Zone2 Risk": Risk[1],"Zone3 Risk": Risk[2],"Zone4 Risk": Risk[3],"Zone5 Risk": Risk[4],"Zone6 Risk": Risk[5],"Zone7 Risk": Risk[6],"Zone8 Risk": Risk[7],"Zone9 Risk": Risk[8],"Zone10 Risk": Risk[9],"Zone11 Risk": Risk[10],"Zone12 Risk": Risk[11],"Timestamp": datetime.now().strftime("%d/%m/%Y, %H:%M")})
230print(label2)
231# ---------------------
232if __name__ == '__main_telegram__':
233 main_telegram()
234# --------------------------------------------------------------------------------------------------------------------------