· 5 years ago · Sep 23, 2020, 08:14 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("1054564599:AAF6kqAC_8haOPmcFO9SlytJB0RB9vbW8fk", 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# import pandas as pd
72
73# INFLUXDB
74# client = InfluxDBClient('vps656540.ovh.net', 3306, 'master26', 'master26_', 'TRIALDB')
75# client.create_database('TRIALDB') # Problems with DB creation
76# ---------------------
77# SUB-DIRECTORY CREATION
78working_path = os.getcwd()
79# sub_directory = "Image"
80# path = os.path.join(working_path, sub_directory)
81path = working_path
82os.makedirs(path, exist_ok = True)
83print(path)
84# ---------------------
85# CAFFE construct the argument parse and parse the arguments
86ap = argparse.ArgumentParser()
87ap.add_argument("-i", "--image", required=True,
88 help="path to input image")
89ap.add_argument("-p", "--prototxt", required=True,
90 help="path to Caffe 'deploy' prototxt file")
91ap.add_argument("-m", "--model", required=True,
92 help="path to Caffe pre-trained model")
93ap.add_argument("-c", "--confidence", type=float, default=0.2,
94 help="minimum probability to filter weak detections")
95args = vars(ap.parse_args())
96CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat",
97 "bottle", "bus", "car", "cat", "chair", "cow", "diningtable",
98 "dog", "horse", "motorbike", "person", "pottedplant", "sheep",
99 "sofa", "train", "tvmonitor"]
100COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))
101print("[INFO] loading model…")
102image = cv2.imread(args["image"])
103net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"])
104(h, w) = image.shape[:2]
105blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 0.007843, (300, 300), 127.5)
106print("[INFO] computing object detections…")
107print(blob.shape)
108net.setInput(blob)
109detections = net.forward()
110# ---------------------
111# RECTANGLE LISTS DEFINITION BASED ON APPLE.JPG + ZONE COUNTER CREATION
112StartXlist = [1,230,580,30,275,460,155,295,415,200,300,390]
113StartYlist = [265,265,265,120,120,120,68,68,68,40,40,40]
114EndXlist = [90,430,640,210,380,620,240,355,510,255,355,465]
115EndYlist = [420,420,420,220,220,220,110,110,110,65,65,65]
116PeopleinZone=[0,0,0,0,0,0,0,0,0,0,0,0]
117LimitpeopleZone= [3,3,3,3,3,3,3,3,3,3,3,3]
118Risk = ["NO","NO","NO","NO","NO","NO","NO","NO","NO","NO","NO","NO"]
119# ---------------------
120for r in range(0,12):
121 cv2.rectangle(image, (StartXlist[r], StartYlist[r]), (EndXlist[r], EndYlist[r]), (0,255,255), 2) # Black color in BGR
122 y = StartYlist[r] - 15 if StartYlist[r] - 15 > 15 else StartYlist[r] + 15
123 cv2.putText(image,'Zone'+str(r+1), (StartXlist[r], y),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,255), 2)
124
125for i in np.arange(0, detections.shape[2]):
126 confidence = detections[0, 0, i, 2]
127
128 if confidence > args["confidence"]:
129 idx = int(detections[0, 0, i, 1])
130 box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
131 (startX, startY, endX, endY) = box.astype("int")
132 # 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))
133 # 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")})
134 # print("[INFO] {}".format(label))
135 # print(label3)
136 # var person = { "name": "John", "age": 31, "city": "New York" }; JSON FORMAT FOUND
137
138 ## Create table
139 # val1 = json.loads(label3)
140 # print(*val1)
141
142 # df = pd.DataFrame(val1, index=list(range(1)))
143 # print(df)
144 ##
145 if CLASSES[idx] == "person":
146 for j in range(0,12):
147 dx= min(EndXlist[j],endX)-max(StartXlist[j],startX)
148 dy= min(EndYlist[j],endY)-max(StartYlist[j],startY)
149 if (dx>=0) and (dy>=0):
150 PeopleinZone[j]+= 1
151 # print("Zone"+str(j+1)+" dx: "+str(dx)+"dy: "+str(dy))
152 # print(PeopleinZone)
153
154print(PeopleinZone)
155# ---------------------
156# MYSQL
157mydb = mysql.connector.connect( host="localhost", user="admin", password="chikulate200827")
158# Check if connection was successful
159if (mydb):
160 # Carry out normal procedure
161 print ("Connection successful")
162else:
163 # Terminate
164 print ("Connection unsuccessful")
165mycursor = mydb.cursor()
166dbname="TFM40"
167mySql_Create_db = "CREATE DATABASE IF NOT EXISTS "+dbname
168mycursor.execute(mySql_Create_db)
169mysql_use_db = "USE "+dbname
170mycursor.execute(mysql_use_db)
171x = datetime.now()
172tablename="T"+str(x.year)+str(x.month)+str(x.day)
173# 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))"
174mySql_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)"
175print(mySql_Create_Table2)
176mycursor.execute (mySql_Create_Table2)
177# sql_insert = "INSERT INTO "+dbname+"."+tablename+" (Classification,Confidence,startX,startY,EndX,EndY,Timestamp) VALUES (%s,%s,%s,%s,%s,%s,%s)"
178sql_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)"
179# val = (str(CLASSES[idx]),str(round(confidence * 100, 1)),str(startX),str(startY),str(endX),str(endY),str(x))
180val2 = ('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))
181# mycursor.execute(sql_insert,(val))
182mycursor.execute(sql_insert2,(val2))
183# mycursor.execute(sql_insert,(val,)) WORKS BUT IT IS FOR TUPLES
184mydb.commit()
185
186
187
188 # python main.py --prototxt MobileNetSSD_deploy.prototxt --model MobileNetSSD_deploy.caffemodel --image EXECUTION
189
190 # cursor.close()
191
192
193
194 # mydb.close()
195
196 # INFLUXDB
197
198 # client = InfluxDBClient(host, port, user, password, dbname)
199 # client = InfluxDBClient('vps656540.ovh.net', 3306, 'master26', 'master26_', 'TRIALDB')
200 # client.create_database('TRIALDB')
201 #DRAW SQUARE
202 #cv2.rectangle(image, (startX, startY), (endX, endY), COLORS[idx], 2) DEFINE OBJECTS DETECTED SQUARE
203
204 #y = startY - 15 if startY - 15 > 15 else startY + 15 VERTICAL POSITION OF CLASS TITLE
205 #cv2.putText(image, label, (startX, y),cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLORS[idx], 2) TITLE INSERTION INTO IMAGE
206cv2.imshow("Output", image)
207#cv2.imwrite('C:/Users/César/Pictures/hall.jpg', image)
208cv2.imwrite(os.path.join(path, '/hall.jpg'), image)
209print(os.path.join(path, 'hall.jpg'))
210cv2.waitKey(10000) # 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__':
233 main_telegram()
234# --------------------------------------------------------------------------------------------------------------------------
235