server.py 2.0 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 sx_utils.sximage import *
  6. from sx_utils.sxtime import sxtimeit
  7. from sx_utils.sxweb import web_try
  8. from core.ocr import IdCardOcr
  9. app = FastAPI()
  10. origins = ["*"]
  11. app.add_middleware(
  12. CORSMiddleware,
  13. allow_origins=origins,
  14. allow_credentials=True,
  15. allow_methods=["*"],
  16. allow_headers=["*"],
  17. )
  18. # templates = Jinja2Templates(directory='templates')
  19. # 初始化ocr模型和后处理模型
  20. ocr = PaddleOCR(use_angle_cls=True,
  21. rec_model_dir="./idcard_rec_infer/",
  22. det_model_dir="./idcard_det_infer/",
  23. cls_model_dir="idcard_cls_infer",
  24. rec_algorithm='CRNN',
  25. ocr_version='PP-OCRv2',
  26. rec_char_dict_path="./ppocr_keys_v1.txt", lang="ch",
  27. use_gpu=True,
  28. warmup=True)
  29. @app.get("/ping")
  30. def ping():
  31. return "pong!"
  32. # @app.get("/")
  33. # def home(request: Request):
  34. # ''' Returns html jinja2 template render for home page form
  35. # '''
  36. #
  37. # return templates.TemplateResponse('home.html', {
  38. # "request": request,
  39. # })
  40. class IdCardInfo(BaseModel):
  41. image: str
  42. image_type: str
  43. # /ocr_system/bankcard 银行卡
  44. # /ocr_system/regbook 户口本
  45. # /ocr_system/schoolcert 学信网
  46. @app.post("/ocr_system/idcard")
  47. @sxtimeit
  48. @web_try()
  49. def idcard(request: Request, id_card: IdCardInfo):
  50. image = base64_to_np(id_card.image)
  51. m = IdCardOcr(ocr, image, id_card.image_type)
  52. return m.predict()
  53. if __name__ == '__main__':
  54. import uvicorn
  55. import argparse
  56. parser = argparse.ArgumentParser()
  57. parser.add_argument('--host', default='0.0.0.0')
  58. parser.add_argument('--port', default=8080)
  59. opt = parser.parse_args()
  60. app_str = 'server:app' # make the app string equal to whatever the name of this file is
  61. uvicorn.run(app_str, host=opt.host, port=int(opt.port), reload=True)