server.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. from fastapi import FastAPI, Request
  2. from fastapi.middleware.cors import CORSMiddleware
  3. from fastapi.templating import Jinja2Templates
  4. from pydantic import BaseModel
  5. from paddleocr import PaddleOCR
  6. from core.idcrad import IdCardStraight
  7. from core.direction import *
  8. from base64 import b64decode
  9. import numpy as np
  10. from sx_utils.sximage import *
  11. from sx_utils.sxtime import sxtimeit
  12. from sx_utils.sxweb import web_try
  13. import cpca
  14. app = FastAPI()
  15. origins = [
  16. "*"
  17. ]
  18. app.add_middleware(
  19. CORSMiddleware,
  20. allow_origins=origins,
  21. allow_credentials=True,
  22. allow_methods=["*"],
  23. allow_headers=["*"],
  24. )
  25. # templates = Jinja2Templates(directory='templates')
  26. # 初始化ocr模型和后处理模型
  27. ocr = PaddleOCR(use_angle_cls=True, rec_model_dir="./idcard_rec_infer/",
  28. det_model_dir="./idcard_det_infer/", cls_model_dir="idcard_cls_infer",
  29. rec_algorithm='CRNN',
  30. ocr_version='PP-OCRv2',
  31. rec_char_dict_path="./ppocr_keys_v1.txt", lang="ch",
  32. use_gpu=True,
  33. warmup=True)
  34. @app.get("/ping")
  35. def ping():
  36. return "pong!"
  37. # @app.get("/")
  38. # def home(request: Request):
  39. # ''' Returns html jinja2 template render for home page form
  40. # '''
  41. #
  42. # return templates.TemplateResponse('home.html', {
  43. # "request": request,
  44. # })
  45. class IdCardInfo(BaseModel):
  46. image: str
  47. image_type: str
  48. # /ocr_system/bankcard 银行卡
  49. # /ocr_system/regbook 户口本
  50. # /ocr_system/schoolcert 学信网
  51. @app.post("/ocr_system/idcard")
  52. @sxtimeit
  53. @web_try()
  54. def idcard(request: Request, id_card: IdCardInfo):
  55. image = base64_to_np(id_card.image)
  56. if int(id_card.image_type) == 0:
  57. return _front(image, id_card.image_type)
  58. elif int(id_card.image_type) == 1:
  59. return _back(image, id_card.image_type)
  60. else:
  61. raise Exception('not implemented yet')
  62. def _back(image, image_type):
  63. raise Exception('not implemented yet')
  64. def _front(image, image_type: str):
  65. angle = detect_angle(image)
  66. print(angle)
  67. # 获取模型检测结果
  68. result = ocr.ocr(image, cls=True)
  69. print("------------------")
  70. print(result)
  71. if not result:
  72. return None
  73. scores = [line[1][1] for line in result]
  74. score = sum(scores) / len(scores)
  75. print("------------------")
  76. print(scores)
  77. print("------------------")
  78. sc = []
  79. for i in range(0, 6):
  80. sc.append(scores[i])
  81. sc.append(scores[i])
  82. sc.append(scores[i])
  83. sc.append(scores[i])
  84. # 将检测到的文字放到一个列表中
  85. txts = [line[1][0] for line in result]
  86. print("......................................")
  87. print(txts)
  88. print("......................................")
  89. # 将结果送入到后处理模型中
  90. postprocessing = IdCardStraight(txts)
  91. id_result = postprocessing.run()
  92. content = id_result['Data']['FrontResult']
  93. location_str = []
  94. location_str.append(content["Address"])
  95. print(location_str)
  96. df = cpca.transform(location_str)
  97. print(df)
  98. province = df.iloc[0, 0]
  99. city = df.iloc[0, 1]
  100. region = df.iloc[0, 2]
  101. detail = df.iloc[0, 3]
  102. print(f'pronvince: {province}, city: {city}, region: {region}, detail: {detail}')
  103. return {
  104. "confidence": score,
  105. "card_type": image_type,
  106. "orientation": angle // 90,
  107. "name": {'text': content['Name'], 'confidence': sc[0]},
  108. "id": {'text': content['IDNumber'], 'confidence': sc[1]},
  109. "ethnicity": {'text': content['Nationality'], 'confidence': sc[2]},
  110. "gender": {'text': content['Gender'], 'confidence': sc[3]},
  111. "birthday": {'text': content['year'], 'confidence': sc[4]},
  112. "address_province": {'text': province, 'confidence': sc[5]},
  113. "address_city": {'text': city, 'confidence': sc[6]},
  114. "address_region": {'text': region, 'confidence': sc[7]},
  115. "address_detail": {'text': detail, 'confidence': sc[8]},
  116. "expire_date": {'text': '', 'confidence': 0}
  117. }
  118. if __name__ == '__main__':
  119. import uvicorn
  120. import argparse
  121. parser = argparse.ArgumentParser()
  122. parser.add_argument('--host', default='0.0.0.0')
  123. parser.add_argument('--port', default=8080)
  124. opt = parser.parse_args()
  125. app_str = 'server:app' # make the app string equal to whatever the name of this file is
  126. uvicorn.run(app_str, host=opt.host, port=int(opt.port), reload=True)