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.

142 lines
4.6 KiB

  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
  8. import datetime
  9. if sys.platform == "win32":
  10. import tensorflow as tf
  11. import numpy as np
  12. import pickle
  13. from utils import label_map_util
  14. from utils import visualization_utils as vis_util
  15. app = Flask(__name__)
  16. api = Api(app)
  17. with open("modules/databases/complaints.json","r") as f:
  18. complaints = json.loads(f.read())
  19. complaints_file = open("modules/databases/complaints.json","w")
  20. complaints_file.write(json.dumps(complaints,indent=4))
  21. if sys.platform == "win32":
  22. # Path to frozen detection graph. This is the actual model that is used for the object detection.
  23. PATH_TO_CKPT = 'trainedModels/ssd_mobilenet_RoadDamageDetector.pb'
  24. # List of the strings that is used to add correct label for each box.
  25. PATH_TO_LABELS = 'trainedModels/crack_label_map.pbtxt'
  26. NUM_CLASSES = 8
  27. detection_graph = tf.Graph()
  28. with detection_graph.as_default():
  29. od_graph_def = tf.GraphDef()
  30. with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
  31. serialized_graph = fid.read()
  32. od_graph_def.ParseFromString(serialized_graph)
  33. tf.import_graph_def(od_graph_def, name='')
  34. label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
  35. categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
  36. category_index = label_map_util.create_category_index(categories)
  37. def load_image_into_numpy_array(image):
  38. (im_width, im_height) = image.size
  39. return np.array(image.getdata()).reshape(
  40. (im_height, im_width, 3)).astype(np.uint8)
  41. def process_img(img_base64):
  42. if sys.platform == "win32":
  43. img = Image.open(io.BytesIO(base64.b64decode(img_base64)))
  44. with detection_graph.as_default():
  45. with tf.Session(graph=detection_graph) as sess:
  46. # Definite input and output Tensors for detection_graph
  47. image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
  48. # Each box represents a part of the image where a particular object was detected.
  49. detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
  50. # Each score represent how level of confidence for each of the objects.
  51. # Score is shown on the result image, together with the class label.
  52. detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
  53. detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')
  54. num_detections = detection_graph.get_tensor_by_name('num_detections:0')
  55. # the array based representation of the image will be used later in order to prepare the
  56. # result image with boxes and labels on it.
  57. image_np = load_image_into_numpy_array(img)
  58. # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
  59. image_np_expanded = np.expand_dims(image_np, axis=0)
  60. # Actual detection.
  61. (boxes, scores, classes, num) = sess.run(
  62. [detection_boxes, detection_scores, detection_classes, num_detections],
  63. feed_dict={image_tensor: image_np_expanded})
  64. # Visualization of the results of a detection.
  65. vis_util.visualize_boxes_and_labels_on_image_array(
  66. image_np,
  67. np.squeeze(boxes),
  68. np.squeeze(classes).astype(np.int32),
  69. np.squeeze(scores),
  70. category_index,
  71. min_score_thresh=0.3,
  72. use_normalized_coordinates=True,
  73. line_thickness=8)
  74. output_dict = {'detection_classes': classes, 'detection_scores': scores}
  75. defects = []
  76. defect_scores = {}
  77. for i in output_dict['detection_classes']:
  78. cont = False
  79. index = np.where(output_dict['detection_classes'] == i)[0][0]
  80. score = output_dict['detection_scores'][index]
  81. if score > 0.3:
  82. defects.append(defect_scores[i])
  83. priority = sum(defects)//10
  84. if priority > 10:
  85. priority = 10
  86. return base64.b64encode(pickle.dumps(image_np)).decode('ascii'),priority
  87. return img_base64, 7
  88. class Complaint(Resource):
  89. def post(self):
  90. complaint = {}
  91. args = request.form.to_dict()
  92. complaint = args
  93. complaint["response"] = {"status":False}
  94. img_process,priority = process_img(complaint["img"])
  95. complaint["img"] = img_process
  96. complaint["response"]["priority"] = priority
  97. complaint["datetime"] = datetime.datetime.now().strftime('%b-%d-%I:%M %p-%G')
  98. try:
  99. complaints[complaint["id"]].append(complaint)
  100. except KeyError:
  101. complaints[complaint["id"]]= [complaint]
  102. del complaints[complaint["id"]][-1]["id"]
  103. complaints_file.seek(0)
  104. complaints_file.truncate()
  105. complaints_file.write(json.dumps(complaints,indent=4))
  106. class Complaints(Resource):
  107. def post(self):
  108. id = request.form["id"]
  109. return complaints[id]
  110. class ComplaintsAdmin(Resource):
  111. def get(self): return complaints