folder_ocr_process.py
15.1 KB
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
import os
import re
import time
import shutil
import base64
import signal
import requests
import traceback
from datetime import datetime
from django.core.management import BaseCommand
from multiprocessing import Process
from settings import conf
from common.mixins import LoggerMixin
from common.tools.pdf_to_img import PDFHandler
from apps.doc import consts
from apps.doc.exceptions import OCR1Exception, OCR4Exception
from apps.doc.ocr.wb import BSWorkbook
class Command(BaseCommand, LoggerMixin):
def __init__(self):
super().__init__()
self.log_base = '[folder ocr process]'
# 处理文件开关
self.switch = True
# 睡眠时间
self.sleep_time = float(conf.SLEEP_SECOND_FOLDER)
# input folder
self.input_dirs = conf.get_namespace('INPUT_DIR_')
# ocr相关
self.ocr_url = conf.OCR_URL_FOLDER
self.ocr_url_4 = conf.IC_URL
# 优雅退出信号:15
signal.signal(signal.SIGTERM, self.signal_handler)
def signal_handler(self, sig, frame):
self.switch = False # 停止处理文件
def license1_process(self, ocr_data, license_summary, classify, res_list, pno, ino, part_idx, img_path):
# 类别:'0'身份证, '1'居住证
license_data = ocr_data.get('data', [])
if not license_data:
res_list.append((pno, ino, part_idx, consts.RES_SUCCESS_EMPTY))
return
res_list.append((pno, ino, part_idx, consts.RES_SUCCESS))
if classify == consts.MVC_CLASSIFY: # 车辆登记证 3/4页结果整合
for mvc_dict in license_data:
try:
mvc_page = mvc_dict.pop('page')
except Exception as e:
pass
else:
if mvc_page == 'VehicleRegArea':
mvc_dict['姓名/名称'] = []
mvc_dict['身份证明名称/号码'] = []
mvc_dict['转移登记日期'] = []
mvc_res = mvc_dict.pop('results', {})
for register_info in mvc_res.get('register_info', []):
if register_info.get('register_type', 0) == 2:
mvc_dict['姓名/名称'].append(
register_info.get('details', {}).get('name', {}).get('words', ''))
mvc_dict['身份证明名称/号码'].append(
register_info.get('details', {}).get('idno', {}).get('words', ''))
mvc_dict['转移登记日期'].append(
register_info.get('details', {}).get('date', {}).get('words', ''))
elif register_info.get('register_type', 0) == 0:
mvc_dict['抵押权人姓名/名称'].append(
register_info.get('details', {}).get('name', {}).get('words', ''))
mvc_dict['抵押身份证明名称/号码'].append(
register_info.get('details', {}).get('idno', {}).get('words', ''))
mvc_dict['抵押登记日期'].append(
register_info.get('details', {}).get('date', {}).get('words', ''))
elif register_info.get('register_type', 0) == 1:
mvc_dict['解除抵押日期'].append(
register_info.get('details', {}).get('date', {}).get('words', ''))
del mvc_res
if classify == consts.IC_CLASSIFY:
for id_card_dict in license_data:
try:
base64_img = id_card_dict.pop('base64_img')
except Exception as e:
continue
else:
card_type = -1
json_data_4 = {
'mode': 1,
'user_info': {
'image_content': base64_img,
},
'options': {
'distinguish_type': 1,
'auto_rotate': True,
},
}
for times in range(consts.RETRY_TIMES):
try:
start_time = time.time()
ocr_4_response = requests.post(self.ocr_url_4, json=json_data_4)
if ocr_4_response.status_code != 200:
raise OCR4Exception('ocr_4 status code: {0}'.format(ocr_4_response.status_code))
except Exception as e:
self.folder_log.warn(
'{0} [ocr_4 failed] [times={1}] [img_path={2}] [error={3}]'.format(
self.log_base, times, img_path, traceback.format_exc()))
else:
ocr_4_res = ocr_4_response.json()
end_time = time.time()
speed_time = int(end_time - start_time)
if ocr_4_res.get('code') == 0 and ocr_4_res.get('result', {}).get('rtn') == 0:
card_type = ocr_4_res.get('result', {}).get(
'idcard_distinguish_result', {}).get('result', -1)
self.folder_log.info(
'{0} [ocr_4 success] [img_path={1}] [speed_time={2}]'.format(
self.log_base, img_path, speed_time))
break
else:
self.folder_log.warn(
'{0} [ocr_4 failed] [img_path={1}]'.format(self.log_base, img_path))
id_card_dict[consts.IC_TURE_OR_FALSE] = consts.IC_RES_MAPPING.get(card_type)
license_summary.setdefault(classify, []).extend(license_data)
@staticmethod
def parse_img_path(img_path):
# 'page_{0}_img_{1}.{2}'.format(pno, img_index, ext)
img_name, _ = os.path.splitext(os.path.basename(img_path))
if re.match(r'page_\d+_img_\d+', img_name):
part_list = img_name.split('_')
return img_name, int(part_list[1])+1, int(part_list[3])+1
else:
return img_name, 1, 1
@staticmethod
def get_path(name, img_output_dir, wb_output_dir, pdf_output_dir):
time_stamp = datetime.now().strftime('%Y-%m-%d_%H:%M:%S')
new_name = '{0}_{1}'.format(time_stamp, name)
img_save_path = os.path.join(img_output_dir, new_name)
pdf_save_path = os.path.join(pdf_output_dir, new_name)
excel_name = '{0}.xlsx'.format(os.path.splitext(new_name)[0])
excel_path = os.path.join(wb_output_dir, excel_name)
return img_save_path, excel_path, pdf_save_path
def res_process(self, all_res, classify, excel_path):
try:
license_summary = {}
res_list = []
if not all_res:
return
else:
for img_path, ocr_res in all_res.items():
img_name, pno, ino = self.parse_img_path(img_path)
part_idx = 1
if isinstance(ocr_res, dict):
if ocr_res.get('code') == 1:
data_list = ocr_res.get('data', [])
if isinstance(data_list, list):
for part_idx, ocr_data in enumerate(data_list):
part_idx = part_idx + 1
self.license1_process(ocr_data, license_summary, classify,
res_list, pno, ino, part_idx, img_path)
else:
res_list.append((pno, ino, part_idx, consts.RES_FAILED_3))
else:
res_list.append((pno, ino, part_idx, consts.RES_FAILED))
else:
res_list.append((pno, ino, part_idx, consts.RES_FAILED))
wb = BSWorkbook(set(), set(), set(), set())
wb.simple_license_rebuild(license_summary, consts.DOC_SCHEME_LIST[0])
wb.remove_base_sheet()
wb.save(excel_path)
except Exception as e:
self.folder_log.error('{0} [wb build error] [path={1}] [error={2}]'.format(
self.log_base, excel_path, traceback.format_exc()))
def ocr_process(self, img_path, classify):
if os.path.exists(img_path):
# TODO 图片验证
with open(img_path, 'rb') as f:
base64_data = base64.b64encode(f.read())
# 获取解码后的base64值
file_data = base64_data.decode()
json_data = {
"file": file_data,
"classify": classify
}
for times in range(consts.RETRY_TIMES):
try:
start_time = time.time()
ocr_response = requests.post(self.ocr_url, json=json_data)
if ocr_response.status_code != 200:
raise OCR1Exception('{0} ocr status code: {1}'.format(self.log_base, ocr_response.status_code))
except Exception as e:
self.folder_log.warn('{0} [ocr failed] [times={1}] [img_path={2}] [error={3}]'.format(
self.log_base, times, img_path, traceback.format_exc()))
else:
ocr_res = ocr_response.json()
end_time = time.time()
speed_time = int(end_time - start_time)
self.folder_log.info('{0} [ocr success] [img={1}] [res={2}] [speed_time={3}]'.format(
self.log_base, img_path, ocr_res, speed_time))
return ocr_res
else:
self.folder_log.warn('{0} [ocr failed] [img_path={1}]'.format(self.log_base, img_path))
def pdf_process(self, name, path, classify, img_output_dir, wb_output_dir, pdf_output_dir):
if os.path.exists(path):
try:
img_save_path, excel_path, pdf_save_path = self.get_path(name, img_output_dir, wb_output_dir, pdf_output_dir)
self.folder_log.info('{0} [pdf to img start] [path={1}]'.format(self.log_base, path))
pdf_handler = PDFHandler(path, img_save_path)
pdf_handler.extract_image()
self.folder_log.info('{0} [pdf to img end] [path={1}]'.format(self.log_base, path))
except Exception as e:
self.folder_log.error('{0} [pdf to img error] [path={1}] [error={2}]'.format(
self.log_base, path, traceback.format_exc()))
else:
all_res = {}
for img_path in pdf_handler.img_path_list:
ocr_res = self.ocr_process(img_path, classify)
all_res[img_path] = ocr_res
self.res_process(all_res, classify, excel_path)
shutil.move(path, pdf_save_path)
def img_process(self, name, path, classify, wb_output_dir, img_output_dir, pdf_output_dir):
ocr_res = self.ocr_process(path, classify)
all_res = {path: ocr_res}
try:
img_save_path, excel_path, _ = self.get_path(name, img_output_dir, wb_output_dir, pdf_output_dir)
except Exception as e:
self.folder_log.error('{0} [get path error] [path={1}] [error={2}]'.format(
self.log_base, path, traceback.format_exc()))
else:
self.res_process(all_res, classify, excel_path)
shutil.move(path, img_save_path)
def folder_process(self, input_dir, classify):
while not os.path.isdir(input_dir):
self.folder_log.info('{0} [input dir is not dir] [input_dir={1}]'.format(self.log_base, input_dir))
if self.switch:
time.sleep(self.sleep_time)
continue
else:
return
output_dir = os.path.join(os.path.dirname(input_dir), 'Output')
img_output_dir = os.path.join(output_dir, 'image')
wb_output_dir = os.path.join(output_dir, 'excel')
pdf_output_dir = os.path.join(output_dir, 'pdf')
failed_output_dir = os.path.join(output_dir, 'failed')
os.makedirs(output_dir, exist_ok=True)
os.makedirs(img_output_dir, exist_ok=True)
os.makedirs(wb_output_dir, exist_ok=True)
os.makedirs(pdf_output_dir, exist_ok=True)
os.makedirs(failed_output_dir, exist_ok=True)
while self.switch:
if not os.path.isdir(input_dir):
self.folder_log.info('{0} [input dir is not dir] [input_dir={1}]'.format(self.log_base, input_dir))
time.sleep(self.sleep_time)
continue
# 1. 从input dir获取pdf or image
list_dir = os.listdir(input_dir)
if not list_dir:
self.folder_log.info('{0} [input dir empty] [input_dir={1}]'.format(self.log_base, input_dir))
time.sleep(self.sleep_time)
continue
for name in list_dir:
try:
path = os.path.join(input_dir, name)
if os.path.isfile(path):
self.folder_log.info('{0} [file start] [path={1}]'.format(self.log_base, path))
if name.endswith('.pdf'):
self.pdf_process(name, path, classify, img_output_dir, wb_output_dir, pdf_output_dir)
else:
self.img_process(name, path, classify, wb_output_dir, img_output_dir, pdf_output_dir)
self.folder_log.info('{0} [file end] [path={1}]'.format(self.log_base, path))
else:
self.folder_log.info('{0} [path is dir] [path={1}]'.format(self.log_base, input_dir))
shutil.move(path, failed_output_dir)
except Exception as e:
try:
path = os.path.join(input_dir, name)
self.folder_log.error('{0} [file error] [path={1}] [error={2}]'.format(self.log_base, path,
traceback.format_exc()))
shutil.move(path, failed_output_dir)
continue
except Exception as e:
self.folder_log.error('{0} [file error] [error={1}]'.format(
self.log_base, traceback.format_exc()))
continue
def handle(self, *args, **kwargs):
process_list = []
for classify_idx, input_dir in self.input_dirs.items():
classify = int(classify_idx.split('_')[0])
process = Process(target=self.folder_process, args=(input_dir, classify))
process_list.append(process)
for p in process_list:
p.start()
for p in process_list:
p.join()
self.folder_log.info('{0} [stop safely]'.format(self.log_base))