server.py 9.3 KB

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