views.py 8.8 KB

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