server.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. from fastapi import FastAPI, Request
  2. from fastapi.middleware.cors import CORSMiddleware
  3. from pydantic import BaseModel
  4. from paddleocr import PaddleOCR
  5. from core.direction import AngleDetector
  6. from sx_utils.sximage import *
  7. from sx_utils.sxtime import sxtimeit
  8. from sx_utils.sxweb import web_try
  9. from core.ocr import BusinessLicenseOcr
  10. import os
  11. app = FastAPI()
  12. origins = ["*"]
  13. # CORS 跨源资源共享
  14. app.add_middleware(
  15. CORSMiddleware,
  16. allow_origins=origins,
  17. allow_credentials=True,
  18. allow_methods=["*"],
  19. allow_headers=["*"],
  20. )
  21. use_gpu = os.getenv('USE_CUDA') == 'gpu'
  22. print(f'use gpu: {use_gpu}')
  23. ocr = PaddleOCR(
  24. use_gpu=use_gpu,
  25. det_db_unclip_ratio=1.8,
  26. det_db_thresh=0.1,
  27. det_db_box_thresh=0.3,)
  28. # 初始化 角度检测器 对象
  29. ad = AngleDetector(ocr)
  30. # 初始化 ocr识别 对象
  31. m = BusinessLicenseOcr(ocr, ad)
  32. # Get 健康检查
  33. @app.get("/ping")
  34. def ping():
  35. return "pong!"
  36. # 解析传入的 json对象
  37. class BusinessLicenseInfo(BaseModel):
  38. image: str
  39. # Post 接口
  40. # 计算耗时
  41. # 异常处理
  42. @app.post("/ocr_system/business_license")
  43. @sxtimeit
  44. @web_try()
  45. # 传入=> base64码 -> np
  46. # 返回=> 检测到到结果 -> (conf, angle, parser, image_type)
  47. def blfe(request: Request, blfe: BusinessLicenseInfo):
  48. image = base64_to_np(blfe.image)
  49. return m.predict(image)
  50. if __name__ == '__main__':
  51. import uvicorn
  52. import argparse
  53. parser = argparse.ArgumentParser()
  54. parser.add_argument('--host', default='0.0.0.0')
  55. parser.add_argument('--port', default=8080)
  56. opt = parser.parse_args()
  57. app_str = 'server:app' # make the app string equal to whatever the name of this file is
  58. uvicorn.run(app_str, host=opt.host, port=int(opt.port), reload=True)