server.py 8.5 KB

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