Jelajahi Sumber

测报灯图片分析模块功能实现

yf_fyh 3 tahun lalu
induk
melakukan
16ccc1f3af

+ 0 - 2
apps/Equipment/views.py

@@ -10,7 +10,6 @@ from utils.utils import get_equip_list
 from utils.db_utils import MongoDBTools
 
 
-
 # Create your views here.
 
 class SearchEquip(APIView):
@@ -32,7 +31,6 @@ class QxzDeviceListView(APIView):
     def get(self, request, *args, **kwargs):
         """获取气象站设备列表接口"""
         uid = request.user
-        # uid = 896
         
         wheres = {
             "device_type_id":5,

+ 40 - 0
apps/PestAnalysis/serializers.py

@@ -0,0 +1,40 @@
+from rest_framework import serializers
+
+
+class ZhiBaoSelectViewSerializer(serializers.Serializer):
+    identify_model = serializers.CharField(help_text="识别模型", required=True)
+    start_time = serializers.IntegerField(help_text="开始时间 秒级时间戳", required=True)
+    end_time = serializers.IntegerField(help_text="结束时间 秒级时间戳", required=True)
+    pest_name = serializers.CharField(help_text="害虫名称", required=False)
+    page = serializers.IntegerField(help_text="页码", required=True)
+    page_size = serializers.IntegerField(help_text="每页数量", required=True)
+
+    def validate_identify_model(self, value):
+        if value not in ["A","B"]:
+            raise serializers.ValidationError("无法识别筛选模型")
+        return value
+
+    def validate_start_time(self, value):
+        if value<0:
+            raise serializers.ValidationError("时间戳不能小于0")
+        return value
+    
+    def validate_end_time(self, value):
+        if value<0:
+            raise serializers.ValidationError("时间戳不能小于0")
+        return value
+    
+    def validate_page(self, value):
+        if value<1:
+            raise serializers.ValidationError("页码不能小于1")
+        return value
+    
+    def validate_page_size(self, value):
+        if value<1:
+            raise serializers.ValidationError("每页数据不能小于1")
+        return value
+
+    def validate(self, attrs):
+        if attrs["start_time"] > attrs["end_time"]:
+            raise serializers.ValidationError("结束时间不能小于开始时间")
+        return attrs

+ 7 - 0
apps/PestAnalysis/urls.py

@@ -0,0 +1,7 @@
+from django.conf.urls import url
+
+from . import views
+
+urlpatterns = [
+    url(r'^info/$', views.PestSelectView.as_view(), name='pest_info'),
+]

+ 151 - 0
apps/PestAnalysis/views.py

@@ -0,0 +1,151 @@
+from rest_framework.generics import GenericAPIView
+from rest_framework.response import Response
+import re
+import math
+
+from .serializers import ZhiBaoSelectViewSerializer
+from utils.JWTAuthentication_diy import MyJWTAuthentication
+from utils.permissions import ModulePermission
+
+from utils.db_utils import MongoDBTools
+from utils.all_dict import insect_dict
+from django.conf import settings
+
+
+class PestSelectView(GenericAPIView):
+    authentication_classes = [MyJWTAuthentication]
+    permission_classes = [ModulePermission]
+    serializer_class = ZhiBaoSelectViewSerializer
+
+    def get(self, request, *args, **kwargs):
+        serializer = self.get_serializer(data=request.query_params)
+        serializer.is_valid(raise_exception=True)
+        data = serializer.validated_data
+        identify_model = data["identify_model"]
+        start_time = data["start_time"]
+        end_time = data["end_time"]
+        page = data["page"]
+        page_size = data["page_size"]
+        select_name = data.get("pest_name",'')
+
+        if select_name:
+            key_list=list(insect_dict.keys())
+            val_list=list(insect_dict.values())
+            ind = val_list.index(select_name)
+            key = key_list[ind]+","   # 1665772530,1666125101
+            wheres = {
+                "photo_status": 1,
+                "addtime": {
+                    "$gte": start_time,
+                    "$lt": end_time
+                },
+                "indentify_result": re.compile("#{}|^{}".format(key,key))
+            }
+        else:
+            wheres = {
+                "photo_status": 1,
+                "addtime":{
+                    "$gte": start_time,
+                    "$lt": end_time
+                },
+                "indentify_result": {
+                    "$nin": ["", "0", None]
+                }
+            }
+        project = {
+            "device_id":"$device_id",
+            "addr":"$addr",
+            "indentify_photo":"$indentify_photo",
+            "indentify_result": "$indentify_result",
+            "addtime":"$addtime"
+        }
+        skip = (page-1)*page_size
+        limit = page_size
+        model = MongoDBTools(db_name='smartfarming', table_name='sa_device_cbdphoto') if identify_model == "A" else MongoDBTools(db_name='smartfarming', table_name='sa_device_cbdphoto_b')
+        photo_data = model.find_many(wheres=wheres, options=project, skip=skip, limit=limit)
+        if photo_data:
+            total_counts = photo_data.count()
+        else:
+            total_counts = 0
+        data = {"total_page":math.ceil(total_counts/page_size), "total_counts":total_counts, "page_size":page_size, "current_page":page, "current_counts":0, "items":[]}
+        d_id_list = []
+        items = []
+        for i in photo_data:
+            d_id_list.append(int(i["device_id"]))
+            items.append(i)
+            data["current_counts"] += 1
+
+        wheres = {
+            "device_type_id":3,
+            "id": {
+                "$in": d_id_list
+            }
+        }
+        project = {
+            'id': "$id",
+            'device_id': '$device_id',
+            'device_name': '$device_name',
+            'device_code': '$device_code',
+            'province': '$province',
+            'city': '$city',
+            'district': '$district'
+        }
+        m = MongoDBTools(db_name='smartfarming', table_name='sa_device')
+        device_data = m.find_many(wheres=wheres, options=project)
+        d_id_dicts = {}
+        for device_item in device_data:
+            d_id_dicts[device_item["id"]] = {"location":device_item["province"]+device_item["city"]+device_item["district"],
+                                            "device_id":device_item["device_id"],
+                                            "device_code":device_item["device_code"],
+                                            "device_name":device_item["device_name"] if device_item["device_name"] else "测报灯"
+                                            }
+        pest_image_data = []
+        for photo_object in items:
+            indentify_result = photo_object["indentify_result"]
+            pest_string = ""
+            pest_dict = {}
+            for index,result in enumerate(indentify_result.split("#")) :
+                if index != 0:
+                    pest_string += "、"
+                tuple_result = result.split(",")
+                pest_name = insect_dict.get(tuple_result[0],"未命名")
+                pest_string+=pest_name
+                pest_dict[pest_name] = int(tuple_result[1])
+
+            addtime = photo_object["addtime"]
+            d_id = int(photo_object["device_id"])
+            device_code = d_id_dicts.get(d_id,{"device_code":0}).get("device_code",0)
+            
+            img_path = settings.CONFIG["image_url"]["image"]
+            if identify_model == "A":
+                indentify_path = settings.CONFIG["image_url"]["discern"]
+            elif identify_model == "B" and device_code == 4:    # 水稻
+                indentify_path = settings.CONFIG["image_url"]["discern"]
+            else:
+                indentify_path = settings.CONFIG["image_url"]["discernB"]
+            if photo_object["addr"].startswith("http"):
+                img_url = photo_object["addr"] 
+            elif photo_object["addr"].startswith('/'):
+                img_url = img_path + photo_object["addr"]
+            else:
+                img_url = img_path + "/" + photo_object["addr"]
+            if photo_object["indentify_photo"]:
+                if photo_object["indentify_photo"].startswith("http"):
+                    indentify_photo = photo_object["indentify_photo"]
+                elif photo_object["indentify_photo"].startswith('/'):
+                    indentify_photo = indentify_path + photo_object["indentify_photo"]
+                else:
+                    indentify_photo = indentify_path + "/" + photo_object["indentify_photo"]
+            else:
+                indentify_photo = ""
+            pest_image_data.append({"deviceId":d_id_dicts.get(d_id,{"device_id":d_id})["device_id"],
+                                    "deviceName":d_id_dicts.get(d_id,{"device_name":"测报灯"})["device_name"],
+                                    "pestName":pest_string,
+                                    "addtime":addtime,
+                                    "location":d_id_dicts.get(d_id,{"location":""})["location"],
+                                    "img_url":img_url,
+                                    "indentify_photo":indentify_photo,
+                                    "pest_dict":pest_dict
+            })
+        data["items"] = pest_image_data
+        return Response(data)

+ 1 - 0
bigdataAPI/urls.py

@@ -21,4 +21,5 @@ urlpatterns = [
     path('iotcard/', include('apps.IOTCard.urls')),
     path('user/', include('apps.UserApp.urls')),
     path('equipment/', include('apps.Equipment.urls')),
+    path('pestanalysis/', include('apps.PestAnalysis.urls')),
 ]

+ 5 - 0
formal.json

@@ -22,5 +22,10 @@
 		"port": 57017,
 		"user": "root",
 		"pwd": "yfkj@6020"
+	},
+	"image_url": {
+		"image": "https://bigdata-image.oss-cn-hangzhou.aliyuncs.com/Basics/cbd",
+		"discern" : "https://bigdata-image.oss-cn-hangzhou.aliyuncs.com/Result/cbd",
+		"discernB" : "https://bigdata-image.oss-cn-hangzhou.aliyuncs.com/ResultB/cbd"
 	}
 }

+ 5 - 0
test.json

@@ -22,5 +22,10 @@
 		"port": 27017,
 		"user": "root",
 		"pwd": "yfkj@6020"
+	},
+	"image_url": {
+		"image": "http://bigdata-all.oss-accelerate.aliyuncs.com/Basics/cbd",
+		"discern" : "http://bigdata-all.oss-accelerate.aliyuncs.com/Result/cbd",
+		"discernB" : "http://bigdata-all.oss-accelerate.aliyuncs.com/ResultB/cbd"
 	}
 }

+ 2 - 2
utils/JWTAuthentication_diy.py

@@ -11,7 +11,7 @@ PrAes = aescrypt(SECRET_KEY, 'ECB', '', 'gbk')
 
 
 def get_token(user):
-    data = str(user.id) + "," + user.username + "," + str(user.user_modules)
+    data = str(user.id) + "," + user.username + "," + str(user.user_modules) + "," + str(user.is_superuser)
     data = PrAes.aesencrypt(data)
     payload = {"token": data}
 
@@ -30,7 +30,7 @@ class MyJWTAuthentication(BaseAuthentication):
                     data = str(data).replace("%2B", "+").replace(" ", "+")
                 data = PrAes.aesdecrypt(data)
                 data_list = data.split(",")
-                user = {"uid": data_list[0], "username": data_list[1], "user_modules": data_list[2]}
+                user = {"uid": data_list[0], "username": data_list[1], "user_modules": data_list[2], "is_superuser":data_list[3]}
                 return (user, token)
             except jwt.ExpiredSignature:
                 msg = 'token过期'

File diff ditekan karena terlalu besar
+ 1052 - 0
utils/all_dict.py


+ 6 - 4
utils/permissions.py

@@ -19,12 +19,14 @@ class ModulePermission(BasePermission):
     def has_permission(self, request, view):
         try:
             user = request.user
+            is_superuser = user.get("is_superuser")
             user_modules = user.get("user_modules")
             path = request.path
-            if path.startswith("/equipment") and user_modules == "1":
-                return True
-            else:
-                return False
+            if path.startswith("/pestanalysis"):
+                if is_superuser == "True" or user_modules == "1":
+                    return True
+                else:
+                    return False
         except:
             return False