views.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. from rest_framework.generics import GenericAPIView
  2. from rest_framework.response import Response
  3. import re
  4. import math
  5. from utils.JWTAuthentication_diy import APIAuthentication
  6. from utils.permissions import CbdDeviceDetailPermission
  7. from .serializers import ZhiBaoSelectViewSerializer
  8. from utils.JWTAuthentication_diy import MyJWTAuthentication
  9. from utils.permissions import ModulePermission
  10. from rest_framework.views import APIView
  11. from utils.db_utils import MongoDBTools
  12. from utils.all_dict import insect_dict
  13. from django.conf import settings
  14. from apps.PestAnalysis.models import CbdAddrPest, HeNanAddr
  15. from apps.PestAnalysis.serializers import CbdAddrPestSerializer
  16. class PestSelectView(GenericAPIView):
  17. authentication_classes = [MyJWTAuthentication]
  18. permission_classes = [ModulePermission]
  19. serializer_class = ZhiBaoSelectViewSerializer
  20. def get(self, request, *args, **kwargs):
  21. serializer = self.get_serializer(data=request.query_params)
  22. serializer.is_valid(raise_exception=True)
  23. data = serializer.validated_data
  24. identify_model = data["identify_model"]
  25. start_time = data["start_time"]
  26. end_time = data["end_time"]
  27. page = data["page"]
  28. page_size = data["page_size"]
  29. select_name = data.get("pest_name",'')
  30. if select_name:
  31. key_list=list(insect_dict.keys())
  32. val_list=list(insect_dict.values())
  33. ind = val_list.index(select_name)
  34. key = key_list[ind]+"," # 1665772530,1666125101
  35. wheres = {
  36. "photo_status": 1,
  37. "addtime": {
  38. "$gte": start_time,
  39. "$lt": end_time
  40. },
  41. "indentify_result": re.compile("#{}|^{}".format(key,key))
  42. }
  43. else:
  44. wheres = {
  45. "photo_status": 1,
  46. "addtime":{
  47. "$gte": start_time,
  48. "$lt": end_time
  49. },
  50. "indentify_result": {
  51. "$nin": ["", "0", None]
  52. }
  53. }
  54. project = {
  55. "device_id":"$device_id",
  56. "addr":"$addr",
  57. "indentify_photo":"$indentify_photo",
  58. "indentify_result": "$indentify_result",
  59. "addtime":"$addtime"
  60. }
  61. skip = (page-1)*page_size
  62. limit = page_size
  63. 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')
  64. photo_data = model.find_many(wheres=wheres, options=project, skip=skip, limit=limit)
  65. if photo_data:
  66. total_counts = photo_data.count()
  67. else:
  68. total_counts = 0
  69. data = {"total_page":math.ceil(total_counts/page_size), "total_counts":total_counts, "page_size":page_size, "current_page":page, "current_counts":0, "items":[]}
  70. d_id_list = []
  71. items = []
  72. for i in photo_data:
  73. d_id_list.append(int(i["device_id"]))
  74. items.append(i)
  75. data["current_counts"] += 1
  76. wheres = {
  77. "device_type_id":3,
  78. "id": {
  79. "$in": d_id_list
  80. }
  81. }
  82. project = {
  83. 'id': "$id",
  84. 'device_id': '$device_id',
  85. 'device_name': '$device_name',
  86. 'device_code': '$device_code',
  87. 'province': '$province',
  88. 'city': '$city',
  89. 'district': '$district'
  90. }
  91. m = MongoDBTools(db_name='smartfarming', table_name='sa_device')
  92. device_data = m.find_many(wheres=wheres, options=project)
  93. d_id_dicts = {}
  94. for device_item in device_data:
  95. d_id_dicts[device_item["id"]] = {"location":device_item["province"]+device_item["city"]+device_item["district"],
  96. "device_id":device_item["device_id"],
  97. "device_code":device_item["device_code"],
  98. "device_name":device_item["device_name"] if device_item["device_name"] else "测报灯"
  99. }
  100. pest_image_data = []
  101. for photo_object in items:
  102. indentify_result = photo_object["indentify_result"]
  103. pest_string = ""
  104. pest_dict = {}
  105. for index,result in enumerate(indentify_result.split("#")) :
  106. if index != 0:
  107. pest_string += "、"
  108. tuple_result = result.split(",")
  109. pest_name = insect_dict.get(tuple_result[0],"未命名")
  110. pest_string+=pest_name
  111. pest_dict[pest_name] = int(tuple_result[1])
  112. addtime = photo_object["addtime"]
  113. d_id = int(photo_object["device_id"])
  114. device_code = d_id_dicts.get(d_id,{"device_code":0}).get("device_code",0)
  115. img_path = settings.CONFIG["image_url"]["image"]
  116. if identify_model == "A":
  117. indentify_path = settings.CONFIG["image_url"]["discern"]
  118. elif identify_model == "B" and device_code == 4: # 水稻
  119. indentify_path = settings.CONFIG["image_url"]["discern"]
  120. else:
  121. indentify_path = settings.CONFIG["image_url"]["discernB"]
  122. if photo_object["addr"].startswith("http"):
  123. img_url = photo_object["addr"]
  124. elif photo_object["addr"].startswith('/'):
  125. img_url = img_path + photo_object["addr"]
  126. else:
  127. img_url = img_path + "/" + photo_object["addr"]
  128. if photo_object["indentify_photo"]:
  129. if photo_object["indentify_photo"].startswith("http"):
  130. indentify_photo = photo_object["indentify_photo"]
  131. elif photo_object["indentify_photo"].startswith('/'):
  132. indentify_photo = indentify_path + photo_object["indentify_photo"]
  133. else:
  134. indentify_photo = indentify_path + "/" + photo_object["indentify_photo"]
  135. else:
  136. indentify_photo = ""
  137. pest_image_data.append({"deviceId":str(d_id_dicts.get(d_id,{"device_id":d_id})["device_id"]),
  138. "deviceName":d_id_dicts.get(d_id,{"device_name":"测报灯"})["device_name"],
  139. "pestName":pest_string,
  140. "addtime":addtime,
  141. "location":d_id_dicts.get(d_id,{"location":""})["location"],
  142. "img_url":img_url,
  143. "indentify_photo":indentify_photo,
  144. "pest_dict":pest_dict
  145. })
  146. data["items"] = pest_image_data
  147. return Response(data)
  148. class RecentMonthPestCount(GenericAPIView):
  149. authentication_classes = [APIAuthentication]
  150. permission_classes = [CbdDeviceDetailPermission]
  151. def get(self, request, *args, **kwargs):
  152. try:
  153. data=request.query_params
  154. start = data.get("start")
  155. end = data.get("end")
  156. device_id = data.get("device_id")
  157. m = MongoDBTools(db_name='smartfarming', table_name='sa_device')
  158. device = m.find_one(wheres={"device_id": device_id}, options={"id": 1})
  159. d_id = device.get("id")
  160. sa_device_cbdphoto_b = MongoDBTools(db_name='smartfarming', table_name='sa_device_cbdphoto_b')
  161. data = sa_device_cbdphoto_b.find_many(
  162. wheres={
  163. "device_id": str(d_id),
  164. "addtime": {
  165. "$gte": int(start),
  166. "$lte": int(end)
  167. }
  168. },
  169. options={
  170. "id": 1,
  171. "indentify_result": 1,
  172. "addr": 1
  173. }
  174. )
  175. # 17,1#158,5#365,5#260,7#20,1#46,2#160,6#3,1#21,1
  176. result = {}
  177. imgs = []
  178. for i in data:
  179. indentify_result = i.get("indentify_result")
  180. addr = i.get("addr")
  181. if indentify_result:
  182. iden = indentify_result.split("#")
  183. for p in iden:
  184. pest, num = p.split(",")
  185. if pest in result.keys():
  186. result[pest] += int(num)
  187. else:
  188. result[pest] = int(num)
  189. imgs.append(addr if addr.startswith("http") else "https://bigdata-image.oss-cn-hangzhou.aliyuncs.com/Basics/cbd/" + addr)
  190. temp = {}
  191. for k, v in result.items():
  192. if k in insect_dict.keys():
  193. temp[insect_dict.get(k)] = v
  194. temp = sorted(temp.items(), key=lambda item: item[1], reverse=True)
  195. data = {
  196. "pest": dict(temp),
  197. "imgs": imgs[:10]
  198. }
  199. return Response(data)
  200. except Exception as e:
  201. return Response({"data": [], "imgs": [], "msg": e.args})
  202. class PestCountAPIView(APIView):
  203. def get(self, request, *args, **kwargs):
  204. try:
  205. data = request.query_params
  206. code = data.get("code")
  207. start = data.get("start")
  208. end = data.get("end")
  209. if code:
  210. hananaddr = HeNanAddr.objects.get(code=code)
  211. if hananaddr.district:
  212. query = CbdAddrPest.objects.filter(addr_code=code)
  213. if start and end:
  214. query = query.filter(format_date__range=[start, end])
  215. data = CbdAddrPestSerializer(query, many=True).data
  216. return Response(data)
  217. except Exception as e:
  218. return Response({"data": [], "imgs": [], "msg": e.args})