You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

143 lines
3.9 KiB

6 years ago
  1. from flask import Flask, request
  2. from flask_restful import Resource, Api, abort
  3. import json
  4. import io
  5. import base64
  6. from PIL import Image
  7. import sys,getpass
  8. import datetime
  9. import cv2
  10. import ssl
  11. from urllib.parse import urlencode
  12. from urllib.request import Request, urlopen
  13. if getpass.getuser() == "tedankara":
  14. import tensorflow as tf
  15. import numpy as np
  16. import pickle
  17. sys.path.insert(0, r'C:\Users\Tednokent01\Downloads\MyCity\traffic_analyzer')
  18. from object_detection.utils import label_map_util
  19. from object_detection.utils import visualization_utils as vis_util
  20. app = Flask(__name__)
  21. api = Api(app)
  22. context = ssl._create_unverified_context()
  23. score_dict = {
  24. 1: 1,
  25. 2: 1,
  26. 3: 1,
  27. 4: 1,
  28. 5: 1,
  29. 6: 1,
  30. 7: 1,
  31. 8: 1
  32. }
  33. with open("modules/databases/complaints.json","r") as f:
  34. complaints = json.load(f)
  35. if getpass.getuser() == "tedankara":
  36. # Path to frozen detection graph. This is the actual model that is used for the object detection.
  37. # List of the strings that is used to add correct label for each box.
  38. PATH_TO_LABELS = 'modules/trainedModels/crack_label_map.pbtxt'
  39. NUM_CLASSES = 8
  40. label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
  41. categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
  42. category_index = label_map_util.create_category_index(categories)
  43. def load_image_into_numpy_array(image):
  44. (im_width, im_height) = image.size
  45. return np.array(image.getdata()).reshape(
  46. (im_height, im_width, 3)).astype(np.uint8)
  47. def process_img(img_base64):
  48. if getpass.getuser() == "tedankara":
  49. url = 'https://127.0.0.1:5001/ai' # Set destination URL here
  50. post_fields = {'img': img_base64,"type":"damage"} # Set POST fields here
  51. request = Request(url, urlencode(post_fields).encode())
  52. img = load_image_into_numpy_array(Image.open(io.BytesIO(base64.b64decode(img_base64))))
  53. output_dict = json.loads(urlopen(request, context=context).read())
  54. print(output_dict)
  55. vis_util.visualize_boxes_and_labels_on_image_array(
  56. img,
  57. np.array(output_dict['detection_boxes']),
  58. output_dict['detection_classes'],
  59. output_dict['detection_scores'],
  60. category_index,
  61. instance_masks=output_dict.get('detection_masks'),
  62. use_normalized_coordinates=True,
  63. line_thickness=8,
  64. min_score_thresh=0.3
  65. )
  66. defects = []
  67. for index, i in enumerate(output_dict['detection_classes']):
  68. score = output_dict['detection_scores'][index]
  69. if score > 0.3:
  70. defects.append(i)
  71. priority = 0
  72. for i in defects:
  73. priority += score_dict[i]
  74. if priority > 10:
  75. priority = 10
  76. buffered = io.BytesIO()
  77. img = Image.fromarray(img, 'RGB')
  78. img.save(buffered, format="JPEG")
  79. img_str = base64.b64encode(buffered.getvalue())
  80. return img_str.decode("ascii"),priority,defects
  81. return img_base64, 7,["unprocessed"]
  82. class Complaint(Resource):
  83. def post(self):
  84. args = request.form.to_dict()
  85. complaint = args
  86. complaint["response"] = {"status":False}
  87. img_process,priority,tags = process_img(complaint["img"])
  88. complaint["img"] = img_process
  89. complaint["response"]["priority"] = str(priority)
  90. complaint["tags"] = list(map(str, tags))
  91. complaint["datetime"] = datetime.datetime.now().strftime('%b-%d-%I:%M %p-%G')
  92. try:
  93. complaints[complaint["id"]].append(complaint)
  94. except KeyError:
  95. complaints[complaint["id"]] = [complaint]
  96. del complaints[complaint["id"]][-1]["id"]
  97. with open('modules/databases/complaints.json', 'w') as complaints_file:
  98. json.dump(complaints, complaints_file, indent=2)
  99. class Complaints(Resource):
  100. def post(self):
  101. id = request.form["id"]
  102. return complaints[id]
  103. class ComplaintsUpdate(Resource):
  104. def get(self):
  105. args = request.args
  106. complaints[args.get("id")][int(args.get("index"))]["response"]["message"] = args.get("message")
  107. complaints[args["id"]][int(args["index"])]["response"]["status"] = True
  108. with open('modules/databases/complaints.json', 'w') as complaints_file:
  109. json.dump(complaints, complaints_file, indent=2)
  110. return