# from codecs import ignore_errors
# from genericpath import exists
# from http.server import BaseHTTPRequestHandler, HTTPServer
# import json
# import os
# import subprocess
# import numpy as np
# import pdb
# import re
# from PIL import Image
# from http.server import HTTPServer
# import json
# import os
# import cgi
# from hikframe.dl.utils import dotdict


# def infer_ret_parser(det_ret):
#     img_names = list(det_ret.keys())
#     # 输出拼接
#     rets = []
#     for img_name in img_names:
#         ret = ''
#         ret += img_name
#         for det in det_ret[img_name]:
#             if len(det) == 6:
#                 label, score, x_min, y_min, x_max, y_max = det
#                 ret += ' '
#                 pred = '{}:{:.3f} {} {} {} {}'.format(label, score, x_min,
#                                                       y_min, x_max, y_max)
#                 ret += pred
#             elif len(det) == 2:
#                 label, score = det
#                 ret += ' '
#                 pred = '{}:{:.3f}'.format(label, score)
#                 ret += pred
#             else:
#                 raise NotImplementedError
#         rets.append(ret)
#     return rets


# def result_parser(ret, sample_path):
#     # todo zyl:
#     # 读取 save_dir里的测试输出json/img
#     results_dict = {
#         "img_file": "",
#         "img_size": "",
#         "predicted": "",
#         "info": ""
#     }
#     data = ret.strip().split(' ')
#     if len(data) == 2:
#         task_type = '图像分类'
#     elif len(data) >= 6:
#         task_type = '图像检测'
#     else:
#         task_type = 'unknow'
#     if task_type == '图像分类':
#         results_dict = {
#             "img_file": "",
#             "img_size": "",
#             "predicted": {
#                 "predicted_label": "",
#                 "scores": {}
#             },
#             "info": ""
#         }
#         data = ret.strip().split(' ')
#         scores = {}
#         maxScore = 0
#         maxScoreLabel = ''
#         for x in data[1].split(','):
#             k, v = x.split(':')
#             scores[k] = v
#             results_dict["predicted"]["scores"][k] = v
#             if float(v) >= maxScore:
#                 maxScore = float(v)
#                 maxScoreLabel = k
#         results_dict["predicted"]["predicted_label"] = maxScoreLabel

#     elif task_type == '图像检测':
#         max_num = 30
#         results_dict = {
#             "img_file": "",
#             "img_size": "",
#             "predicted": {
#                 "detected_object": []
#             },
#             "info": ""
#         }

#         data = ret.strip().split(' ')
#         index = -1
#         for i in range(1, len(data), 5):
#             if index >= max_num:
#                 break
#             index += 1
#             t_obj = {
#                 "predicted_label": "",
#                 "scores": {},
#                 "bbox": {
#                     "xmin": 0,
#                     "ymin": 0,
#                     "xmax": 0,
#                     "ymax": 0
#                 }
#             }
#             # info = ' '.join(data[i:i+6])+'\n'
#             scores_str = data[i]
#             scores = {}
#             maxScore = 0
#             maxScoreLabel = ''
#             for x in scores_str.split(','):
#                 k, v = x.split(':')
#                 scores[k] = v
#                 t_obj["scores"][k] = v
#                 if float(v) >= maxScore:
#                     maxScore = float(v)
#                     maxScoreLabel = k
#             t_obj["predicted_label"] = maxScoreLabel
#             t_obj["bbox"]["xmin"] = data[i + 1]
#             t_obj["bbox"]["ymin"] = data[i + 2]
#             t_obj["bbox"]["xmax"] = data[i + 3]
#             t_obj["bbox"]["ymax"] = data[i + 4]
#             t_obj["index"] = index
#             results_dict["predicted"]["detected_object"].append(t_obj)
#     else:
#         pass
#         print('can not parser result.')
#     try:
#         if os.path.basename(sample_path).endswith((".png", ".jpeg", ".jpg", ".bmp")):
#             results_dict["img_file"] = sample_path
#             # img = cv2.imread(sample_path)
#             img = np.array(Image.open(sample_path))
#             results_dict["img_size"] = {}
#             results_dict["img_size"]["height"], results_dict["img_size"]["width"], results_dict["img_size"]["depth"] = img.shape
#     except Exception as e:
#         print(e)
#     return results_dict


# def generate_result(img_path, save_dir, ret):
#     """
#     return format:
#     clf:
#     9.9.jpg 0:0.000,1:0.236,2:0.003,3:0.001,4:0.011,5:0.006,6:0.003,7:0.215,8:0.000,9:0.524
#     det:
#     000005.jpg chair:0.969 278.8556213378906 185.5542449951172 311.0206604003906 220.06031799316406
#     """
#     if type(ret) == dict:
#         ret = infer_ret_parser(ret)[0]

#     # 统一的输出格式
#     results_dict = {
#         "img_file": "",
#         "img_size": {},
#         "predicted": "",
#         "info": ""
#     }
#     # 查看是否有需要前端展示的图片
#     try:
#         for f in os.listdir(save_dir):
#             if f.endswith((".png", ".jpeg", ".jpg", ".bmp")):
#                 img_file = os.path.join(save_dir, f)
#                 # img = cv2.imread(img_file)
#                 img = np.array(Image.open(img_file))
#                 results_dict["img_file"] = img_file
#                 results_dict["img_size"] = {}
#                 results_dict["img_size"]["height"], results_dict["img_size"]["width"], results_dict["img_size"]["depth"] = img.shape
#                 break
#     except Exception as e:
#         print('can not find img for show.')
#         print(e)

#     try:
#         t_ret_dcit = result_parser(ret, img_path)
#         results_dict["predicted"] = t_ret_dcit["predicted"]
#         results_dict["info"] = t_ret_dcit["info"]
#         # 展示输入的图片
#         if not results_dict["img_file"]:
#             results_dict["img_file"] = t_ret_dcit["img_file"]
#             results_dict["img_size"] = t_ret_dcit["img_size"]
#     except Exception as e:
#         print('can not use default parser!')
#         print(e)
#         try:
#             ret = json.loads(ret)
#         except Exception as e:
#             print(e)
#             pass
#         # results_dict["predicted"] = ret_list
#         results_dict["predicted"] = ret

#     print("results_dict:")
#     print(results_dict)
#     return results_dict


# class RequestHandler(BaseHTTPRequestHandler):
#     # def _generate_result(self, img_path, save_dir, ret):
#     #     ret_dict = generate_result(img_path, save_dir, ret)
#     #     ret = {}
#     #     ret['status'] = True
#     #     ret['info'] = ret

#     #     self.send_response(200)
#     #     self.send_header("Content-type", "application/json")
#     #     self.send_header("Access-Control-Allow-Origin", "*")
#     #     self.send_header("Access-Control-Allow-Methods", "*")
#     #     self.send_header("Access-Control-Allow-Headers",
#     #                      "Authorization, Content-Type")
#     #     self.end_headers()
#     #     self.wfile.write(json.dumps(ret).encode())
#     #     return ret_dict
#     def _generate_result(self, ret_dict):
#         ret = {}
#         ret['status'] = True
#         ret['info'] = ret_dict

#         self.send_response(200)
#         self.send_header("Content-type", "application/json")
#         self.send_header("Access-Control-Allow-Origin", "*")
#         self.send_header("Access-Control-Allow-Methods", "*")
#         self.send_header("Access-Control-Allow-Headers",
#                          "Authorization, Content-Type")
#         self.end_headers()
#         self.wfile.write(json.dumps(ret).encode())
#         return ret_dict

#     def _get_data(self, tmp_dir):
#         form = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={
#                                 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': self.headers['Content-Type'], })
#         filename = form['file'].filename
#         data = form['file'].file.read()
#         file_path = os.path.join(tmp_dir, filename)
#         with open(file_path, 'wb') as f:
#             f.write(data)
#         return file_path


# if __name__ == "__main__":
#     serverAddress = ('', 8081)
#     server = HTTPServer(serverAddress, RequestHandler)
#     server.serve_forever()
