|
@@ -8,52 +8,28 @@
|
|
|
"""
|
|
|
import base64
|
|
|
import json
|
|
|
+import logging
|
|
|
import os
|
|
|
+import threading
|
|
|
import time
|
|
|
-import glob
|
|
|
-import urllib
|
|
|
-from urllib.parse import quote, parse_qs, unquote
|
|
|
|
|
|
import apns2
|
|
|
import boto3
|
|
|
import jpush
|
|
|
-import oss2
|
|
|
-import paypalrestsdk
|
|
|
-import threading
|
|
|
-import calendar
|
|
|
-import datetime
|
|
|
-import logging
|
|
|
-import sys
|
|
|
-import requests
|
|
|
-from aliyunsdkcore import client
|
|
|
-from aliyunsdksts.request.v20150401 import AssumeRoleRequest
|
|
|
from boto3.session import Session
|
|
|
-from django.http import JsonResponse, HttpResponseRedirect, HttpResponse
|
|
|
-from django.db import transaction
|
|
|
from django.views.generic.base import View
|
|
|
-import jwt
|
|
|
-from Object.ETkObject import ETkObject
|
|
|
from pyfcm import FCMNotification
|
|
|
-from AnsjerPush.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, OSS_ROLE_ARN, SERVER_DOMAIN, PAYPAL_CRD, \
|
|
|
- SERVER_DOMAIN_SSL, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_ARN, APNS_MODE, APNS_CONFIG, BASE_DIR, \
|
|
|
- JPUSH_CONFIG, FCM_CONFIG, OAUTH_ACCESS_TOKEN_SECRET
|
|
|
-from Model.models import UidPushModel, AiService, Equipment_Info
|
|
|
-from Object.RedisObject import RedisObject
|
|
|
+
|
|
|
+from AnsjerPush.config import AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, APNS_MODE, APNS_CONFIG, BASE_DIR, \
|
|
|
+ JPUSH_CONFIG, FCM_CONFIG
|
|
|
+from Model.models import UidPushModel, AiService
|
|
|
+from Object import MergePic
|
|
|
+from Object.ETkObject import ETkObject
|
|
|
from Object.ResponseObject import ResponseObject
|
|
|
from Object.TokenObject import TokenObject
|
|
|
-from Object.UidTokenObject import UidTokenObject
|
|
|
from Object.utils import LocalDateTimeUtil
|
|
|
from Service.CommonService import CommonService
|
|
|
-from django.db.models import Q, F, Count
|
|
|
-from decimal import Decimal
|
|
|
-from AnsjerPush.config import SERVER_TYPE
|
|
|
from Service.EquipmentInfoService import EquipmentInfoService
|
|
|
-from Service.ModelService import ModelService
|
|
|
-from Object import MergePic
|
|
|
-import boto3
|
|
|
-import botocore
|
|
|
-from botocore import client
|
|
|
-
|
|
|
|
|
|
|
|
|
# AI服务
|
|
@@ -93,14 +69,13 @@ class AiView(View):
|
|
|
else:
|
|
|
return response.json(414)
|
|
|
|
|
|
-
|
|
|
- def do_ai_identification(self, request_dict,response):
|
|
|
+ def do_ai_identification(self, request_dict, response):
|
|
|
etk = request_dict.get('etk', None)
|
|
|
n_time = request_dict.get('n_time', None)
|
|
|
channel = request_dict.get('channel', '1')
|
|
|
receiveTime = int(time.time())
|
|
|
logger = logging.getLogger('info')
|
|
|
- logger.info('-----------into----ai--api')
|
|
|
+ logger.info('进入-----------into----ai--api')
|
|
|
logger.info("etk={etk}".format(etk=etk))
|
|
|
if not etk:
|
|
|
return response.json(444)
|
|
@@ -114,13 +89,13 @@ class AiView(View):
|
|
|
return response.json(444)
|
|
|
|
|
|
##通过uid查出endTime是否过期,并且ai开关是否打开
|
|
|
- AiServiceQuery = AiService.objects.filter(uid=uid, detect_status=1, use_status=1, endTime__gt=receiveTime).\
|
|
|
+ AiServiceQuery = AiService.objects.filter(uid=uid, detect_status=1, use_status=1, endTime__gt=receiveTime). \
|
|
|
values('detect_group')
|
|
|
if not AiServiceQuery.exists():
|
|
|
logger.info('none-----aiService')
|
|
|
return response.json(173)
|
|
|
detect_group = AiServiceQuery[0]['detect_group']
|
|
|
- #{}??
|
|
|
+ # {}??
|
|
|
#
|
|
|
file_post_one = request_dict.get('fileOne', None)
|
|
|
file_post_two = request_dict.get('fileTwo', None)
|
|
@@ -132,7 +107,7 @@ class AiView(View):
|
|
|
if not all(file_list):
|
|
|
for k, val in enumerate(file_list):
|
|
|
if not val:
|
|
|
- return response.json(444,'缺少第{k}张图'.format(k=k+1))
|
|
|
+ return response.json(444, '缺少第{k}张图'.format(k=k + 1))
|
|
|
|
|
|
dir_path = os.path.join(BASE_DIR, 'static/ai/' + uid + '/' + str(n_time))
|
|
|
if not os.path.exists(dir_path):
|
|
@@ -150,12 +125,12 @@ class AiView(View):
|
|
|
image_size = 0 # 每张小图片的大小,等于0是按原图大小进行合并
|
|
|
image_colnum = 1 # 合并成一张图后,一行有几个小图
|
|
|
image_size = MergePic.merge_images(dir_path, image_size, image_colnum)
|
|
|
- photo = open(dir_path + '.jpg', 'rb') #打开合成图
|
|
|
+ photo = open(dir_path + '.jpg', 'rb') # 打开合成图
|
|
|
|
|
|
# photo = open(r'E:\test---------------\test\snipaste20220121_215952.jpg', 'rb')
|
|
|
- #识别合成图片
|
|
|
- maxLabels = 50 #最大标签
|
|
|
- minConfidence = 95 #置信度
|
|
|
+ # 识别合成图片
|
|
|
+ maxLabels = 50 # 最大标签
|
|
|
+ minConfidence = 95 # 置信度
|
|
|
|
|
|
ai_start_time = int(time.time())
|
|
|
client = boto3.client(
|
|
@@ -175,7 +150,7 @@ class AiView(View):
|
|
|
# rekognition_res = json.loads(rekognition_res)
|
|
|
|
|
|
ai_end_time = int(time.time())
|
|
|
- labels = self.labelsCoords(detect_group, rekognition_res, image_size, n_time) #检查标签是否符合用户选择的识别类型
|
|
|
+ labels = self.labelsCoords(detect_group, rekognition_res, image_size, n_time) # 检查标签是否符合用户选择的识别类型
|
|
|
# return response.json(0,labels)
|
|
|
if len(labels['label_list']) == 0:
|
|
|
# 需要删除图片
|
|
@@ -192,12 +167,12 @@ class AiView(View):
|
|
|
# 上传缩略图到s3
|
|
|
for i, val in enumerate(file_path_list):
|
|
|
upload_path = "{uid}/{channel}/{n_time}_{i}.jpeg".format(uid=uid, channel=channel,
|
|
|
- n_time=n_time,i=i) # 封面图
|
|
|
+ n_time=n_time, i=i) # 封面图
|
|
|
thread_task = threading.Thread(target=self.upload_s3, args=(val, upload_path))
|
|
|
thread_task.start()
|
|
|
|
|
|
- #存储消息以及推送
|
|
|
- is_st = 4 #ai多图
|
|
|
+ # 存储消息以及推送
|
|
|
+ is_st = 4 # ai多图
|
|
|
# 查询推送数据
|
|
|
uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid). \
|
|
|
values('token_val', 'app_type', 'appBundleId', 'm_code', 'push_type', 'userID_id',
|
|
@@ -229,6 +204,7 @@ class AiView(View):
|
|
|
if tz is None or tz == '':
|
|
|
tz = 0
|
|
|
local_date_time = CommonService.get_now_time_str(n_time=n_time, tz=tz, lang='cn')
|
|
|
+ logger.info('----AI消息存库{},{},{}'.format(uid, local_date_time, tz))
|
|
|
local_date_time = local_date_time[0:10]
|
|
|
# 以下是存库
|
|
|
userID_id = up["userID_id"]
|
|
@@ -242,7 +218,7 @@ class AiView(View):
|
|
|
device_uid=uid,
|
|
|
device_nick_name=nickname,
|
|
|
channel=channel,
|
|
|
- alarm='检查到{labels} \tChannel:{channel}'.format(labels=label_str,channel=channel),
|
|
|
+ alarm='检查到{labels} \tChannel:{channel}'.format(labels=label_str, channel=channel),
|
|
|
is_st=is_st,
|
|
|
receive_time=receiveTime,
|
|
|
add_time=now_time,
|
|
@@ -279,7 +255,8 @@ class AiView(View):
|
|
|
# res = self.do_fcm(**kwargs)
|
|
|
# apns_end_time = int(time.time())
|
|
|
except Exception as e:
|
|
|
- logger.info("errLine={errLine}, errMsg={errMsg}".format(errLine=e.__traceback__.tb_lineno,errMsg=repr(e)))
|
|
|
+ logger.info(
|
|
|
+ "errLine={errLine}, errMsg={errMsg}".format(errLine=e.__traceback__.tb_lineno, errMsg=repr(e)))
|
|
|
continue
|
|
|
# 需要删除图片
|
|
|
photo.close()
|
|
@@ -287,15 +264,17 @@ class AiView(View):
|
|
|
self.del_path(dir_path + '.jpg')
|
|
|
# 分表批量存储
|
|
|
if eq_list and len(eq_list) > 0:
|
|
|
+ logger.info("AI存库中........")
|
|
|
week = LocalDateTimeUtil.date_to_week(local_date_time)
|
|
|
- EquipmentInfoService.equipment_info_bulk_create(week, eq_list)
|
|
|
+ result = EquipmentInfoService.equipment_info_bulk_create(week, eq_list)
|
|
|
+ logger.info("-.-存库结果{}".format(result))
|
|
|
return response.json(0)
|
|
|
|
|
|
except Exception as e:
|
|
|
print(e)
|
|
|
data = {
|
|
|
- 'errLine':e.__traceback__.tb_lineno,
|
|
|
- 'errMsg':repr(e)
|
|
|
+ 'errLine': e.__traceback__.tb_lineno,
|
|
|
+ 'errMsg': repr(e)
|
|
|
}
|
|
|
return response.json(48, data)
|
|
|
|
|
@@ -314,7 +293,6 @@ class AiView(View):
|
|
|
os.remove(c_path)
|
|
|
os.rmdir(path)
|
|
|
|
|
|
-
|
|
|
## 检查是否有符合条件的标签,并且返回标签坐标位置信息
|
|
|
def labelsCoords(self, user_detect_group, rekognition_res, image_size, n_time):
|
|
|
logger = logging.getLogger('info')
|
|
@@ -327,7 +305,7 @@ class AiView(View):
|
|
|
'2': ['Dog', 'Pet', 'Canine', 'Animal', 'Puppy', 'Cat'], # 动物
|
|
|
'3': ['Car', 'Vehicle', 'Transportation', 'Automobile'] # 车
|
|
|
}
|
|
|
- #找出识别的所有标签
|
|
|
+ # 找出识别的所有标签
|
|
|
for label in labels:
|
|
|
label_name.append(label['Name'])
|
|
|
for Parents in label['Parents']:
|
|
@@ -335,7 +313,7 @@ class AiView(View):
|
|
|
|
|
|
logger.info('标签名------')
|
|
|
logger.info(label_name)
|
|
|
- #删除用户没有选择的ai识别类型, 并且得出最终识别结果
|
|
|
+ # 删除用户没有选择的ai识别类型, 并且得出最终识别结果
|
|
|
user_detect_list = user_detect_group.split(',')
|
|
|
user_detect_list = [i.strip() for i in user_detect_list]
|
|
|
conform_label_list = []
|
|
@@ -346,17 +324,17 @@ class AiView(View):
|
|
|
if label in label_name:
|
|
|
conform_user_d_group.add(key)
|
|
|
conform_label_list.append(label)
|
|
|
- #找出标签边框线位置信息
|
|
|
+ # 找出标签边框线位置信息
|
|
|
boundingBoxList = []
|
|
|
for label in labels:
|
|
|
if label['Name'] in conform_label_list:
|
|
|
for boundingBox in label['Instances']:
|
|
|
boundingBoxList.append(boundingBox['BoundingBox'])
|
|
|
|
|
|
- #找出边框位置信息对应的单图位置并重新计算位置比
|
|
|
+ # 找出边框位置信息对应的单图位置并重新计算位置比
|
|
|
merge_image_height = image_size['height']
|
|
|
# merge_image_width = image_size['width']
|
|
|
- single_height = merge_image_height//image_size['num']
|
|
|
+ single_height = merge_image_height // image_size['num']
|
|
|
new_bounding_box_dict = {}
|
|
|
new_bounding_box_dict['file_0'] = []
|
|
|
new_bounding_box_dict['file_1'] = []
|
|
@@ -364,39 +342,39 @@ class AiView(View):
|
|
|
new_bounding_box_dict['file_3'] = []
|
|
|
for k, val in enumerate(boundingBoxList):
|
|
|
boundingBoxTop = merge_image_height * val['Top']
|
|
|
- #找出当前边框属于哪张图片范围
|
|
|
+ # 找出当前边框属于哪张图片范围
|
|
|
boxDict = {}
|
|
|
for i in range(image_size['num']):
|
|
|
- min = i*single_height #第n张图
|
|
|
- max = (i+1)*single_height
|
|
|
+ min = i * single_height # 第n张图
|
|
|
+ max = (i + 1) * single_height
|
|
|
if boundingBoxTop >= min and boundingBoxTop <= max:
|
|
|
# print("属于第{i}张图".format(i=i+1))
|
|
|
boxDict['Width'] = val['Width']
|
|
|
- boxDict['Height'] = merge_image_height*val['Height']/single_height
|
|
|
- boxDict['Top'] = ((merge_image_height*val['Top'])-(i*single_height))/single_height #减去前i张图片的高度
|
|
|
+ boxDict['Height'] = merge_image_height * val['Height'] / single_height
|
|
|
+ boxDict['Top'] = ((merge_image_height * val['Top']) - (
|
|
|
+ i * single_height)) / single_height # 减去前i张图片的高度
|
|
|
boxDict['Left'] = val['Left']
|
|
|
new_bounding_box_dict["file_{i}".format(i=i)].append(boxDict)
|
|
|
# exit(new_bounding_box_list)
|
|
|
conform_user_d_group = list(conform_user_d_group)
|
|
|
if len(conform_user_d_group) > 1:
|
|
|
- eventType = 123 #组合类型
|
|
|
+ eventType = 123 # 组合类型
|
|
|
else:
|
|
|
eventType = conform_user_d_group[0]
|
|
|
|
|
|
return {'eventType': eventType, 'label_list': conform_label_list,
|
|
|
- 'new_bounding_box_dict':new_bounding_box_dict}
|
|
|
-
|
|
|
+ 'new_bounding_box_dict': new_bounding_box_dict}
|
|
|
|
|
|
def upload_s3(self, file_path, upload_path):
|
|
|
try:
|
|
|
- aws_key = AWS_ACCESS_KEY_ID[0] #【你的 aws_access_key】
|
|
|
- aws_secret = AWS_SECRET_ACCESS_KEY[0] # 【你的 aws_secret_key】
|
|
|
+ aws_key = AWS_ACCESS_KEY_ID[0] # 【你的 aws_access_key】
|
|
|
+ aws_secret = AWS_SECRET_ACCESS_KEY[0] # 【你的 aws_secret_key】
|
|
|
session = Session(aws_access_key_id=aws_key,
|
|
|
aws_secret_access_key=aws_secret,
|
|
|
region_name="cn-northwest-1")
|
|
|
s3 = session.resource("s3")
|
|
|
# client = session.client("s3")
|
|
|
- bucket = "push" # 【你 bucket 的名字】 # 首先需要保.证 s3 上已经存在该存储桶,否则报错
|
|
|
+ bucket = "push" # 【你 bucket 的名字】 # 首先需要保.证 s3 上已经存在该存储桶,否则报错
|
|
|
upload_data = open(file_path, "rb")
|
|
|
# upload_key = "test"
|
|
|
s3.Bucket(bucket).put_object(Key=upload_path, Body=upload_data)
|
|
@@ -425,7 +403,7 @@ class AiView(View):
|
|
|
return nickname
|
|
|
|
|
|
def get_msg_text(self, channel, n_time, lang, tz, label_list):
|
|
|
- n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz,lang=lang)
|
|
|
+ n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz, lang=lang)
|
|
|
if lang == 'cn':
|
|
|
msg = '摄像头AI识别到了{}'.format(label_list)
|
|
|
send_text = '{msg} 通道:{channel} 日期:{date}'.format(msg=msg, channel=channel, date=n_date)
|
|
@@ -472,7 +450,6 @@ class AiView(View):
|
|
|
except Exception as e:
|
|
|
return 'serverKey abnormal'
|
|
|
|
|
|
-
|
|
|
def do_apns(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
|
|
|
logger = logging.getLogger('info')
|
|
|
logger.info("进来do_apns函数了")
|
|
@@ -480,7 +457,8 @@ class AiView(View):
|
|
|
logger.info(APNS_MODE)
|
|
|
logger.info(os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
|
|
|
try:
|
|
|
- cli = apns2.APNSClient(mode=APNS_MODE, client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
|
|
|
+ cli = apns2.APNSClient(mode=APNS_MODE,
|
|
|
+ client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
|
|
|
push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
|
|
|
"received_at": n_time, "sound": "", "uid": uid, "zpush": "1", "channel": channel}
|
|
|
alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
|
|
@@ -500,8 +478,3 @@ class AiView(View):
|
|
|
print(repr(e))
|
|
|
logger.info(repr(e))
|
|
|
return repr(e)
|
|
|
-
|
|
|
-
|
|
|
-
|
|
|
-
|
|
|
-
|