server.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. from fastapi import FastAPI, Request, Form, File, UploadFile
  2. from fastapi.templating import Jinja2Templates
  3. from pydantic import BaseModel
  4. from typing import List, Optional
  5. from sx_utils import web_try
  6. import cv2
  7. import numpy as np
  8. import torch
  9. import base64
  10. import random
  11. YOLO_DIR = '/workspace/yolov5'
  12. # WEIGHTS = '/data/yolov5/runs/train/yolov5x_layout_reuslt37/weights/best.pt'
  13. WEIGHTS = '/workspace/best.pt'
  14. device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
  15. print('====',torch.cuda.is_available())
  16. app = FastAPI()
  17. templates = Jinja2Templates(directory = 'templates')
  18. model_selection_options = ['ocr-layout']
  19. model_dict = {model_name: None for model_name in model_selection_options} #set up model cache
  20. colors = [tuple([random.randint(0, 255) for _ in range(3)]) for _ in range(100)] #for bbox plotting
  21. ##############################################
  22. #-------------GET Request Routes--------------
  23. ##############################################
  24. @app.get("/")
  25. def home(request: Request):
  26. ''' Returns html jinja2 template render for home page form
  27. '''
  28. return templates.TemplateResponse('home.html', {
  29. "request": request,
  30. "model_selection_options": model_selection_options,
  31. })
  32. @app.get("/drag_and_drop_detect")
  33. def drag_and_drop_detect(request: Request):
  34. ''' drag_and_drop_detect detect page. Uses a drag and drop
  35. file interface to upload files to the server, then renders
  36. the image + bboxes + labels on HTML canvas.
  37. '''
  38. return templates.TemplateResponse('drag_and_drop_detect.html',
  39. {"request": request,
  40. "model_selection_options": model_selection_options,
  41. })
  42. ##############################################
  43. #------------POST Request Routes--------------
  44. ##############################################
  45. @app.post("/")
  46. def detect_via_web_form(request: Request,
  47. file_list: List[UploadFile] = File(...),
  48. model_name: str = Form(...),
  49. img_size: int = Form(1824)):
  50. '''
  51. Requires an image file upload, model name (ex. yolov5s). Optional image size parameter (Default 1824).
  52. Intended for human (non-api) users.
  53. Returns: HTML template render showing bbox data and base64 encoded image
  54. '''
  55. #assume input validated properly if we got here
  56. if model_dict[model_name] is None:
  57. model_dict[model_name] = model = torch.hub.load(YOLO_DIR, 'custom', path=WEIGHTS, source='local').to(device)
  58. img_batch = [cv2.imdecode(np.fromstring(file.file.read(), np.uint8), cv2.IMREAD_COLOR)
  59. for file in file_list]
  60. #create a copy that corrects for cv2.imdecode generating BGR images instead of RGB
  61. #using cvtColor instead of [...,::-1] to keep array contiguous in RAM
  62. img_batch_rgb = [cv2.cvtColor(img, cv2.COLOR_BGR2RGB) for img in img_batch]
  63. results = model_dict[model_name](img_batch_rgb, size = img_size)
  64. json_results = results_to_json(results,model_dict[model_name])
  65. img_str_list = []
  66. #plot bboxes on the image
  67. for img, bbox_list in zip(img_batch, json_results):
  68. for bbox in bbox_list:
  69. label = f'{bbox["class_name"]} {bbox["confidence"]:.2f}'
  70. plot_one_box(bbox['bbox'], img, label=label,
  71. color=colors[int(bbox['class'])], line_thickness=3)
  72. img_str_list.append(base64EncodeImage(img))
  73. #escape the apostrophes in the json string representation
  74. encoded_json_results = str(json_results).replace("'",r"\'").replace('"',r'\"')
  75. return templates.TemplateResponse('show_results.html', {
  76. 'request': request,
  77. 'bbox_image_data_zipped': zip(img_str_list,json_results), #unzipped in jinja2 template
  78. 'bbox_data_str': encoded_json_results,
  79. })
  80. @app.post("/detect")
  81. @web_try()
  82. def detect_via_api(request: Request,
  83. file_list: List[UploadFile] = File(...),
  84. model_name: str = Form(...),
  85. img_size: Optional[int] = Form(1824),
  86. download_image: Optional[bool] = Form(False)):
  87. '''
  88. Requires an image file upload, model name (ex. yolov5s).
  89. Optional image size parameter (Default 1824)
  90. Optional download_image parameter that includes base64 encoded image(s) with bbox's drawn in the json response
  91. Returns: JSON results of running YOLOv5 on the uploaded image. If download_image parameter is True, images with
  92. bboxes drawn are base64 encoded and returned inside the json response.
  93. Intended for API usage.
  94. '''
  95. if model_dict[model_name] is None:
  96. model_dict[model_name] = model = torch.hub.load(YOLO_DIR, 'custom', path=WEIGHTS, source='local').to(device)
  97. img_batch = [cv2.imdecode(np.fromstring(file.file.read(), np.uint8), cv2.IMREAD_COLOR)
  98. for file in file_list]
  99. #create a copy that corrects for cv2.imdecode generating BGR images instead of RGB,
  100. #using cvtColor instead of [...,::-1] to keep array contiguous in RAM
  101. img_batch_rgb = [cv2.cvtColor(img, cv2.COLOR_BGR2RGB) for img in img_batch]
  102. results = model_dict[model_name](img_batch_rgb, size = img_size)
  103. json_results = results_to_json(results,model_dict[model_name])
  104. if download_image:
  105. for idx, (img, bbox_list) in enumerate(zip(img_batch, json_results)):
  106. for bbox in bbox_list:
  107. label = f'{bbox["class_name"]} {bbox["confidence"]:.2f}'
  108. plot_one_box(bbox['bbox'], img, label=label,
  109. color=colors[int(bbox['class'])], line_thickness=3)
  110. payload = {'image_base64':base64EncodeImage(img)}
  111. json_results[idx].append(payload)
  112. encoded_json_results = str(json_results).replace("'",r'"')
  113. return encoded_json_results
  114. ##############################################
  115. #--------------Helper Functions---------------
  116. ##############################################
  117. def results_to_json(results, model):
  118. ''' Converts yolo model output to json (list of list of dicts)'''
  119. return [
  120. [
  121. {
  122. "class": int(pred[5]),
  123. "class_name": model.model.names[int(pred[5])],
  124. "bbox": [int(x) for x in pred[:4].tolist()], #convert bbox results to int from float
  125. "confidence": float(pred[4]),
  126. }
  127. for pred in result
  128. ]
  129. for result in results.xyxy
  130. ]
  131. def plot_one_box(x, im, color=(128, 128, 128), label=None, line_thickness=3):
  132. # Directly copied from: https://github.com/ultralytics/yolov5/blob/cd540d8625bba8a05329ede3522046ee53eb349d/utils/plots.py
  133. # Plots one bounding box on image 'im' using OpenCV
  134. assert im.data.contiguous, 'Image not contiguous. Apply np.ascontiguousarray(im) to plot_on_box() input image.'
  135. tl = line_thickness or round(0.002 * (im.shape[0] + im.shape[1]) / 2) + 1 # line/font thickness
  136. c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))
  137. cv2.rectangle(im, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)
  138. if label:
  139. tf = max(tl - 1, 1) # font thickness
  140. t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
  141. c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3
  142. cv2.rectangle(im, c1, c2, color, -1, cv2.LINE_AA) # filled
  143. cv2.putText(im, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA)
  144. def base64EncodeImage(img):
  145. ''' Takes an input image and returns a base64 encoded string representation of that image (jpg format)'''
  146. _, im_arr = cv2.imencode('.jpg', img)
  147. im_b64 = base64.b64encode(im_arr.tobytes()).decode('utf-8')
  148. return im_b64
  149. if __name__ == '__main__':
  150. import uvicorn
  151. import argparse
  152. parser = argparse.ArgumentParser()
  153. parser.add_argument('--host', default = 'localhost')
  154. parser.add_argument('--port', default = 8080)
  155. parser.add_argument('--precache-models', action='store_true',
  156. help='Pre-cache all models in memory upon initialization, otherwise dynamically caches models')
  157. opt = parser.parse_args()
  158. # if opt.precache_models:
  159. # model_dict = {model_name: torch.hub.load('ultralytics/yolov5', model_name, pretrained=True)
  160. # for model_name in model_selection_options}
  161. app_str = 'server:app' #make the app string equal to whatever the name of this file is
  162. uvicorn.run(app_str, host= opt.host, port=int(opt.port), reload=True)