Spaces:
Sleeping
Sleeping
File size: 13,987 Bytes
e155984 8bf9be8 e155984 19cd81c e155984 0f37e88 e155984 0f37e88 19cd81c e155984 25f341a e155984 87b7701 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 | import os
import re
import json
import cv2
import time
import threading
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from paddleocr import PaddleOCR
from vietocr.tool.predictor import Predictor
from vietocr.tool.config import Cfg
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
ocr = None
detector = None
class Extractor:
def __init__(self):
self.config = Cfg.load_config_from_name('vgg_seq2seq')
self.config['weights'] = os.path.join(CURRENT_DIR, "seq2seqocr.pth")
self.config['cnn']['pretrained'] = False
self.config['device'] = 'cpu'
self.ocr = PaddleOCR(
lang='en',
use_gpu=False,
ocr_version='PP-OCRv3',
det_model_dir='./models/det/en_PP-OCRv3_det_infer/',
rec_model_dir='./models/rec/en_PP-OCRv3_rec_infer/',
cls_model_dir='./models/cls/ch_ppocr_mobile_v2.0_cls_infer/'
)
if (detector == None):
self.detector = Predictor(self.config)
else:
self.detector = detector
# result = {'ID_number':'',
# 'Name':'',
# 'Date_of_birth':'',
# 'Gender':'',
# 'Nationality':'',
# 'Place_of_origin':'',
# 'Place_of_residence':''}
####################################################################################################
def Detection(self, frame):
annotations = self.ocr.ocr(frame, rec=True, cls=False)
return annotations[0]
####################################################################################################
def WarpAndSave(self, frame, fileName, top_left, top_right, bottom_right, bottom_left):
w, h, cn = frame.shape
padding = 4.0
padding = int(padding * w / 640)
# All points are in format [cols, rows]
pt_A = top_left[0], top_left[1]
pt_B = bottom_left[0], bottom_left[1]
pt_C = bottom_right[0], bottom_right[1]
pt_D = top_right[0], top_right[1]
# Here, I have used L2 norm. You can use L1 also.
width_AD = np.sqrt(((pt_A[0] - pt_D[0]) ** 2) + ((pt_A[1] - pt_D[1]) ** 2))
width_BC = np.sqrt(((pt_B[0] - pt_C[0]) ** 2) + ((pt_B[1] - pt_C[1]) ** 2))
maxWidth = max(int(width_AD), int(width_BC))
height_AB = np.sqrt(((pt_A[0] - pt_B[0]) ** 2) + ((pt_A[1] - pt_B[1]) ** 2))
height_CD = np.sqrt(((pt_C[0] - pt_D[0]) ** 2) + ((pt_C[1] - pt_D[1]) ** 2))
maxHeight = max(int(height_AB), int(height_CD))
input_pts = np.float32([pt_A, pt_B, pt_C, pt_D])
output_pts = np.float32([[0, 0],
[0, maxHeight - 1],
[maxWidth - 1, maxHeight - 1],
[maxWidth - 1, 0]])
# Compute the perspective transform M
M = cv2.getPerspectiveTransform(input_pts, output_pts)
matWarped = cv2.warpPerspective(frame, M, (maxWidth, maxHeight), flags=cv2.INTER_LINEAR)
cv2.imwrite(fileName, matWarped)
return True
####################################################################################################
def WarpAndRec(self, frame, top_left, top_right, bottom_right, bottom_left):
w, h, cn = frame.shape
padding = 4.0
padding = int(padding * w / 640)
box = []
# All points are in format [cols, rows]
pt_A = top_left[0] - padding, top_left[1] - padding
pt_B = bottom_left[0] - padding, bottom_left[1] + padding
pt_C = bottom_right[0] + padding, bottom_right[1] + padding
pt_D = top_right[0] + padding, top_right[1] - padding
# Here, I have used L2 norm. You can use L1 also.
width_AD = np.sqrt(((pt_A[0] - pt_D[0]) ** 2) + ((pt_A[1] - pt_D[1]) ** 2))
width_BC = np.sqrt(((pt_B[0] - pt_C[0]) ** 2) + ((pt_B[1] - pt_C[1]) ** 2))
maxWidth = max(int(width_AD), int(width_BC))
height_AB = np.sqrt(((pt_A[0] - pt_B[0]) ** 2) + ((pt_A[1] - pt_B[1]) ** 2))
height_CD = np.sqrt(((pt_C[0] - pt_D[0]) ** 2) + ((pt_C[1] - pt_D[1]) ** 2))
maxHeight = max(int(height_AB), int(height_CD))
input_pts = np.float32([pt_A, pt_B, pt_C, pt_D])
output_pts = np.float32([[0, 0],
[0, maxHeight - 1],
[maxWidth - 1, maxHeight - 1],
[maxWidth - 1, 0]])
# Compute the perspective transform M
M = cv2.getPerspectiveTransform(input_pts, output_pts)
matWarped = cv2.warpPerspective(frame, M, (maxWidth, maxHeight), flags=cv2.INTER_LINEAR)
# cv2.imwrite(fileName, matWarped)
s = self.detector.predict(Image.fromarray(matWarped))
box.append(pt_A)
box.append(pt_D)
box.append(pt_C)
box.append(pt_B)
return [s, box]
####################################################################################################
def GetInformationAndSave(self, _results, _idnumber, _idnumberbox):
print("---------------------------------")
print(_results)
# string = '{"ID_number": "09219802508", "Name": "", "Date_of_birth": "", "Gender": "", "Nationality": "", "Place_of_origin": "", "Place_of_residence": "", "ID_number_box": [[208.0, 171.0], [495.0, 177.0], [495.0, 201.0], [208.0, 195.0]]}'
# result = json.loads(string)
result = {}
result['ID_number'] = _idnumber
result['Name'] = ''
result['Date_of_birth'] = ''
result['Date_of_issue'] = ''
result['Gender'] = ''
result['Nationality'] = ''
result['Place_of_origin'] = ''
result['Place_of_residence'] = ''
result['ID_number_box'] = _idnumberbox
regex_issue = r'[0-9][0-9]/[0-9][0-9]'
regex_dob = r'[0-9][0-9]/[0-9][0-9]'
regex_residence = r'[0-9][0-9]/[0-9][0-9]/|[0-9]{4,10}|Date|Demo|Dis|Dec|Dale|fer|ting|gical|ping|exp|ver|pate|cond|trị|đến|không|Không|Có|Pat|ter|ity'
for i, res in enumerate(_results):
s = res[0]
print(s)
if re.search(r'tên|name', s):
# result['ID_number'] = result[i+1].split(':|;|,|\\.|\s+')[-1].strip()
# ID_number = result[i+1] if re.search(r'[0-9][0-9][0-9]',(re.split(r':|[.]|\s+',result[i+1][0]))[-1].strip()) else (result[i+2] if re.search(r'[0-9][0-9][0-9]',result[i+2][0]) else result[i+3])
# result['ID_number'] = (re.split(r':|[.]|\s+',ID_number[0]))[-1].strip()
# result['ID_number_box'] = ID_number[1]
Name = _results[i + 1] if (not re.search(r'[0-9]', _results[i + 1][0])) else _results[i + 2]
result['Name'] = Name[0].title()
result['Name_box'] = Name[1] if Name[1] else []
if (result['Date_of_birth'] == ''):
DOB = _results[i - 2] if re.search(regex_dob, _results[i - 2][0]) else []
result['Date_of_birth'] = (re.split(r':|\s+', DOB[0]))[-1].strip() if DOB else ''
result['Date_of_birth_box'] = DOB[1] if DOB else []
continue
if re.search(r'month|year|date', s) and (not result['Date_of_issue']):
if re.search(regex_dob, s):
DOI = _results[i]
elif re.search(regex_dob, _results[i - 1][0]):
DOI = _results[i - 1]
elif re.search(regex_dob, _results[i + 1][0]):
DOI = _results[i + 1]
else:
DOI = []
result['Date_of_issue'] = (re.split(r':|\s+', DOI[0]))[-1].strip() if DOI else ''
result['Date_of_issue_box'] = DOI[1] if DOI else []
continue
if re.search(r'sinh|birth|bith', s) and (not result['Date_of_birth']):
if re.search(regex_dob, s):
DOB = _results[i]
elif re.search(regex_dob, _results[i - 1][0]):
DOB = _results[i - 1]
elif re.search(regex_dob, _results[i + 1][0]):
DOB = _results[i + 1]
else:
DOB = []
result['Date_of_birth'] = (re.split(r':|\s+', DOB[0]))[-1].strip() if DOB else ''
result['Date_of_birth_box'] = DOB[1] if DOB else []
if re.search(r"Việt Nam", _results[i + 1][0]):
result['Nationality'] = 'Việt Nam'
result['Nationality_box'] = _results[i + 1][1]
continue
if re.search(r'Giới|Sex', s):
Gender = _results[i]
result['Gender'] = 'Nữ' if re.search(r'Nữ|nữ', Gender[0]) else 'Nam'
result['Gender_box'] = Gender[1] if Gender[1] else []
# continue
if re.search(r'Quốc|tịch|Nat', s):
if (not re.search(r'ty|ing', re.split(r':|,|[.]|ty|tịch', s)[-1].strip()) and (
len(re.split(r':|,|[.]|ty|tịch', s)[-1].strip()) >= 3)):
Nationality = _results[i]
elif not re.search(r'[0-9][0-9]/[0-9][0-9]/', _results[i + 1][0]):
Nationality = _results[i + 1]
else:
Nationality = _results[i - 1]
result['Nationality'] = re.split(r':|-|,|[.]|ty|[0-9]|tịch', Nationality[0])[-1].strip().title()
result['Nationality_box'] = Nationality[1] if Nationality[1] else []
for s in re.split(r'\s+', result['Nationality']):
if len(s) < 3:
result['Nationality'] = re.split(s, result['Nationality'])[-1].strip().title()
if re.search(r'Nam', result['Nationality']):
result['Nationality'] = 'Việt Nam'
continue
if re.search(r'Quê|origin|ongin|ngin|orging', s):
PlaceOfOrigin = [_results[i], _results[i + 1]] if not re.search(r'[0-9]{4}', _results[i + 1][0]) else []
if PlaceOfOrigin:
if len(re.split(r':|;|of|ging|gin|ggong', PlaceOfOrigin[0][0])[-1].strip()) > 2:
result['Place_of_origin'] = (
(re.split(r':|;|of|ging|gin|ggong', PlaceOfOrigin[0][0]))[-1].strip() + ', ' +
PlaceOfOrigin[1][0])
else:
result['Place_of_origin'] = PlaceOfOrigin[1][0]
result['Place_of_origin_box'] = PlaceOfOrigin[1][1]
continue
if re.search(r'Nơi|trú|residence', s):
vals2 = "" if (i + 2 > len(_results) - 1) else _results[i + 2] if len(_results[i + 2][0]) > 5 else \
_results[-1]
vals3 = "" if (i + 3 > len(_results) - 1) else _results[i + 3] if len(_results[i + 3][0]) > 5 else \
_results[-1]
if ((re.split(r':|;|residence|ence|end', s))[-1].strip() != ''):
if (vals2 != '' and not re.search(regex_residence, vals2[0])):
PlaceOfResidence = [_results[i], vals2]
elif (vals3 != '' and not re.search(regex_residence, vals3[0])):
PlaceOfResidence = [_results[i], vals3]
elif not re.search(regex_residence, _results[-1][0]):
PlaceOfResidence = [_results[i], _results[-1]]
else:
PlaceOfResidence = [_results[-1], []]
else:
PlaceOfResidence = [vals2, []] if (vals2 and not re.search(regex_residence, vals2[0])) else [
_results[-1], []]
print('PlaceOfResidence: {}'.format(PlaceOfResidence))
if PlaceOfResidence[1]:
result['Place_of_residence'] = re.split(r':|;|residence|sidencs|ence|end', PlaceOfResidence[0][0])[
-1].strip() + ' ' + str(PlaceOfResidence[1][0]).strip()
result['Place_of_residence_box'] = PlaceOfResidence[1][1]
else:
result['Place_of_residence'] = PlaceOfResidence[0][0]
result['Place_of_residence_box'] = PlaceOfResidence[0][1] if PlaceOfResidence else []
continue
elif (i == len(_results) - 1):
if result['Place_of_residence'] == '':
if not re.search(regex_residence, _results[-1][0]):
PlaceOfResidence = _results[-1]
elif not re.search(regex_residence, _results[-2][0]):
PlaceOfResidence = _results[-2]
else:
PlaceOfResidence = []
result['Place_of_residence'] = PlaceOfResidence[0] if PlaceOfResidence else ''
result['Place_of_residence_box'] = PlaceOfResidence[1] if PlaceOfResidence else []
if result['Gender'] == '':
result['Gender_box'] = []
if result['Nationality'] == '':
result['Nationality_box'] = []
if result['Name'] == '':
result['Name_box'] = []
if result['Date_of_birth'] == '':
result['Date_of_birth_box'] = []
if result['Place_of_origin'] == '':
result['Place_of_origin_box'] = []
else:
continue
# with open('extracted_infomation.json', 'w', encoding='utf-8') as f:
# f.write(json.dumps(result, indent=4, ensure_ascii=False))
# f.close()
return result |