server.py 9.4 KB

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