server.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 utils.image import *
  7. from utils.time import sxtimeit
  8. from utils.web import web_try
  9. from core.ocr import CetOcr
  10. import os
  11. # 导入一些包
  12. app = FastAPI()
  13. origins = ["*"]
  14. # CORS 跨源资源共享
  15. app.add_middleware(
  16. CORSMiddleware,
  17. allow_origins=origins,
  18. allow_credentials=True,
  19. allow_methods=["*"],
  20. allow_headers=["*"],
  21. )
  22. use_gpu = os.getenv('USE_CUDA') == 'gpu'
  23. print(f'use gpu: {use_gpu}')
  24. ocr = PaddleOCR(use_angle_cls=True,
  25. rec_model_dir='server_model/rec/',
  26. det_model_dir='server_model/det/',
  27. ocr_version='PP-OCRv2',
  28. rec_algorithm='CRNN',
  29. use_gpu=use_gpu,
  30. det_db_unclip_ratio=2.5,
  31. det_db_thresh=0.1,
  32. det_db_box_thresh=0.3,
  33. warmup=True)
  34. # 初始化 角度检测器 对象
  35. ad = AngleDetector(ocr)
  36. # 初始化 身份证ocr识别 对象
  37. m = CetOcr(ocr, ad)
  38. # Get 健康检查
  39. @app.get("/ping")
  40. def ping():
  41. return "pong!"
  42. # 解析传入的 json对象
  43. class CetInfo(BaseModel):
  44. image: str
  45. @app.post("/ocr_system/cet")
  46. @sxtimeit
  47. @web_try()
  48. def cet(request: Request, cer: CetInfo):
  49. image = base64_to_np(cer.image)
  50. return m.predict(image)
  51. if __name__ == '__main__':
  52. import uvicorn
  53. import argparse
  54. parser = argparse.ArgumentParser()
  55. parser.add_argument('--host', default='0.0.0.0')
  56. parser.add_argument('--port', default=8080)
  57. opt = parser.parse_args()
  58. app_str = 'server:app' # make the app string equal to whatever the name of this file is
  59. uvicorn.run(app_str, host=opt.host, port=int(opt.port), reload=True)