idc.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. import re
  2. from time import time
  3. from utils.util import *
  4. from utils.conf import MAX_CONTENT_LENGTH
  5. from flask import Blueprint, views, render_template, request
  6. idc = Blueprint("idc", __name__, url_prefix="/idc")
  7. __exclude = "中国CHINA *#★☆"
  8. __face_ptn = r"^姓名(?P<name>.+)性别(?P<gender>男|女)民族(?P<nation>.+)" \
  9. r"出生(?P<year>\d{4})年(?P<month>\d\d)月(?P<day>\d\d)日" \
  10. r"住址(?P<addr>.+)公民身份号码(?P<idn>\d{17}\d|x|X)$"
  11. __icon_ptn = r"^中华人民共和国居民身份证签发机关(?P<agent>.+)" \
  12. r"有效期限(?P<from_year>\d{4})\.(?P<from_month>\d{2})\.(?P<from_day>\d{2})" \
  13. r"[^\d]+(?P<to_year>\d{4})\.(?P<to_month>\d{2})\.(?P<to_day>\d{2})$"
  14. def get_face_info(data: "list[str]") -> "tuple[dict, str, bool]":
  15. res = {"name": "", "gender": "", "nation": "", "birth": {"year": "", "month": "", "day": ""}, "addr": "", "idn": ""}
  16. if len(data) < 5: # 最少 5 个识别结果
  17. return res, "请使用正确的身份证人像面照片", False
  18. str_all = "".join([item for item in data if not str_include(__exclude, item)])
  19. if match := re.match(__face_ptn, str_all):
  20. res["name"] = match.group("name")
  21. res["gender"] = match.group("gender")
  22. res["nation"] = match.group("nation")
  23. res["birth"] = {
  24. "year": match.group("year"),
  25. "month": match.group("month"),
  26. "day": match.group("day")
  27. }
  28. res["addr"] = match.group("addr")
  29. res["idn"] = match.group("idn")
  30. return res, str_all, True
  31. return res, "识别失败,请重新选择", False
  32. def get_icon_info(data: "list[str]"):
  33. res = {"agent": "", "from": {"year": "", "month": "", "day": ""}, "to": {"year": "", "month": "", "day": ""}}
  34. if len(data) < 4: # 最少 4 个识别结果
  35. return res, "请使用正确的身份证国徽面照片", False
  36. str_all = "".join([item for item in data if not str_include(__exclude, item)])
  37. if match := re.match(__icon_ptn, str_all):
  38. res["agent"] = match.group("agent")
  39. res["from"] = {
  40. "year": match.group("from_year"),
  41. "month": match.group("from_month"),
  42. "day": match.group("from_day"),
  43. }
  44. res["to"] = {
  45. "year": match.group("to_year"),
  46. "month": match.group("to_month"),
  47. "day": match.group("to_day"),
  48. }
  49. return res, str_all, True
  50. return res, "识别失败,请重新选择", False
  51. class IdcView(views.MethodView):
  52. @staticmethod
  53. def get():
  54. return render_template("idc_index.html")
  55. @staticmethod
  56. def post():
  57. start = time()
  58. which = request.form.get("which")
  59. if which is not None:
  60. which = which.lower()
  61. if which not in ["face", "icon"]:
  62. return Response(f"not recognized arg <which>: '{which}'")
  63. pic = request.files.get("picture")
  64. if pic is None:
  65. return Response("empty body")
  66. ext = get_ext_name(pic.filename)
  67. if not is_image_ext(ext):
  68. return Response("文件类型错误")
  69. content = pic.read()
  70. if len(content) > MAX_CONTENT_LENGTH:
  71. return Response("文件过大,请重新选择")
  72. img = read_img(content)
  73. images = rot_img(img)
  74. rec = Engine.ocr_multi(images, cls=True, use_space=False)
  75. info, msg, sta, idx = {}, "识别失败,请重新选择", False, 0
  76. for idx, ocr_res in enumerate(rec):
  77. words = [it[0].replace(" ", "") for it in ocr_res]
  78. if which == "face":
  79. if not words or not words[0].startswith("姓名"):
  80. continue
  81. info, msg, sta = get_face_info(words)
  82. else:
  83. if not words or not words[0].startswith("中华"):
  84. continue
  85. info, msg, sta = get_icon_info(words)
  86. if sta:
  87. break
  88. info["duration"] = time() - start
  89. if sta:
  90. raw_path = f"static/images/{current_time()}_{rand_str()}.{ext}"
  91. save_img(raw_path, images[idx])
  92. return Response(data=info)
  93. return Response(msg, info)
  94. class IdcHtmlView(views.MethodView):
  95. @staticmethod
  96. def post():
  97. start = time()
  98. which = request.form.get("which")
  99. if which is not None:
  100. which = which.lower()
  101. if which not in ["face", "icon"]:
  102. return Response(f"not recognized arg <which>: '{which}'")
  103. pic = request.files.get("picture")
  104. if pic is None:
  105. return Response("empty body")
  106. ext = get_ext_name(pic.filename)
  107. if not is_image_ext(ext):
  108. return Response("文件类型错误")
  109. content = pic.read()
  110. if len(content) > MAX_CONTENT_LENGTH:
  111. return Response("文件过大,请重新选择")
  112. img = read_img(content)
  113. images = rot_img(img)
  114. rec = Engine.ocr_multi(images, cls=True, use_space=False)
  115. info, msg, sta, idx = {}, "识别失败,请重新选择", False, 0
  116. for idx, ocr_res in enumerate(rec):
  117. words = [it[0].replace(" ", "") for it in ocr_res]
  118. if which == "face":
  119. if not words or not words[0].startswith("姓名"):
  120. continue
  121. info, msg, sta = get_face_info(words)
  122. else:
  123. if not words or not words[0].startswith("中华"):
  124. continue
  125. info, msg, sta = get_icon_info(words)
  126. if sta:
  127. break
  128. file_path = f"static/images/{current_time()}_{rand_str()}.{ext}"
  129. save_img(file_path, images[idx])
  130. info["SUCCESS"] = str(sta).upper()
  131. info["MESSAGE"] = msg
  132. info["DURATION"] = time() - start # noqa
  133. return render_template("k-v_result.html", raw=file_path, data=info)
  134. idc.add_url_rule("/", view_func=IdcView.as_view("idc"))
  135. idc.add_url_rule("/html/", view_func=IdcHtmlView.as_view("idc-html"))