|
|
@@ -0,0 +1,259 @@
|
|
|
+from io import BytesIO
|
|
|
+import json
|
|
|
+import time
|
|
|
+import pandas as pd
|
|
|
+import ast
|
|
|
+from django.views.generic import ListView
|
|
|
+from django.http import HttpResponse
|
|
|
+from django.utils.encoding import escape_uri_path
|
|
|
+from django.conf import settings
|
|
|
+from django.db.models import Q
|
|
|
+from smartfarming.models.worm_forecast import MongoCBDphoto, MongoCBDphoto_B
|
|
|
+from smartfarming.models.device import MongoDevice
|
|
|
+from smartfarming.models.user import DeviceUser
|
|
|
+from smartfarming.api.views.forecast.all_dict import insect_dict
|
|
|
+from kedong.decoration import kedong_deco, PortError
|
|
|
+
|
|
|
+config_dict = settings.CONFIG
|
|
|
+
|
|
|
+
|
|
|
+class PestImageSourceExport(ListView):
|
|
|
+ def get(self, request, *args, **kwargs):
|
|
|
+ '''
|
|
|
+ 测报灯害虫图像信息溯源数据导出
|
|
|
+ '''
|
|
|
+ parameters = request.GET
|
|
|
+ d_ids = parameters.get("d_ids")
|
|
|
+ device_type = parameters.get("device_type","cbd")
|
|
|
+ identify_model = parameters.get("identify_model")
|
|
|
+ start_time = int(parameters.get("start_time"))
|
|
|
+ end_time = int(parameters.get("end_time"))
|
|
|
+ select_name = parameters.get("pest_name")
|
|
|
+ filename = parameters.get("filename")
|
|
|
+ # 获取统计模型
|
|
|
+ if device_type == "cbd":
|
|
|
+ insect_pest_dict = insect_dict
|
|
|
+ if identify_model:
|
|
|
+ model = MongoCBDphoto if identify_model == "A" else MongoCBDphoto_B
|
|
|
+ else:
|
|
|
+ return HttpResponse(json.dumps({"code":"400","type":"identify_model参数为空"},ensure_ascii=False))
|
|
|
+ # 获取统计设备列表
|
|
|
+ if d_ids:
|
|
|
+ d_id_list = [int(d_id) for d_id in d_ids.split(",")]
|
|
|
+ d_id_dicts = {}
|
|
|
+ device_queryset = MongoDevice.objects.filter(id__in=d_id_list)
|
|
|
+ for device_object in device_queryset:
|
|
|
+ d_id_dicts[device_object.id] = {
|
|
|
+ "location":device_object.province+device_object.city+device_object.district,
|
|
|
+ "device_id":device_object.device_id,
|
|
|
+ "device_code":device_object.device_code,
|
|
|
+ "device_name":device_object.device_name if device_object.device_name else "测报灯"
|
|
|
+ }
|
|
|
+ else:
|
|
|
+ raise PortError("d_ids","参数缺失")
|
|
|
+ disable = 1
|
|
|
+ # 统计
|
|
|
+ photo_queryset = model.objects.filter(device_id__in=list(d_id_dicts.keys()))
|
|
|
+ photo_queryset = photo_queryset.filter(photo_status=1)
|
|
|
+ photo_queryset = photo_queryset.filter(addtime__gte=start_time)
|
|
|
+ photo_queryset = photo_queryset.filter(addtime__lte=end_time)
|
|
|
+ if amend == "0":
|
|
|
+ photo_queryset = photo_queryset.exclude(indentify_result="").order_by("-addtime")
|
|
|
+ else:
|
|
|
+ photo_queryset = photo_queryset.filter(~Q(indentify_result="") | Q(is_mark=1)).order_by("-addtime")
|
|
|
+ save_data = dict(设备ID=[],设备名称=[],害虫名称=[],上报时间=[],设备位置=[],图像=[])
|
|
|
+ for photo_object in photo_queryset:
|
|
|
+ # 单张照片结果
|
|
|
+ indentify_result = photo_object.indentify_result
|
|
|
+ is_mark = photo_object.is_mark
|
|
|
+ mark = photo_object.mark
|
|
|
+ pest_string = ""
|
|
|
+ if amend == "1" and is_mark==1:
|
|
|
+ if mark == "[]":
|
|
|
+ continue
|
|
|
+ else:
|
|
|
+ try:
|
|
|
+ mark = json.loads(mark)
|
|
|
+ except:
|
|
|
+ mark = ast.literal_eval(mark)
|
|
|
+ for index,label in enumerate(mark):
|
|
|
+ pest_name = label.get("text")
|
|
|
+ if pest_name not in pest_string:
|
|
|
+ if index != 0:
|
|
|
+ pest_string += "、"
|
|
|
+ pest_string += pest_name
|
|
|
+ else:
|
|
|
+ if disable == 1:
|
|
|
+ if indentify_result and indentify_result != "0":
|
|
|
+ for index, result in enumerate(indentify_result.split("#")) :
|
|
|
+ if index != 0:
|
|
|
+ pest_string += "、"
|
|
|
+ tuple_result = result.split(",")
|
|
|
+ pest_name = insect_pest_dict.get(tuple_result[0],"未命名")
|
|
|
+ pest_string+=pest_name
|
|
|
+ else:
|
|
|
+ continue
|
|
|
+ else:
|
|
|
+ continue
|
|
|
+ if select_name and select_name not in pest_string:
|
|
|
+ continue
|
|
|
+ addtime = photo_object.addtime
|
|
|
+ time_strf = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(addtime))
|
|
|
+ __d_id = int(photo_object.device_id)
|
|
|
+ device_code = d_id_dicts[__d_id]["device_code"]
|
|
|
+ indentify_photo = photo_object.indentify_photo
|
|
|
+
|
|
|
+ if device_type == "cbd":
|
|
|
+ img_path = config_dict["image_url"]["image"]
|
|
|
+ if identify_model == "A":
|
|
|
+ indentify_path = config_dict["image_url"]["discern"]
|
|
|
+ elif identify_model == "B" and device_code == 4: # 水稻
|
|
|
+ indentify_path = config_dict["image_url"]["discern"]
|
|
|
+ else:
|
|
|
+ indentify_path = config_dict["image_url"]["discernB"]
|
|
|
+ elif device_type == "xct":
|
|
|
+ indentify_path = config_dict["image_url"]["xct_photo"]
|
|
|
+ if indentify_photo and (indentify_photo not in ["0", ""]):
|
|
|
+ indentify_path = config_dict["image_url"]["xct_discern_photo"]
|
|
|
+
|
|
|
+ if indentify_photo and (indentify_photo not in ["0", ""]):
|
|
|
+ if indentify_photo.startswith("http"):
|
|
|
+ indentify_photo = photo_object.indentify_photo
|
|
|
+ elif indentify_photo.startswith('/'):
|
|
|
+ indentify_photo = indentify_path + indentify_photo
|
|
|
+ else:
|
|
|
+ indentify_photo = indentify_path + "/" + indentify_photo
|
|
|
+ else:
|
|
|
+ if photo_object.addr.startswith("http"):
|
|
|
+ indentify_photo = photo_object.addr
|
|
|
+ elif photo_object.addr.startswith('/'):
|
|
|
+ indentify_photo = indentify_path + photo_object.addr
|
|
|
+ else:
|
|
|
+ indentify_photo = indentify_path + "/" + photo_object.addr
|
|
|
+ save_data["设备ID"].append(d_id_dicts[__d_id]["device_id"])
|
|
|
+ save_data["设备名称"].append(d_id_dicts[__d_id]["device_name"])
|
|
|
+ save_data["害虫名称"].append(pest_string)
|
|
|
+ save_data["上报时间"].append(time_strf)
|
|
|
+ save_data["设备位置"].append(d_id_dicts[__d_id]["location"])
|
|
|
+ save_data["图像"].append(indentify_photo)
|
|
|
+ df = pd.DataFrame(data=save_data)
|
|
|
+ output = BytesIO()
|
|
|
+ df.to_excel(output,index=False)
|
|
|
+ output.seek(0)
|
|
|
+ response = HttpResponse(content_type='application/vnd.ms-excel')
|
|
|
+ response['Content-Disposition'] = 'attachment;filename={}.xls'.format(escape_uri_path(filename))
|
|
|
+ response.write(output.getvalue())
|
|
|
+ return response
|
|
|
+
|
|
|
+
|
|
|
+class pest_base_data_export(ListView):
|
|
|
+ # 虫害基础数据
|
|
|
+ def get(self, request, *args, **kwargs):
|
|
|
+ '''
|
|
|
+ 测报灯害虫基础数据导出
|
|
|
+ '''
|
|
|
+ parameters = request.GET
|
|
|
+ d_ids = parameters.get("d_ids")
|
|
|
+ device_type = parameters.get("device_type","cbd")
|
|
|
+ identify_model = parameters.get("identify_model")
|
|
|
+ start_time = int(parameters.get("start_time"))
|
|
|
+ end_time = int(parameters.get("end_time"))
|
|
|
+ select_name = parameters.get("pest_name")
|
|
|
+ filename = parameters.get("filename")
|
|
|
+ amend = parameters.get("amend","0")
|
|
|
+ uid = parameters.get("uid")
|
|
|
+
|
|
|
+ # 获取统计模型
|
|
|
+ if device_type == "cbd":
|
|
|
+ insect_pest_dict = insect_dict
|
|
|
+ if identify_model:
|
|
|
+ model = MongoCBDphoto if identify_model == "A" else MongoCBDphoto_B
|
|
|
+ else:
|
|
|
+ return HttpResponse(json.dumps({"code":"400","type":"identify_model参数为空"},ensure_ascii=False))
|
|
|
+ else:
|
|
|
+ model = MongoXCTphoto
|
|
|
+ insect_pest_dict = xct_pest_dict
|
|
|
+
|
|
|
+ # 获取统计设备列表
|
|
|
+ if d_ids:
|
|
|
+ d_id_list = [int(d_id) for d_id in d_ids.split(",")]
|
|
|
+ else:
|
|
|
+ raise PortError("d_ids","参数缺失")
|
|
|
+
|
|
|
+ if device_type == "cbd":
|
|
|
+ myuser = DeviceUser.objects.get(uid=int(uid))
|
|
|
+ if myuser.user_type == 1:
|
|
|
+ disable = 1
|
|
|
+ else:
|
|
|
+ if len(d_id_list) == 1:
|
|
|
+ # 单设备根据是否支持识别区分
|
|
|
+ disable = Device.objects.get(id=d_id_list[0]).disable
|
|
|
+ else:
|
|
|
+ # 多设备保持原逻辑不动
|
|
|
+ disable = 0
|
|
|
+ else:
|
|
|
+ disable = 1
|
|
|
+
|
|
|
+ # 统计
|
|
|
+ photo_queryset = model.objects.filter(device_id__in=d_id_list)
|
|
|
+ photo_queryset = photo_queryset.filter(photo_status=1)
|
|
|
+ # photo_queryset = photo_queryset.filter(addtime__range=(start_time, end_time))
|
|
|
+ photo_queryset = photo_queryset.filter(addtime__gte=start_time)
|
|
|
+ photo_queryset = photo_queryset.filter(addtime__lte=end_time)
|
|
|
+ if amend == "0":
|
|
|
+ photo_queryset = photo_queryset.exclude(indentify_result="").order_by("-addtime")
|
|
|
+ else:
|
|
|
+ photo_queryset = photo_queryset.filter(~Q(indentify_result="") | Q(is_mark=1)).order_by("-addtime")
|
|
|
+ save_data = dict(害虫名称=[],害虫数量=[],上报时间=[])
|
|
|
+ for photo_object in photo_queryset:
|
|
|
+ # 单张照片结果
|
|
|
+ indentify_result = photo_object.indentify_result
|
|
|
+ mark = photo_object.mark
|
|
|
+ is_mark = photo_object.is_mark
|
|
|
+ addtime = photo_object.addtime
|
|
|
+ time_strf = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(addtime))
|
|
|
+ if amend == "1" and is_mark==1:
|
|
|
+ try:
|
|
|
+ mark = json.loads(mark)
|
|
|
+ except:
|
|
|
+ mark = ast.literal_eval(mark)
|
|
|
+ pest_dict = {}
|
|
|
+ for label in mark:
|
|
|
+ pest_name = label.get("text")
|
|
|
+ pest_num = 1
|
|
|
+ if select_name and select_name not in pest_name:
|
|
|
+ continue
|
|
|
+ if pest_name in pest_dict:
|
|
|
+ pest_dict[pest_name] += pest_num
|
|
|
+ else:
|
|
|
+ pest_dict[pest_name] = pest_num
|
|
|
+ for label_key,label_value in pest_dict.items():
|
|
|
+ save_data["害虫名称"].append(label_key)
|
|
|
+ save_data["害虫数量"].append(label_value)
|
|
|
+ save_data["上报时间"].append(time_strf)
|
|
|
+
|
|
|
+ else:
|
|
|
+ if disable == 1:
|
|
|
+ if indentify_result and indentify_result != "0":
|
|
|
+ for result in indentify_result.split("#"):
|
|
|
+ tuple_result = result.split(",")
|
|
|
+ pest_name = insect_pest_dict.get(tuple_result[0],"未命名")
|
|
|
+ if select_name and select_name not in pest_name:
|
|
|
+ continue
|
|
|
+ pest_num = int(tuple_result[1])
|
|
|
+
|
|
|
+ save_data["害虫名称"].append(pest_name)
|
|
|
+ save_data["害虫数量"].append(pest_num)
|
|
|
+ save_data["上报时间"].append(time_strf)
|
|
|
+ else:
|
|
|
+ continue
|
|
|
+ else:
|
|
|
+ continue
|
|
|
+ df = pd.DataFrame(data=save_data)
|
|
|
+ output = BytesIO()
|
|
|
+ df.to_excel(output,index=False)
|
|
|
+ output.seek(0)
|
|
|
+ response = HttpResponse(content_type='application/vnd.ms-excel')
|
|
|
+ response['Content-Disposition'] = 'attachment;filename={}.xls'.format(escape_uri_path(filename))
|
|
|
+ response.write(output.getvalue())
|
|
|
+ return response
|