server.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 timeit
  8. from utils.web import web_try
  9. from core.ocr import IdCardOcr
  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(use_angle_cls=True,
  24. rec_model_dir='./modules/rec',
  25. det_model_dir='./modules/det',
  26. cls_model_dir='./modules/cls',
  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 = IdCardOcr(ocr, ad)
  38. # Get 健康检查
  39. @app.get("/ping")
  40. def ping():
  41. return "pong!"
  42. # 解析传入的 json对象
  43. class IdCardInfo(BaseModel):
  44. image: str
  45. image_type: str
  46. @app.post("/ocr_system/idcard")
  47. @timeit
  48. @web_try()
  49. def idcard(request: Request, id_card: IdCardInfo):
  50. image = base64_to_np(id_card.image)
  51. return m.predict(image, id_card.image_type)
  52. if __name__ == '__main__':
  53. import uvicorn
  54. import argparse
  55. parser = argparse.ArgumentParser()
  56. parser.add_argument('--host', default='0.0.0.0')
  57. parser.add_argument('--port', default=8080)
  58. opt = parser.parse_args()
  59. app_str = 'server:app' # make the app string equal to whatever the name of this file is
  60. uvicorn.run(app_str, host=opt.host, port=int(opt.port), reload=True)