server.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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", use_gpu=False)
  32. @app.get("/ping")
  33. def ping():
  34. return "pong!"
  35. # @app.get("/")
  36. # def home(request: Request):
  37. # ''' Returns html jinja2 template render for home page form
  38. # '''
  39. #
  40. # return templates.TemplateResponse('home.html', {
  41. # "request": request,
  42. # })
  43. class IdCardInfo(BaseModel):
  44. image: str
  45. image_type: str
  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. if int(id_card.image_type) == 0:
  52. return _front(image, id_card.image_type)
  53. if int(id_card.image_type) == 1:
  54. return _back(image, id_card.image_type)
  55. def _back(image, image_type):
  56. raise Exception('not implemented yet')
  57. def _front(image, image_type: str):
  58. angle = detect_angle(image)
  59. print(angle)
  60. # 获取模型检测结果
  61. result = ocr.ocr(image, cls=True)
  62. print("------------------")
  63. print(result)
  64. if not result:
  65. return None
  66. scores = [line[1][1] for line in result]
  67. score = sum(scores) / len(scores)
  68. print("------------------")
  69. print(scores)
  70. print("------------------")
  71. sc = []
  72. for i in range(0, 6):
  73. sc.append(scores[i])
  74. sc.append(scores[i])
  75. sc.append(scores[i])
  76. sc.append(scores[i])
  77. # 将检测到的文字放到一个列表中
  78. txts = [line[1][0] for line in result]
  79. print("......................................")
  80. print(txts)
  81. print("......................................")
  82. # 将结果送入到后处理模型中
  83. postprocessing = IdCardStraight(txts)
  84. id_result = postprocessing.run()
  85. content = id_result['Data']['FrontResult']
  86. location_str = []
  87. location_str.append(content["Address"])
  88. print(location_str)
  89. df = cpca.transform(location_str)
  90. print(df)
  91. province = df.iloc[0, 0]
  92. city = df.iloc[0, 1]
  93. region = df.iloc[0, 2]
  94. detail = df.iloc[0, 3]
  95. print(f'pronvince: {province}, city: {city}, region: {region}, detail: {detail}')
  96. return {
  97. "confidence": score,
  98. "card_type": image_type,
  99. "orientation": angle // 90,
  100. "name": {'text': content['Name'], 'confidence': sc[0]},
  101. "id": {'text': content['IDNumber'], 'confidence': sc[1]},
  102. "ethnicity": {'text': content['Nationality'], 'confidence': sc[2]},
  103. "gender": {'text': content['Gender'], 'confidence': sc[3]},
  104. "birthday": {'text': content['year'], 'confidence': sc[4]},
  105. "address_province": {'text': province, 'confidence': sc[5]},
  106. "address_city": {'text': city, 'confidence': sc[6]},
  107. "address_region": {'text': region, 'confidence': sc[7]},
  108. "address_detail": {'text': detail, 'confidence': sc[8]},
  109. "expire_date": {'text': '', 'confidence': 0}
  110. }
  111. if __name__ == '__main__':
  112. import uvicorn
  113. import argparse
  114. parser = argparse.ArgumentParser()
  115. parser.add_argument('--host', default='0.0.0.0')
  116. parser.add_argument('--port', default=8080)
  117. opt = parser.parse_args()
  118. app_str = 'server:app' # make the app string equal to whatever the name of this file is
  119. uvicorn.run(app_str, host=opt.host, port=int(opt.port), reload=True)