views.py 13 KB

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