AiController.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. @Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
  5. @software: PyCharm
  6. @Version: python3.6
  7. @MODIFY DECORD:ansjer dev
  8. """
  9. import base64
  10. import json
  11. import logging
  12. import os
  13. import threading
  14. import time
  15. import apns2
  16. import boto3
  17. import jpush
  18. from boto3.session import Session
  19. from django.views.generic.base import View
  20. from pyfcm import FCMNotification
  21. from AnsjerPush.config import AI_IDENTIFICATION_TAGS_DICT, CONFIG_US, CONFIG_EUR
  22. from AnsjerPush.config import AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, APNS_MODE, APNS_CONFIG, BASE_DIR, \
  23. JPUSH_CONFIG, FCM_CONFIG
  24. from AnsjerPush.config import CONFIG_INFO
  25. from AnsjerPush.config import PUSH_BUCKET
  26. from Model.models import UidPushModel, AiService, VodHlsTag, VodHlsTagType
  27. from Object import MergePic
  28. from Object.DynamodbObject import DynamodbObject
  29. from Object.ETkObject import ETkObject
  30. from Object.OCIObjectStorage import OCIObjectStorage
  31. from Object.RedisObject import RedisObject
  32. from Object.ResponseObject import ResponseObject
  33. from Object.SageMakerAiObject import SageMakerAiObject
  34. from Object.TokenObject import TokenObject
  35. from Object.enums.MessageTypeEnum import MessageTypeEnum
  36. from Service.CommonService import CommonService
  37. from Service.DevicePushService import DevicePushService
  38. from Service.EquipmentInfoService import EquipmentInfoService
  39. TIME_LOGGER = logging.getLogger('time')
  40. # AI服务
  41. class AiView(View):
  42. def get(self, request, *args, **kwargs):
  43. request.encoding = 'utf-8'
  44. operation = kwargs.get('operation')
  45. return self.validation(request.GET, request, operation)
  46. def post(self, request, *args, **kwargs):
  47. request.encoding = 'utf-8'
  48. operation = kwargs.get('operation')
  49. return self.validation(request.POST, request, operation)
  50. def validation(self, request_dict, request, operation):
  51. response = ResponseObject()
  52. if operation is None:
  53. return response.json(444, 'error path')
  54. elif operation == 'identification': # ai识别
  55. return self.do_ai_identification(request.POST, response)
  56. else:
  57. token = request_dict.get('token', None)
  58. # 设备主键uid
  59. tko = TokenObject(token)
  60. response.lang = tko.lang
  61. if tko.code != 0:
  62. return response.json(tko.code)
  63. userID = tko.userID
  64. if operation == 'identification': # ai识别
  65. return self.do_ai_identification(request_dict, response)
  66. else:
  67. return response.json(414)
  68. def do_ai_identification(self, request_dict, response):
  69. etk = request_dict.get('etk', None)
  70. n_time = request_dict.get('n_time', None)
  71. channel = request_dict.get('channel', '1')
  72. receiveTime = int(time.time())
  73. TIME_LOGGER.info('*****进入into----ai--api,etk={etk}'.format(etk=etk))
  74. if not etk:
  75. return response.json(444)
  76. dir_path = ''
  77. uid = ''
  78. try:
  79. # 解密uid及判断长度
  80. eto = ETkObject(etk)
  81. uid = eto.uid
  82. TIME_LOGGER.info(f'etk解析uid={uid},n_time={n_time},etk:{etk}')
  83. if len(uid) != 20 and len(uid) != 14:
  84. return response.json(444)
  85. # 通过uid查出endTime是否过期,并且ai开关是否打开
  86. AiServiceQuery = AiService.objects.filter(uid=uid, detect_status=1, use_status=1, endTime__gt=receiveTime) \
  87. .values('detect_group', 'orders__payType', 'addTime')
  88. if not AiServiceQuery.exists():
  89. TIME_LOGGER.info(f'uid={uid}AI服务未开通或已到期')
  90. return response.json(173)
  91. detect_group = AiServiceQuery[0]['detect_group']
  92. file_post_one = request_dict.get('fileOne', None)
  93. file_post_two = request_dict.get('fileTwo', None)
  94. file_post_three = request_dict.get('fileThree', None)
  95. TIME_LOGGER.info(f'uid:{uid},图1:{file_post_one[:30]},图2:{file_post_two[:30]},图3:{file_post_three[:30]}')
  96. file_list = [file_post_one, file_post_two, file_post_three]
  97. del file_post_one, file_post_two, file_post_three
  98. if not all(file_list):
  99. for k, val in enumerate(file_list):
  100. if not val:
  101. return response.json(444, '缺少第{k}张图'.format(k=k + 1))
  102. redis_obj = RedisObject(db=6)
  103. ai_key = f'PUSH:AI:{uid}:{channel}'
  104. ai_data = redis_obj.get_data(ai_key)
  105. if ai_data:
  106. return response.json(0, {'msg': 'Push again in one minute'})
  107. # 查询推送数据
  108. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid). \
  109. values('token_val', 'app_type', 'appBundleId', 'm_code', 'push_type', 'userID_id',
  110. 'userID__NickName',
  111. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval',
  112. 'uid_set__detect_group', 'uid_set__new_detect_interval',
  113. 'uid_set__channel', 'uid_set__msg_notify')
  114. if not uid_push_qs.exists():
  115. TIME_LOGGER.info(f'uid={uid},用户没有开启AI推送')
  116. return response.json(173)
  117. ai_server = 'sageMaker'
  118. if AiServiceQuery[0]['orders__payType'] == 10: # AI首次体验前半个月调Rekognition
  119. now_time = int(time.time())
  120. add_time = AiServiceQuery[0]['addTime']
  121. if (now_time - add_time) <= (3600 * 24 * 3):
  122. ai_server = 'rekognition'
  123. APP_NOTIFY_KEY = f'ASJ:NOTIFY:PUSH:{uid}:{channel}' # 推送间隔缓存KEY
  124. push_cache_data = redis_obj.get_data(APP_NOTIFY_KEY)
  125. is_push = False if push_cache_data else True
  126. notify_data = uid_push_qs[0]['uid_set__msg_notify']
  127. # APP推送提醒状态
  128. notify = self.is_ai_push(uid, notify_data) if is_push else is_push
  129. if ai_server == 'sageMaker': # 自建模型sageMaker AI
  130. sage_maker = SageMakerAiObject()
  131. ai_result = sage_maker.sage_maker_ai_server(uid, file_list) # 图片base64识别AI标签
  132. if ai_result:
  133. if ai_result == 'imageError':
  134. return response.json(0)
  135. res = sage_maker.get_table_name(uid, ai_result, detect_group)
  136. if not res: # 当前识别结果未匹配
  137. return response.json(0)
  138. push_thread = threading.Thread(
  139. target=self.async_message_push,
  140. kwargs={'sage_maker': sage_maker, 'uid': uid, 'n_time': n_time, 'uid_push_qs': uid_push_qs,
  141. 'channel': channel, 'res': res, 'file_list': file_list, 'notify': notify})
  142. push_thread.start() # AI识别异步存表&推送
  143. self.add_push_cache(APP_NOTIFY_KEY, redis_obj, push_cache_data,
  144. uid_push_qs[0]['uid_set__new_detect_interval'])
  145. redis_obj.set_data(ai_key, uid, 60)
  146. return response.json(0)
  147. TIME_LOGGER.info(f'uid={uid},sagemakerAI识别失败{ai_result}')
  148. push_thread = threading.Thread(target=self.image_label_detection,
  149. kwargs={'ai_server': ai_server, 'uid': uid, 'file_list': file_list,
  150. 'detect_group': detect_group, 'n_time': n_time,
  151. 'uid_push_qs': uid_push_qs,
  152. 'channel': channel})
  153. push_thread.start() # AI识别异步存表&推送
  154. redis_obj.set_data(ai_key, uid, 60)
  155. return response.json(0)
  156. except Exception as e:
  157. print(e)
  158. data = {
  159. 'errLine': e.__traceback__.tb_lineno,
  160. 'errMsg': repr(e)
  161. }
  162. TIME_LOGGER.info(f'rekognition识别errMsg={data}')
  163. return response.json(48, data)
  164. def async_message_push(self, sage_maker, uid, n_time, uid_push_qs, channel, res, file_list, notify):
  165. # 保存推送消息
  166. sage_maker.save_push_message(uid, n_time, uid_push_qs, channel, res, file_list, notify)
  167. def add_push_cache(self, key, redis_obj, cache_push_data, push_interval):
  168. """
  169. 推送间隔缓存设置
  170. """
  171. if push_interval > 0:
  172. if cache_push_data: # 缓存存在
  173. interval = json.loads(cache_push_data)['interval']
  174. if interval != push_interval:
  175. push_data = {'interval': push_interval}
  176. redis_obj.set_data(key=key, val=json.dumps(push_data), expire=push_interval)
  177. else: # 缓存不存在
  178. push_data = {'interval': push_interval}
  179. redis_obj.set_data(key=key, val=json.dumps(push_data), expire=push_interval)
  180. def image_label_detection(self, ai_server, uid, file_list, detect_group,
  181. n_time, uid_push_qs, channel):
  182. """
  183. :param ai_server: AI服务类型
  184. :param uid: 用户uid
  185. :param file_list: 图片base64列表
  186. :param detect_group: 识别组
  187. :param n_time: 时间戳
  188. :param uid_push_qs: 推送数据
  189. :param channel: 推送通道
  190. :return:
  191. """
  192. try:
  193. start_time = time.time()
  194. redis_obj = RedisObject(db=6)
  195. APP_NOTIFY_KEY = f'ASJ:NOTIFY:PUSH:{uid}:{channel}' # 推送间隔缓存KEY
  196. push_cache_data = redis_obj.get_data(APP_NOTIFY_KEY)
  197. is_push = False if push_cache_data else True
  198. notify_data = uid_push_qs[0]['uid_set__msg_notify']
  199. # APP推送提醒状态
  200. notify = self.is_ai_push(uid, notify_data) if is_push else is_push
  201. TIME_LOGGER.info(f'*****现执行Reko,uid={uid}识别类型={ai_server}')
  202. dir_path = os.path.join(BASE_DIR, 'static/ai/' + uid + '/' + str(n_time))
  203. if not os.path.exists(dir_path):
  204. os.makedirs(dir_path)
  205. file_path_list = []
  206. for i, val in enumerate(file_list):
  207. val = val.replace(' ', '+')
  208. val = base64.b64decode(val)
  209. file_path = "{dir_path}/{n_time}_{i}.jpg".format(dir_path=dir_path, n_time=n_time, i=i)
  210. file_path_list.append(file_path)
  211. with open(file_path, 'wb') as f:
  212. f.write(val)
  213. f.close()
  214. image_size = 0 # 每张小图片的大小,等于0是按原图大小进行合并
  215. image_colnum = 1 # 合并成一张图后,一行有几个小图
  216. image_size = MergePic.merge_images(dir_path, image_size, image_colnum)
  217. photo = open(dir_path + '.jpg', 'rb') # 打开合成图
  218. # rekognition识别合成图片
  219. maxLabels = 50 # 最大标签
  220. minConfidence = 80 # 置信度
  221. client = boto3.client(
  222. 'rekognition',
  223. aws_access_key_id='AKIA2E67UIMD6JD6TN3J',
  224. aws_secret_access_key='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',
  225. region_name='us-east-1')
  226. # 执行AWS Rekognition:
  227. rekognition_res = client.detect_labels(
  228. Image={'Bytes': photo.read()},
  229. MaxLabels=maxLabels,
  230. MinConfidence=minConfidence)
  231. photo.close()
  232. if rekognition_res['ResponseMetadata']['HTTPStatusCode'] != 200:
  233. return False
  234. end_time = time.time()
  235. labels = self.labelsCoords(detect_group, rekognition_res, image_size) # 检查标签是否符合用户选择的识别类型
  236. TIME_LOGGER.info(f'uid={uid},{(end_time - start_time)}s,rekognition Result={labels}')
  237. # 将识别结果存到S3以及DynamoDB
  238. # AiView.store_image_results_to_dynamo_and_s3(file_path_list, uid, channel, n_time, labels, rekognition_res)
  239. eventType = labels['eventType']
  240. label_str = ','.join(labels['label_list'])
  241. new_bounding_box_dict = labels['new_bounding_box_dict']
  242. # 上传缩略图到s3
  243. file_dict = {}
  244. for i, val in enumerate(file_path_list):
  245. file_dict[val] = "{uid}/{channel}/{n_time}_{i}.jpeg".format(uid=uid, channel=channel, # 封面图
  246. n_time=n_time, i=i)
  247. self.upload_s3(file_dict, dir_path)
  248. # 设置推送间隔缓存
  249. self.add_push_cache(APP_NOTIFY_KEY, redis_obj, push_cache_data,
  250. uid_push_qs[0]['uid_set__new_detect_interval'])
  251. self.save_message_and_push(eventType, uid, n_time, uid_push_qs, channel,
  252. label_str, new_bounding_box_dict, notify)
  253. AiView.save_cloud_ai_tag(uid, int(n_time), eventType, 0)
  254. except Exception as e:
  255. data = {
  256. 'errLine': e.__traceback__.tb_lineno,
  257. 'errMsg': repr(e)
  258. }
  259. TIME_LOGGER.info(f'rekognition识别errMsg={data}')
  260. def save_message_and_push(self, eventType, uid, n_time, uid_push_qs, channel, label_str, new_bounding_box_dict,
  261. notify):
  262. """
  263. 保存消息以及推送
  264. """
  265. uid_push_list = []
  266. for qs in uid_push_qs:
  267. uid_push_list.append(qs)
  268. nickname = uid_push_list[0]['uid_set__nickname']
  269. if not nickname:
  270. nickname = uid
  271. userID_ids = []
  272. region = 4 if CONFIG_INFO == CONFIG_EUR else 3
  273. for up in uid_push_list:
  274. push_type = up['push_type']
  275. appBundleId = up['appBundleId']
  276. token_val = up['token_val']
  277. lang = up['lang']
  278. tz = up['tz']
  279. if tz is None or tz == '':
  280. tz = 0
  281. local_date_time = CommonService.get_now_time_str(n_time=n_time, tz=tz, lang='cn')
  282. TIME_LOGGER.info('*****AI消息存库{},{},{}'.format(uid, local_date_time, tz))
  283. # 以下是存库
  284. userID_id = up["userID_id"]
  285. if userID_id not in userID_ids:
  286. now_time = int(time.time())
  287. EquipmentInfoService.randoms_insert_equipment_info(
  288. device_user_id=userID_id,
  289. event_time=n_time,
  290. event_type=eventType,
  291. device_uid=uid,
  292. device_nick_name=nickname,
  293. channel=channel,
  294. alarm=label_str,
  295. is_st=3,
  296. add_time=now_time,
  297. storage_location=region,
  298. border_coords=json.dumps(new_bounding_box_dict)
  299. )
  300. userID_ids.append(userID_id)
  301. if not notify: # 不推送
  302. continue
  303. # 推送标题
  304. msg_title = self.get_msg_title(appBundleId=appBundleId, nickname=nickname)
  305. # 推送内容
  306. msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz, label_list=label_str)
  307. kwargs = {
  308. 'uid': uid,
  309. 'channel': channel,
  310. 'event_type': eventType,
  311. 'n_time': n_time,
  312. 'appBundleId': appBundleId,
  313. 'token_val': token_val,
  314. 'msg_title': msg_title,
  315. 'msg_text': msg_text,
  316. }
  317. try:
  318. # 推送消息
  319. if push_type == 0: # ios apns
  320. self.do_apns(**kwargs)
  321. elif push_type == 1: # android gcm
  322. self.do_fcm(**kwargs)
  323. elif push_type == 2: # android jpush
  324. self.do_jpush(**kwargs)
  325. except Exception as e:
  326. TIME_LOGGER.info('*****error,uid={uid},errLine={errLine}, errMsg={errMsg}'
  327. .format(uid=uid, errLine=e.__traceback__.tb_lineno, errMsg=repr(e)))
  328. continue
  329. def is_ai_push(self, uid, app_push_config):
  330. """
  331. 是否进行APP消息提醒
  332. @return: True|False
  333. """
  334. try:
  335. if not app_push_config:
  336. return True
  337. is_push = app_push_config['appPush']
  338. if is_push != 1: # 1:进行APP提醒,其它则不执行APP提醒
  339. return False
  340. all_day = app_push_config['pushTime']['allDay']
  341. if all_day == 0: # 1:全天提醒,0:自定义时间提醒
  342. push_time_config = app_push_config['pushTime']
  343. # 计算当前时间是否在自定义消息提醒范围内
  344. if not DevicePushService.is_push_notify_allowed_now(push_time_config):
  345. return False
  346. # 在开启接收APP消息提醒时,判断是否勾选云端AI消息提醒
  347. return app_push_config['eventTypes']['aiCloud'] == 1
  348. except Exception as e:
  349. TIME_LOGGER.info('*****error,uid={uid},errLine={errLine}, errMsg={errMsg}'
  350. .format(uid=uid, errLine=e.__traceback__.tb_lineno, errMsg=repr(e)))
  351. return True
  352. def del_path(self, path):
  353. try:
  354. if not os.path.exists(path):
  355. return
  356. if os.path.isfile(path):
  357. os.remove(path)
  358. else:
  359. items = os.listdir(path)
  360. for f in items:
  361. c_path = os.path.join(path, f)
  362. if os.path.isdir(c_path):
  363. self.del_path(c_path)
  364. else:
  365. os.remove(c_path)
  366. os.rmdir(path)
  367. except Exception as e:
  368. print(repr(e))
  369. ## 检查是否有符合条件的标签,并且返回标签坐标位置信息
  370. def labelsCoords(self, user_detect_group, rekognition_res, image_size):
  371. logger = logging.getLogger('info')
  372. labels = rekognition_res['Labels']
  373. label_name = []
  374. label_list = []
  375. logger.info('--------识别到的标签-------')
  376. logger.info(labels)
  377. all_labels_type = {
  378. '1': ['Person', 'Human'], # 人
  379. '2': ['Pet', 'Dog', 'Canine', 'Animal', 'Puppy', 'Cat'], # 动物
  380. '3': ['Vehicle', 'Car', 'Transportation', 'Automobile', 'Bus'], # 车
  381. '4': ['Package', 'Carton', 'Cardboard', 'Package Delivery'] # 包裹
  382. }
  383. # 找出识别的所有标签
  384. for label in labels:
  385. label_name.append(label['Name'])
  386. for Parents in label['Parents']:
  387. label_name.append(Parents['Name'])
  388. logger.info('标签名------')
  389. logger.info(label_name)
  390. # 删除用户没有选择的ai识别类型, 并且得出最终识别结果
  391. user_detect_list = user_detect_group.split(',')
  392. user_detect_list = [i.strip() for i in user_detect_list]
  393. conform_label_list = []
  394. conform_user_d_group = set()
  395. for key, label_type_val in all_labels_type.items():
  396. if key in user_detect_list:
  397. for label in label_type_val:
  398. if label in label_name:
  399. conform_user_d_group.add(key)
  400. conform_label_list.append(label)
  401. # 找出标签边框线位置信息
  402. boundingBoxList = []
  403. for label in labels:
  404. if label['Name'] in conform_label_list:
  405. for boundingBox in label['Instances']:
  406. boundingBoxList.append(boundingBox['BoundingBox'])
  407. # 找出边框位置信息对应的单图位置并重新计算位置比
  408. merge_image_height = image_size['height']
  409. # merge_image_width = image_size['width']
  410. single_height = merge_image_height // image_size['num']
  411. new_bounding_box_dict = {}
  412. new_bounding_box_dict['file_0'] = []
  413. new_bounding_box_dict['file_1'] = []
  414. new_bounding_box_dict['file_2'] = []
  415. # new_bounding_box_dict['file_3'] = []
  416. for k, val in enumerate(boundingBoxList):
  417. boundingBoxTop = merge_image_height * val['Top']
  418. # 找出当前边框属于哪张图片范围
  419. boxDict = {}
  420. for i in range(image_size['num']):
  421. min = i * single_height # 第n张图
  422. max = (i + 1) * single_height
  423. if boundingBoxTop >= min and boundingBoxTop <= max:
  424. # print("属于第{i}张图".format(i=i+1))
  425. boxDict['Width'] = val['Width']
  426. boxDict['Height'] = merge_image_height * val['Height'] / single_height
  427. boxDict['Top'] = ((merge_image_height * val['Top']) - (
  428. i * single_height)) / single_height # 减去前i张图片的高度
  429. boxDict['Left'] = val['Left']
  430. new_bounding_box_dict["file_{i}".format(i=i)].append(boxDict)
  431. # exit(new_bounding_box_list)
  432. conform_user_d_group = list(conform_user_d_group)
  433. if len(conform_user_d_group) > 0:
  434. conform_user_d_group.sort()
  435. # 集成识别标签
  436. for label_key in conform_user_d_group:
  437. label_list.append(AI_IDENTIFICATION_TAGS_DICT[label_key])
  438. eventType = ''.join(conform_user_d_group) # 组合类型
  439. else:
  440. eventType = ''
  441. logger.info('------conform_user_d_group------ {}'.format(conform_user_d_group))
  442. logger.info('------label_list------ {}'.format(label_list))
  443. return {'eventType': eventType, 'label_list': label_list,
  444. 'new_bounding_box_dict': new_bounding_box_dict}
  445. def upload_s3(self, file_dict, dir_path):
  446. try:
  447. # if CONFIG_INFO == CONFIG_US or CONFIG_INFO == CONFIG_EUR:
  448. # # 存国外
  449. # aws_key = AWS_ACCESS_KEY_ID[1]
  450. # aws_secret = AWS_SECRET_ACCESS_KEY[1]
  451. # session = Session(aws_access_key_id=aws_key,
  452. # aws_secret_access_key=aws_secret,
  453. # region_name="us-east-1")
  454. # s3 = session.resource("s3")
  455. # bucket = "foreignpush"
  456. # else:
  457. # # 存国内
  458. # aws_key = AWS_ACCESS_KEY_ID[0]
  459. # aws_secret = AWS_SECRET_ACCESS_KEY[0]
  460. # session = Session(aws_access_key_id=aws_key,
  461. # aws_secret_access_key=aws_secret,
  462. # region_name="cn-northwest-1")
  463. # s3 = session.resource("s3")
  464. # bucket = "push"
  465. #
  466. # for file_path, upload_path in file_dict.items():
  467. # print('-------')
  468. # print(file_path)
  469. # print('-------')
  470. # upload_data = open(file_path, "rb")
  471. # # upload_key = "test"
  472. # s3.Bucket(bucket).put_object(Key=upload_path, Body=upload_data)
  473. region = 'eur' if CONFIG_INFO == CONFIG_EUR else 'us'
  474. oci = OCIObjectStorage(region)
  475. for file_path, upload_path in file_dict.items():
  476. upload_data = open(file_path, "rb")
  477. # OCI上传对象
  478. oci.put_object(PUSH_BUCKET, upload_path, upload_data, 'image/jpeg')
  479. return True
  480. except Exception as e:
  481. TIME_LOGGER.error('rekoAI上传对象异常errLine={errLine}, errMsg={errMsg}'
  482. .format(errLine=e.__traceback__.tb_lineno, errMsg=repr(e)))
  483. return False
  484. def get_msg_title(self, appBundleId, nickname):
  485. package_title_config = {
  486. 'com.ansjer.customizedd_a': 'DVS',
  487. 'com.ansjer.zccloud_a': 'ZosiSmart',
  488. 'com.ansjer.zccloud_ab': '周视',
  489. 'com.ansjer.adcloud_a': 'ADCloud',
  490. 'com.ansjer.adcloud_ab': 'ADCloud',
  491. 'com.ansjer.accloud_a': 'ACCloud',
  492. 'com.ansjer.loocamccloud_a': 'Loocam',
  493. 'com.ansjer.loocamdcloud_a': 'Anlapus',
  494. 'com.ansjer.customizedb_a': 'COCOONHD',
  495. 'com.ansjer.customizeda_a': 'Guardian365',
  496. 'com.ansjer.customizedc_a': 'PatrolSecure',
  497. }
  498. if appBundleId in package_title_config.keys():
  499. return package_title_config[appBundleId] + '(' + nickname + ')'
  500. else:
  501. return nickname
  502. def get_msg_text(self, channel, n_time, lang, tz, label_list):
  503. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz, lang=lang)
  504. if lang == 'cn':
  505. msg = '摄像头AI识别到了{}'.format(label_list)
  506. send_text = '{msg} 通道:{channel} 日期:{date}'.format(msg=msg, channel=channel, date=n_date)
  507. else:
  508. msg = 'Camera AI recognizes {}'.format(label_list)
  509. send_text = '{msg} channel:{channel} date:{date}'.format(msg=msg, channel=channel, date=n_date)
  510. return send_text
  511. @classmethod
  512. def save_cloud_ai_tag(cls, uid, event_time, types, week=0):
  513. """
  514. 保存云存AI标签
  515. """
  516. try:
  517. types = str(types)
  518. if not types:
  519. return False
  520. n_time = int(time.time())
  521. vod_hls_tag = {"uid": uid, "ai_event_time": event_time, "created_time": n_time, 'tab_num': int(week)}
  522. vod_tag_vo = VodHlsTag.objects.create(**vod_hls_tag)
  523. tag_list = []
  524. if len(types) > 1:
  525. for i in range(1, len(types) + 1):
  526. ai_type = MessageTypeEnum(int(types[i - 1:i]))
  527. vod_tag_type_vo = VodHlsTagType(tag_id=vod_tag_vo.id, created_time=n_time, type=ai_type.value)
  528. tag_list.append(vod_tag_type_vo)
  529. else:
  530. ai_type = MessageTypeEnum(int(types))
  531. vod_tag_type_vo = {"tag_id": vod_tag_vo.id, "created_time": n_time, "type": ai_type.value}
  532. VodHlsTagType.objects.create(**vod_tag_type_vo)
  533. if tag_list:
  534. VodHlsTagType.objects.bulk_create(tag_list)
  535. return True
  536. except Exception as e:
  537. print('AI标签存储异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  538. return False
  539. def do_jpush(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  540. app_key = JPUSH_CONFIG[appBundleId]['Key']
  541. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  542. # 此处换成各自的app_key和master_secre
  543. _jpush = jpush.JPush(app_key, master_secret)
  544. push = _jpush.create_push()
  545. push.audience = jpush.registration_id(token_val)
  546. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  547. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  548. android = jpush.android(alert=msg_text, priority=1, style=1, alert_type=7,
  549. big_text=msg_text, title=msg_title,
  550. extras=push_data)
  551. push.notification = jpush.notification(android=android)
  552. push.platform = jpush.all_
  553. res = push.send()
  554. print(res)
  555. return res.status_code
  556. def do_fcm(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  557. try:
  558. serverKey = FCM_CONFIG[appBundleId]
  559. push_service = FCMNotification(api_key=serverKey)
  560. data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  561. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  562. result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
  563. message_body=msg_text, data_message=data,
  564. extra_kwargs={
  565. 'default_vibrate_timings': True,
  566. 'default_sound': True,
  567. 'default_light_settings': True
  568. })
  569. print('fcm push ing')
  570. print(result)
  571. return result
  572. except Exception as e:
  573. return 'serverKey abnormal'
  574. def do_apns(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  575. logger = logging.getLogger('info')
  576. logger.info("进来do_apns函数了")
  577. logger.info(token_val)
  578. logger.info(APNS_MODE)
  579. logger.info(os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  580. try:
  581. cli = apns2.APNSClient(mode=APNS_MODE,
  582. client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  583. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  584. "received_at": n_time, "sound": "", "uid": uid, "zpush": "1", "channel": channel}
  585. alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
  586. payload = apns2.Payload(alert=alert, custom=push_data, sound="default")
  587. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  588. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  589. if res.status_code == 200:
  590. return res.status_code
  591. else:
  592. logger.info('apns push fail')
  593. logger.info(res.reason)
  594. return res.status_code
  595. except (ValueError, ArithmeticError):
  596. return 'The program has a numeric format exception, one of the arithmetic exceptions'
  597. except Exception as e:
  598. print(repr(e))
  599. logger.info(repr(e))
  600. return repr(e)
  601. @staticmethod
  602. def store_image_results_to_dynamo_and_s3(file_path_list, uid, channel, n_time, labels_data,
  603. reko_result):
  604. """
  605. 将图片识别结果存储到dynamoDB并且存储到S3
  606. @param file_path_list: 图片名称列表
  607. @param uid: 设备uid
  608. @param channel: 设备通道号
  609. @param n_time: 设备触发移动侦测时间戳
  610. @param labels_data: 标签数据(经过reko_result结果进行计算后的数据)
  611. @param reko_result: rekognition 响应结果
  612. @return: 保存结果
  613. """
  614. logger = logging.getLogger('info')
  615. try:
  616. file_dict = {}
  617. for i, val in enumerate(file_path_list):
  618. file_dict[val] = "{uid}/{channel}/{n_time}_{i}.jpeg".format(uid=uid, channel=channel, # 封面图
  619. n_time=n_time, i=i)
  620. if not reko_result:
  621. logger.info('{}识别结果为空'.format(uid))
  622. return False
  623. if CONFIG_INFO != CONFIG_US: # 目前只上美洲
  624. return False
  625. # 存美洲
  626. session = Session(aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  627. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  628. region_name="us-west-1")
  629. s3 = session.resource("s3")
  630. bucket = "rekognition-pic-results"
  631. # 上传到S3 rekognition-pic-results
  632. for file_path, upload_path in file_dict.items():
  633. logger.info('{}文件路径{}'.format(uid, file_path))
  634. upload_data = open(file_path, "rb")
  635. s3.Bucket(bucket).put_object(Key=upload_path, Body=upload_data)
  636. # reko结果存储到dynamoDB
  637. event_type = 0
  638. new_bounding_box_dict = ''
  639. if len(labels_data['label_list']) > 0:
  640. event_type = int(labels_data['eventType'])
  641. new_bounding_box_dict = json.dumps(labels_data['new_bounding_box_dict'])
  642. table_name = 'asj_push_message' # 表名称
  643. dynamo = DynamodbObject(AWS_ACCESS_KEY_ID[1], AWS_SECRET_ACCESS_KEY[1], 'us-west-1')
  644. item = {'device_uid': {'S': uid}, # 设备uid
  645. 'event_time': {'N': str(n_time)}, # 设备触发时间戳,也用作S3资源对象名前缀
  646. 'ai_coordinate': {'S': new_bounding_box_dict}, # ai坐标框信息
  647. 'channel': {'N': str(channel)}, # 设备通道号
  648. 'event_type': {'N': str(event_type)}, # 事件类型
  649. 'is_pic': {'N': '3'}, # 1:图片,2:视频,3:多图
  650. 'reko_result': {'S': json.dumps(reko_result)}, # reko识别结果
  651. 'storage_region': {'N': '2'}, # 存储平台1:阿里云,2:AWS
  652. 'create_time': {'N': str(int(time.time()))} # 记录创建时间
  653. }
  654. result = dynamo.put_item(table_name, item)
  655. logger.info('{}识别后存S3与DynamoDB成功{}'.format(uid, result))
  656. return True
  657. except Exception as e:
  658. logger.info('{}识别后存S3与DynamoDB失败:{}'.format(uid, repr(e)))
  659. return False