zhangdongming 2 жил өмнө
parent
commit
4a49e731a4

+ 2 - 0
Ansjer/server_urls/algorithm_shop_url.py

@@ -16,4 +16,6 @@ urlpatterns = [
     re_path(r'^api/(?P<operation>.*)$', AlgorithmShopController.AlgorithmShopView.as_view()),
     re_path(r'^cron/(?P<operation>.*)$', CronCloudPhotoController.CronCloudPhotoView.as_view()),
     re_path(r'^photo/(?P<operation>.*)$', CloudPhotoController.CronCloudPhotoView.as_view()),
+    re_path(r'^open/(?P<operation>.*)$', AlgorithmShopController.AlgorithmShopView.as_view()),
+
 ]

+ 1 - 0
Ansjer/urls.py

@@ -356,6 +356,7 @@ urlpatterns = [
     url(r'^unicom/', include("Ansjer.server_urls.unicom_url")),
     # 算法小店
     url(r'^algorithm-shop/', include("Ansjer.server_urls.algorithm_shop_url")),
+    re_path(r'^api/algorithm/', include("Ansjer.server_urls.algorithm_shop_url")),
     # KVS模块
     url(r'^kvs/', include("Ansjer.server_urls.kvs_url")),
     # 超级密码模块

+ 175 - 5
Controller/AlgorithmShop/AlgorithmShopController.py

@@ -9,14 +9,15 @@
 import logging
 import time
 
-from django.db.models import F
+from django.db.models import F, Value, CharField
 from django.views.generic.base import View
 
-from Model.models import DeviceAlgorithmExplain, DeviceAlgorithmBanner, DeviceUidAlgorithmType, DeviceTypeAlgorithmInfo
+from Model.models import DeviceAlgorithmExplain, DeviceAlgorithmBanner, DeviceUidAlgorithmType, \
+    DeviceTypeAlgorithmInfo, DeviceAppScenario, DeviceScenarioLangInfo, DeviceAlgorithmScenario
 from Object.ResponseObject import ResponseObject
 from Object.TokenObject import TokenObject
 
-logger = logging.getLogger('info')
+LOGGER = logging.getLogger('info')
 
 
 class AlgorithmShopView(View):
@@ -44,6 +45,170 @@ class AlgorithmShopView(View):
             return self.get_algorithm_details(request_dict, response)
         elif operation == 'save':
             return self.algorithm_setting_save(request_dict, response)
+        elif operation == 'getScenarioList':  # 获取应用场景数据列表
+            return self.get_scenario_list(request_dict, response)
+        elif operation == 'getAlgorithmListByScenarioId':  # 根据应用场景id获取算法列表
+            return self.get_scenario_algorithm_list(request_dict, response)
+        else:
+            return response.json(0)
+
+    @classmethod
+    def get_algorithm_list_by_scenario_id(cls, scenario_id, lang):
+        """
+        根据应用场景ID查询算法信息列表
+        @param scenario_id: 场景ID
+        @param lang: 语言
+        @return: 算法类型信息
+        """
+        try:
+            if not scenario_id or scenario_id == 0:
+                return []
+            # 根据场景id查询关联的算法id
+            algorithm_scenario_qs = DeviceAlgorithmScenario.objects.filter(scenario_id=scenario_id) \
+                .order_by('sort').values('algorithm_id')
+            if not algorithm_scenario_qs.exists():
+                return []
+            algorithm_list = []
+            for item in algorithm_scenario_qs:
+                algorithm_id = item['algorithm_id']
+                # 根据算法id查询多语言数据
+                algorithm_list.append(cls.get_lang_info_by_algorithm_id(algorithm_id, lang, None))
+            return algorithm_list
+        except Exception as e:
+            LOGGER.info('***get_algorithm_list_by_scenario_id,errLine:{}, errMsg:{}'
+                        .format(e.__traceback__.tb_lineno, repr(e)))
+            return []
+
+    @classmethod
+    def get_lang_info_by_algorithm_id(cls, algorithm_id, lang, uid):
+        """
+        根据算法id查询多语言数据详情
+        @param uid: 设备uid
+        @param algorithm_id: 算法id
+        @param lang: 语言
+        @return: 算法多语言数据详情
+        """
+        try:
+            algorithm_qs = DeviceAlgorithmExplain.objects.filter(algorithm_type_id=algorithm_id, lang=lang) \
+                .values('algorithm_type__icon_url', 'algorithm_type__id',
+                        'title', 'subtitle', 'algorithm_type__image_url',
+                        'algorithm_type__basic_function', 'concerning',
+                        'price', 'algorithm_type__tag', 'algorithm_type__status',
+                        'algorithm_type__type')
+            if not algorithm_qs.exists():
+                return {}
+            setting = ''  # 当前支持设置的算法功能json
+            # 存在uid则查询当前uid是否支持该算法
+            if uid:
+                setting = cls.get_uid_algorithm_info(algorithm_id, uid)
+                setting = setting if setting else {'status': 0, 'function': {}}
+            data = {
+                'typeId': algorithm_qs[0]['algorithm_type__id'],
+                'iconUrl': algorithm_qs[0]['algorithm_type__icon_url'],
+                'imageUrl': algorithm_qs[0]['algorithm_type__image_url'],
+                'title': algorithm_qs[0]['title'],
+                'subtitle': algorithm_qs[0]['subtitle'],
+                'basicFunction': algorithm_qs[0]['algorithm_type__basic_function'],
+                'concerning': algorithm_qs[0]['concerning'],
+                'price': algorithm_qs[0]['price'],
+                'tag': algorithm_qs[0]['algorithm_type__tag'],
+                'status': algorithm_qs[0]['algorithm_type__status'],
+                'setting': setting,
+                'type': algorithm_qs[0]['algorithm_type__type']
+            }
+            return data
+        except Exception as e:
+            LOGGER.info('***get_lang_info_by_algorithm_id,errLine:{}, errMsg:{}'
+                        .format(e.__traceback__.tb_lineno, repr(e)))
+            return {}
+
+    @classmethod
+    def get_algorithm_list(cls, lang):
+        """
+        获取所有算法数据列表
+        @return: 算法数据列表
+        """
+        algorithm_qs = DeviceAlgorithmExplain.objects.filter(lang=lang).order_by('algorithm_type__sort') \
+            .annotate(iconUrl=F('algorithm_type__icon_url'),
+                      typeId=F('algorithm_type__id'),
+                      type=F('algorithm_type__type'),
+                      imageUrl=F('algorithm_type__image_url'),
+                      basicFunction=F('algorithm_type__basic_function'),
+                      tag=F('algorithm_type__tag'), status=F('algorithm_type__status'),
+                      setting=Value('', output_field=CharField())) \
+            .values('iconUrl', 'imageUrl', 'title', 'subtitle', 'concerning', 'basicFunction', 'price', 'tag', 'status',
+                    'setting', 'typeId', 'type')
+        if not algorithm_qs.exists():
+            return []
+        return list(algorithm_qs)
+
+    @classmethod
+    def get_scenario_list(cls, request_dist, response):
+        """
+        获取应用场景列表
+        @param request_dist: lang
+        @param response: 响应结果
+        @return: 应用场景列表
+        """
+        try:
+            lang = request_dist.get('lang', 'en')
+            if not lang:
+                return response.json(444)
+            # 获取应用场景列表
+            scenario_qs = DeviceAppScenario.objects.filter().exclude(type=0).all().order_by('sort') \
+                .values('id', 'type', 'cver_url', 'banner_url')
+            scenario_list = []
+            if not scenario_qs.exists():
+                return response.json(0, scenario_list)
+
+            for item in scenario_qs:
+                scenario_vo = {'id': item['id'], 'cverUrl': item['cver_url'], 'bannerUrl': item['banner_url'],
+                               'name': '', 'content': ''}
+                # 获取根据语言应用场景信息
+                scenario_info_qs = DeviceScenarioLangInfo.objects.filter(lang=lang, scenario_id=item['id']) \
+                    .values('name', 'content')
+                if not scenario_info_qs.exists():
+                    continue
+                scenario_vo['name'] = scenario_info_qs[0]['name']
+                scenario_vo['content'] = scenario_info_qs[0]['content']
+                # 根据应用场景id查询关联算法类型数据
+                # scenario_vo['algorithmList'] = cls.get_algorithm_list_by_scenario_id(item['id'], lang)
+                scenario_list.append(scenario_vo)
+            # 获取所有算法图标地址以及算法名称
+            algorithm_qs = DeviceAlgorithmExplain.objects.filter(lang=lang).order_by('algorithm_type__sort') \
+                .annotate(algorithmId=F('algorithm_type__id'), algorithmType=F('algorithm_type__type'),
+                          iconUrl=F('algorithm_type__icon_url'),
+                          algorithmName=F('title')).values('algorithmId', 'algorithmType', 'iconUrl', 'algorithmName')
+            scenario_qs = DeviceAppScenario.objects.filter(type=0) \
+                .values('cver_url', 'banner_url')
+            scenario_banner = {}
+            if scenario_qs.exists():
+                scenario_banner['cverUrl'] = scenario_qs[0]['cver_url']
+                scenario_banner['bannerUrl'] = scenario_qs[0]['banner_url']
+            result_dto = {'scenarioList': scenario_list, 'scenarioUrl': scenario_banner}
+            if algorithm_qs.exists():
+                result_dto['iconList'] = list(algorithm_qs)
+            return response.json(0, result_dto)
+        except Exception as e:
+            LOGGER.info('接口异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
+            return response.json(500, repr(e))
+
+    @classmethod
+    def get_scenario_algorithm_list(cls, request_dist, response):
+        """
+        获取应用场景关联算法列表
+        @param request_dist:  scenarioId、lang
+        @param response: 响应结果
+        @return: 算法列表
+        """
+        scenario_id = request_dist.get('scenarioId', None)
+        lang = request_dist.get('lang', 'en')
+        result_dto = {'scenarioBannerUrl': ''}
+        if not scenario_id:
+            result_dto['algorithmList'] = cls.get_algorithm_list(lang)
+            return response.json(0, result_dto)
+        result_dto['algorithmList'] = cls.get_algorithm_list_by_scenario_id(scenario_id, lang)
+        return response.json(0, result_dto)
 
     @classmethod
     def get_algorithm_banner(cls, response):
@@ -72,7 +237,12 @@ class AlgorithmShopView(View):
         try:
             lang = request_dict.get('lang', 'en')
             uid = request_dict.get('uid', None)
-            algorithm_qs = DeviceAlgorithmExplain.objects.filter(lang=lang).order_by('algorithm_type__sort') \
+            version = request_dict.get('version', 'v1')
+            algorithm_qs = DeviceAlgorithmExplain.objects.filter(lang=lang)
+            types = [0, 1, 3, 4, 5]
+            if version == 'v1':
+                algorithm_qs = algorithm_qs.filter(algorithm_type__type__in=types)
+            algorithm_qs = algorithm_qs.order_by('algorithm_type__sort') \
                 .values('algorithm_type__id', 'algorithm_type__type',
                         'algorithm_type__icon_url',
                         'title', 'subtitle', 'algorithm_type__image_url',
@@ -99,7 +269,7 @@ class AlgorithmShopView(View):
             return response.json(0, algorithm_list)
         except Exception as e:
             print('查询算法小店列表异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
-            return response.json(177, repr(e))
+            return response.json(500, repr(e))
 
     @classmethod
     def get_algorithm_details(cls, request_dict, response):

+ 3 - 2
Controller/DetectControllerV2.py

@@ -416,9 +416,10 @@ class DetectControllerViewV2(View):
 
                 p['borderCoords'] = '' if p['borderCoords'] == '' else json.loads(p['borderCoords'])  # ai消息坐标信息
                 p['ai_event_type_list'] = []
-                if p['eventType'] in ai_all_event_type:  # 如果是ai消息类型,则分解eventType, 如:123 -> [1,2,3]
+                # 如果是ai消息类型,则分解eventType, 如:123 -> [1,2,3]
+                if p['borderCoords'] and p['eventType'] in ai_all_event_type:
                     p['ai_event_type_list'] = list(map(int, str(p['eventType'])))
-                p['ai_event_type_list'] += EquipmentInfoService.get_combo_types(p['eventType'])
+                p['ai_event_type_list'] += EquipmentInfoService.get_combo_types(p['eventType'], p['eventTag'])
                 res.append(p)
             return response.json(0, {'datas': res, 'count': count})
         except Exception as e:

+ 11 - 23
Controller/UidSetController.py

@@ -11,27 +11,23 @@
 @file: AliPayObject.py
 @Contact: pzb3076@163.com
 """
-import threading
 import time
 import traceback
 
 import requests
-from django.db.models import Count
-
-from Object.RedisObject import RedisObject
 import simplejson as json
+from django.db import transaction
 from django.utils.decorators import method_decorator
 from django.views.decorators.csrf import csrf_exempt
 from django.views.generic.base import View
 
-from Model.models import UidSetModel, Device_User, Device_Info, UidPushModel, Equipment_Info, UID_Preview, UID_Bucket, \
-    VodHlsModel, Order_Model, OssCrdModel, UidUserModel, UidChannelSetModel, User_Brand, ExperienceContextModel, \
-    StsCrdModel, Unused_Uid_Meal, UIDMainUser, LogModel, CountryModel
+from Model.models import UidSetModel, Device_Info, UidPushModel, Equipment_Info, UID_Preview, UID_Bucket, \
+    VodHlsModel, Order_Model, OssCrdModel, UidUserModel, UidChannelSetModel, ExperienceContextModel, \
+    StsCrdModel, Unused_Uid_Meal, LogModel, CountryModel
 from Object.ResponseObject import ResponseObject
 from Object.TokenObject import TokenObject
 from Service.CommonService import CommonService
 from Service.ModelService import ModelService
-from django.db import transaction
 from Service.VodHlsService import SplitVodHlsObject
 
 '''
@@ -107,7 +103,7 @@ class UidSetView(View):
         uid_set_qs = UidSetModel.objects.filter(uid__in=uid_list).values('uid', 'detect_status', 'detect_interval',
                                                                          'version', 'ucode', 'p2p_region', 'tz',
                                                                          'video_code', 'channel', 'cloud_vod')
-        
+
         if uid_set_qs.exists():
             return response.json(0, list(uid_set_qs))
         else:
@@ -139,7 +135,7 @@ class UidSetView(View):
                     del_uid = UidSetModel.objects.filter(uid__in=uid)
                     if del_uid.exists():
                         del_uid.delete()
-                        print ('删除UidSetModel')
+                        print('删除UidSetModel')
                     else:
                         val = 1
                         print('UidSetModel表没有数据')
@@ -149,7 +145,7 @@ class UidSetView(View):
                         del_uid.delete()
                         # print('删除Equipment_Info')
                     else:
-                        val = val+1
+                        val = val + 1
                         print('Equipment_Info表没有数据')
                 if 'UID_Preview' in id_list:
                     del_uid = UID_Preview.objects.filter(uid__in=uid)
@@ -431,6 +427,7 @@ class UidSetView(View):
         end_time = request_dict.get('end_time', None)
         repeat_day = request_dict.get('repeat_day', None)
         direction = request_dict.get('direction', None)
+        algorithm_type = int(request_dict.get('algorithmType', 99))
 
         if uid and channel:
             channel = int(channel)
@@ -440,41 +437,32 @@ class UidSetView(View):
                 ucs = {}
                 if enter_voice:
                     ucs['voice_prompt_enter'] = enter_voice
-
                 if leave_voice:
                     ucs['voice_prompt_leave'] = leave_voice
-
                 if voice_status:
                     ucs['voice_prompt_status'] = voice_status
-
                 if intelligent_mute:
                     ucs['voice_prompt_intelligent_mute'] = intelligent_mute
-
                 if start_x:
                     ucs['voice_start_x'] = start_x
-
                 if start_y:
                     ucs['voice_start_y'] = start_y
-
                 if end_x:
                     ucs['voice_end_x'] = end_x
-
                 if end_y:
                     ucs['voice_end_y'] = end_y
-
                 if start_time:
                     ucs['voice_start_time'] = start_time
-
                 if end_time:
                     ucs['voice_end_time'] = end_time
-
                 if repeat_day:
                     ucs['voice_repeat_day'] = repeat_day
-
                 if direction:
                     ucs['voice_direction'] = direction
+                ucs['algorithm_type'] = algorithm_type
 
                 uid_channel_set_qs = UidChannelSetModel.objects.filter(uid__uid=uid, channel=channel)
+                uid_channel_set_qs = uid_channel_set_qs.filter(algorithm_type=algorithm_type)
                 if not uid_channel_set_qs.exists():
                     uidObject = UidSetModel.objects.filter(uid=uid)
                     ucs['channel'] = channel
@@ -587,4 +575,4 @@ class UidSetView(View):
     #     di_qs = Device_Info.objects.values('area', 'Type').annotate(c=Count('UID', distinct=True)).order_by()
     #     for di in di_qs:
     #         print(di)
-    #     return response.json(0)
+    #     return response.json(0)

+ 15 - 9
Controller/VoicePromptController.py

@@ -64,9 +64,12 @@ class VoicePromptView(View):
         uid = request_dict.get('uid', None)
         channel = request_dict.get('channel', None)
         type = request_dict.get('type', None)
+        algorithm_type = int(request_dict.get('algorithmType', 99))
 
         if upload_type and uid and channel:
-            count = VoicePromptModel.objects.filter(uid=uid, channel=channel, type=type).count()
+            vp_qs = VoicePromptModel.objects.filter(uid=uid, channel=channel, type=type)
+            vp_qs = vp_qs.filter(algorithm_type=algorithm_type)
+            count = vp_qs.count()
             if count >= 3:
                 return response.json(201)
 
@@ -88,6 +91,7 @@ class VoicePromptView(View):
         lang = request_dict.get('lang', '')
         uid = request_dict.get('uid', None)
         channel = request_dict.get('channel', None)
+        algorithm_type = request_dict.get('algorithmType', None)
 
         if filename and title and type and uid and channel:
             voice_prompt = VoicePromptModel()
@@ -99,6 +103,8 @@ class VoicePromptView(View):
             voice_prompt.uid = uid
             voice_prompt.channel = channel
             voice_prompt.add_time = int(time.time())
+            if algorithm_type:
+                voice_prompt.algorithm_type = int(algorithm_type)
             voice_prompt.save()
 
             res = {
@@ -145,7 +151,6 @@ class VoicePromptView(View):
         elif ids:
             voice_qs = VoicePromptModel.objects.filter(id__in=ids.split(','))
 
-
         if not voice_qs.exists():
             return response.json(14)
 
@@ -171,11 +176,16 @@ class VoicePromptView(View):
         lang = request_dict.get('lang', None)
         uid = request_dict.get('uid', None)
         channel = request_dict.get('channel', None)
+        # 个性语音增加算法类型区分默认0兼容老版本
+        algorithm_type = int(request_dict.get('algorithmType', 99))
 
         if uid and channel and lang:
-            voice_qs = VoicePromptModel.objects.filter(uid=uid, channel=channel, classification=1)
-            system_qs = VoicePromptModel.objects.filter(classification=0, language=lang, status=1)
-            channel_qs = UidChannelSetModel.objects.filter(uid__uid=uid, channel=channel)
+            voice_qs = VoicePromptModel.objects.filter(uid=uid, channel=channel, classification=1,
+                                                       algorithm_type=algorithm_type)
+            system_qs = VoicePromptModel.objects.filter(classification=0, language=lang, status=1,
+                                                        algorithm_type=algorithm_type)
+            channel_qs = UidChannelSetModel.objects.filter(uid__uid=uid, channel=channel,
+                                                           algorithm_type=algorithm_type)
 
             res = {
                 'enter_voice': {},
@@ -373,7 +383,3 @@ class VoicePromptView(View):
             return response.json(0)
         else:
             return response.json(444)
-
-
-
-

+ 35 - 8
Service/EquipmentInfoService.py

@@ -11,7 +11,7 @@ import itertools
 import logging
 import time
 
-from django.db.models import Value, CharField
+from django.db.models import Value, CharField, Q
 
 from Model.models import EquipmentInfoMonday, EquipmentInfoTuesday, EquipmentInfoWednesday, EquipmentInfoThursday, \
     EquipmentInfoFriday, EquipmentInfoSaturday, EquipmentInfoSunday
@@ -169,9 +169,10 @@ class EquipmentInfoService:
         if event_type:
             # 多类型查询
             eventTypeList = cls.get_comb_event_type(event_type)
-            eventTypeList += cls.get_combo_type_bins(event_type)
+            # eventTypeList += cls.get_combo_type_bins(event_type)
             eventTypeList = list(set(eventTypeList))
-            qs = qs.filter(event_type__in=eventTypeList)
+            tags = cls.get_event_tag(event_type)
+            qs = qs.filter(Q(event_type__in=eventTypeList) | Q(event_tag__regex=tags))
         if start_time and end_time:
             qs = qs.filter(event_time__range=(start_time, end_time))
         else:
@@ -191,9 +192,9 @@ class EquipmentInfoService:
         @return: qs_page 遍历后的设备信息结果集
         """
         equipment_info_qs = equipment_info_qs.values('id', 'device_uid', 'device_nick_name', 'channel', 'event_type',
-                                                     'status', 'alarm',
+                                                     'status', 'answer_status', 'alarm',
                                                      'event_time', 'receive_time', 'is_st', 'add_time',
-                                                     'storage_location', 'border_coords', 'tab_val')
+                                                     'storage_location', 'border_coords', 'tab_val', 'event_tag')
 
         equipment_info_qs = equipment_info_qs.order_by('-event_time')
         qs_page = equipment_info_qs[(page - 1) * size:page * size]
@@ -212,6 +213,7 @@ class EquipmentInfoService:
             item['receiveTime'] = item['receive_time']
             item['addTime'] = item['add_time']
             item['borderCoords'] = item['border_coords']
+            item['eventTag'] = item['event_tag']
             item.pop('device_uid')
             item.pop('device_nick_name')
             item.pop('channel')
@@ -221,6 +223,7 @@ class EquipmentInfoService:
             item.pop('add_time')
             item.pop('border_coords')
             item.pop('tab_val')
+            item.pop('event_tag')
         return qs_page
 
     @classmethod
@@ -315,21 +318,27 @@ class EquipmentInfoService:
         return equipment_info
 
     @classmethod
-    def get_combo_types(cls, event_type):
+    def get_combo_types(cls, event_type, event_tag):
         """
         获取设备算法组合类型
         51:移动侦测,52:传感器报警,53:影像遗失,54:PIR,55:门磁报警,56:外部发报,57:人型报警(提示:有人出现),58:车型,59:宠物,60:人脸,61:异响,
+        62:区域闯入,63:区域闯出,64:长时间无人检测,65:长时间无人检测
         0:代表空字符,702:摄像头休眠,703:摄像头唤醒,704:电量过低
         AWS AI识别 1:人形,2:车型,3:宠物,4:包裹。云端AI类型
+        @param event_tag:
         @param event_type:
         @return:
         """
         try:
             types = []
+            if event_tag:
+                res = event_tag.split(',')
+                types = [int(var) for var in res if var]
+                return types
             res_type = cls.is_type_exist(event_type)
             if res_type == 0:
                 return types
-            combo_types = [51, 57, 58, 60, 59, 61]
+            combo_types = [51, 57, 58, 60, 59, 61, 62, 63, 64, 65]
             event_type = str(event_type)
             len_type = len(event_type)
             for i in range(0, len_type):
@@ -364,7 +373,7 @@ class EquipmentInfoService:
         """
         arr_list = []
         event_arr = []
-        resource_list = [1, 2, 4, 8, 16, 32]
+        resource_list = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
         for i in range(2, len(resource_list) + 1):
             arr_list += list(itertools.combinations(resource_list, i))  # 表示从 [1,2,3,4] 中选出 3个元素的组合情况
         for i in arr_list:
@@ -416,3 +425,21 @@ class EquipmentInfoService:
         except Exception as e:
             print('推送错误异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
             return res_list
+
+    @staticmethod
+    def get_event_tag(event_type):
+        """
+        获取标签用于筛选推送消息
+        """
+        if ',' in event_type:
+            tags = ''
+            res_list = event_type.split(',')
+            tag_size = len(res_list)
+            for i, item in enumerate(res_list):
+                tags += ',' + str(item) + ','
+                if i < (tag_size - 1):
+                    tags += '|'
+            return tags
+
+        else:
+            return ',' + str(event_type) + ','