server.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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. import logging
  13. YOLO_DIR = '/workspace/yolov5'
  14. # WEIGHTS = '/data/yolov5/runs/train/yolov5x_layout_reuslt37/weights/best.pt'
  15. WEIGHTS = '/workspace/best.pt'
  16. logger = logging.getLogger('log')
  17. logger.setLevel(logging.DEBUG)
  18. # 调用模块时,如果错误引用,比如多次调用,每次会添加Handler,造成重复日志,这边每次都移除掉所有的handler,后面在重新添加,可以解决这类问题
  19. while logger.hasHandlers():
  20. for i in logger.handlers:
  21. logger.removeHandler(i)
  22. # file log 写入文件配置
  23. formatter = logging.Formatter('%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s') # 日志的格式
  24. fh = logging.FileHandler(r'/var/log/be.log', encoding='utf-8') # 日志文件路径文件名称,编码格式
  25. fh.setLevel(logging.DEBUG) # 日志打印级别
  26. fh.setFormatter(formatter)
  27. logger.addHandler(fh)
  28. # console log 控制台输出控制
  29. ch = logging.StreamHandler(sys.stdout)
  30. ch.setLevel(logging.DEBUG)
  31. ch.setFormatter(formatter)
  32. logger.addHandler(ch)
  33. device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
  34. bl = torch.cuda.is_available()
  35. logger.info(f'是否可使用GPU=======>{bl}')
  36. app = FastAPI()
  37. templates = Jinja2Templates(directory = 'templates')
  38. model_selection_options = ['ocr-layout']
  39. model_dict = {model_name: None for model_name in model_selection_options} #set up model cache
  40. colors = [tuple([random.randint(0, 255) for _ in range(3)]) for _ in range(100)] #for bbox plotting
  41. if model_dict['ocr-layout'] is None:
  42. model_dict['ocr-layout'] = model = torch.hub.load(YOLO_DIR, 'custom', path=WEIGHTS, source='local').to(device)
  43. logger.info("========>模型加载成功")
  44. ##############################################
  45. #-------------GET Request Routes--------------
  46. ##############################################
  47. @app.get("/")
  48. def home(request: Request):
  49. ''' Returns html jinja2 template render for home page form
  50. '''
  51. return templates.TemplateResponse('home.html', {
  52. "request": request,
  53. "model_selection_options": model_selection_options,
  54. })
  55. @app.get("/drag_and_drop_detect")
  56. def drag_and_drop_detect(request: Request):
  57. ''' drag_and_drop_detect detect page. Uses a drag and drop
  58. file interface to upload files to the server, then renders
  59. the image + bboxes + labels on HTML canvas.
  60. '''
  61. return templates.TemplateResponse('drag_and_drop_detect.html',
  62. {"request": request,
  63. "model_selection_options": model_selection_options,
  64. })
  65. ##############################################
  66. #------------POST Request Routes--------------
  67. ##############################################
  68. @app.post("/")
  69. def detect_via_web_form(request: Request,
  70. file_list: List[UploadFile] = File(...),
  71. model_name: str = Form(...),
  72. img_size: int = Form(1824)):
  73. '''
  74. Requires an image file upload, model name (ex. yolov5s). Optional image size parameter (Default 1824).
  75. Intended for human (non-api) users.
  76. Returns: HTML template render showing bbox data and base64 encoded image
  77. '''
  78. #assume input validated properly if we got here
  79. if model_dict[model_name] is None:
  80. model_dict[model_name] = model = torch.hub.load(YOLO_DIR, 'custom', path=WEIGHTS, source='local').to(device)
  81. img_batch = [cv2.imdecode(np.fromstring(file.file.read(), np.uint8), cv2.IMREAD_COLOR)
  82. for file in file_list]
  83. #create a copy that corrects for cv2.imdecode generating BGR images instead of RGB
  84. #using cvtColor instead of [...,::-1] to keep array contiguous in RAM
  85. img_batch_rgb = [cv2.cvtColor(img, cv2.COLOR_BGR2RGB) for img in img_batch]
  86. results = model_dict[model_name](img_batch_rgb, size = img_size)
  87. json_results = results_to_json(results,model_dict[model_name])
  88. img_str_list = []
  89. #plot bboxes on the image
  90. for img, bbox_list in zip(img_batch, json_results):
  91. for bbox in bbox_list:
  92. label = f'{bbox["class_name"]} {bbox["confidence"]:.2f}'
  93. plot_one_box(bbox['bbox'], img, label=label,
  94. color=colors[int(bbox['class'])], line_thickness=3)
  95. img_str_list.append(base64EncodeImage(img))
  96. #escape the apostrophes in the json string representation
  97. encoded_json_results = str(json_results).replace("'",r"\'").replace('"',r'\"')
  98. return templates.TemplateResponse('show_results.html', {
  99. 'request': request,
  100. 'bbox_image_data_zipped': zip(img_str_list,json_results), #unzipped in jinja2 template
  101. 'bbox_data_str': encoded_json_results,
  102. })
  103. @app.post("/detect")
  104. @web_try()
  105. def detect_via_api(request: Request,
  106. file_list: List[UploadFile] = File(...),
  107. model_name: str = Form(...),
  108. img_size: Optional[int] = Form(1824),
  109. download_image: Optional[bool] = Form(False)):
  110. '''
  111. Requires an image file upload, model name (ex. yolov5s).
  112. Optional image size parameter (Default 1824)
  113. Optional download_image parameter that includes base64 encoded image(s) with bbox's drawn in the json response
  114. Returns: JSON results of running YOLOv5 on the uploaded image. If download_image parameter is True, images with
  115. bboxes drawn are base64 encoded and returned inside the json response.
  116. Intended for API usage.
  117. '''
  118. img_batch = [cv2.imdecode(np.fromstring(file.file.read(), np.uint8), cv2.IMREAD_COLOR)
  119. for file in file_list]
  120. #create a copy that corrects for cv2.imdecode generating BGR images instead of RGB,
  121. #using cvtColor instead of [...,::-1] to keep array contiguous in RAM
  122. img_batch_rgb = [cv2.cvtColor(img, cv2.COLOR_BGR2RGB) for img in img_batch]
  123. results = model_dict[model_name](img_batch_rgb, size = img_size)
  124. json_results = results_to_json(results,model_dict[model_name])
  125. if download_image:
  126. for idx, (img, bbox_list) in enumerate(zip(img_batch, json_results)):
  127. for bbox in bbox_list:
  128. label = f'{bbox["class_name"]} {bbox["confidence"]:.2f}'
  129. plot_one_box(bbox['bbox'], img, label=label,
  130. color=colors[int(bbox['class'])], line_thickness=3)
  131. payload = {'image_base64':base64EncodeImage(img)}
  132. json_results[idx].append(payload)
  133. encoded_json_results = str(json_results).replace("'",r'"')
  134. return encoded_json_results
  135. ##############################################
  136. #--------------Helper Functions---------------
  137. ##############################################
  138. def results_to_json(results, model):
  139. ''' Converts yolo model output to json (list of list of dicts)'''
  140. return [
  141. [
  142. {
  143. "class": int(pred[5]),
  144. "class_name": model.model.names[int(pred[5])],
  145. "bbox": [int(x) for x in pred[:4].tolist()], #convert bbox results to int from float
  146. "confidence": float(pred[4]),
  147. }
  148. for pred in result
  149. ]
  150. for result in results.xyxy
  151. ]
  152. def plot_one_box(x, im, color=(128, 128, 128), label=None, line_thickness=3):
  153. # Directly copied from: https://github.com/ultralytics/yolov5/blob/cd540d8625bba8a05329ede3522046ee53eb349d/utils/plots.py
  154. # Plots one bounding box on image 'im' using OpenCV
  155. assert im.data.contiguous, 'Image not contiguous. Apply np.ascontiguousarray(im) to plot_on_box() input image.'
  156. tl = line_thickness or round(0.002 * (im.shape[0] + im.shape[1]) / 2) + 1 # line/font thickness
  157. c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))
  158. cv2.rectangle(im, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)
  159. if label:
  160. tf = max(tl - 1, 1) # font thickness
  161. t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
  162. c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3
  163. cv2.rectangle(im, c1, c2, color, -1, cv2.LINE_AA) # filled
  164. cv2.putText(im, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA)
  165. def base64EncodeImage(img):
  166. ''' Takes an input image and returns a base64 encoded string representation of that image (jpg format)'''
  167. _, im_arr = cv2.imencode('.jpg', img)
  168. im_b64 = base64.b64encode(im_arr.tobytes()).decode('utf-8')
  169. return im_b64
  170. if __name__ == '__main__':
  171. import uvicorn
  172. import argparse
  173. parser = argparse.ArgumentParser()
  174. parser.add_argument('--host', default = 'localhost')
  175. parser.add_argument('--port', default = 8080)
  176. parser.add_argument('--precache-models', action='store_true',
  177. help='Pre-cache all models in memory upon initialization, otherwise dynamically caches models')
  178. opt = parser.parse_args()
  179. # if opt.precache_models:
  180. # model_dict = {model_name: torch.hub.load('ultralytics/yolov5', model_name, pretrained=True)
  181. # for model_name in model_selection_options}
  182. app_str = 'server:app' #make the app string equal to whatever the name of this file is
  183. uvicorn.run(app_str, host= opt.host, port=int(opt.port), reload=True)