folder_ocr_process.py 19 KB
import os
import re
import time
import shutil
import base64
import signal
import requests
import traceback
from PIL import Image
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 TIFFHandler:

    def __init__(self, path, img_save_path):
        self.path = path
        self.img_save_path = img_save_path
        self.img_path_list = []

    def extract_image(self):
        os.makedirs(self.img_save_path, exist_ok=True)
        tiff = Image.open(self.path)
        tiff.load()

        for i in range(tiff.n_frames):
            try:
                save_path = os.path.join(self.img_save_path, 'page_{0}.jpeg'.format(i))
                tiff.seek(i)
                tiff.save(save_path)
                self.img_path_list.append(save_path)
            except EOFError:
                break


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):
        # 类别:'0'身份证, '1'居住证
        license_data = ocr_data.get('data')
        if not license_data:
            return
        if isinstance(license_data, dict):
            license_data.pop('base64_img', '')

        # 保单
        if classify == consts.INSURANCE_CLASSIFY:
            product_result = ['', '', '']
            for product in license_data.get('result', {}).get('productList', []):
                name = product.get('name', {}).get('words', '')
                if name.find('机动车损失') != -1:
                    product_result[0] = product.get('coverage', {}).get('words', '')
                    product_result[2] = product.get('deductible_franchise', {}).get('words', '')
                elif name.find('第三者责任') != -1:
                    product_result[1] = product.get('coverage', {}).get('words', '')

            special_str = license_data.get('result', {}).get('1stBeneficiary', {}).get('words', '')
            special = '无'
            if special_str.find('宝马') != -1 or special_str.find('先锋国际融资租赁有限公司') != -1:
                special = '有'
            insurance_ocr_result = {
                '被保险人姓名': license_data.get('result', {}).get('insured', {}).get('name', {}).get('words', ''),
                '被保险人证件号码': license_data.get('result', {}).get('insured', {}).get('certiCode', {}).get('words', ''),
                '车架号': license_data.get('result', {}).get('vehicle', {}).get('VIN', {}).get('words', ''),
                '机动车损失保险金额': product_result[0],
                '机动车第三者责任保险金额': product_result[1],
                '机动车损失保险绝对免赔率/绝对免赔额': product_result[2],
                '保险费合计': license_data.get('result', {}).get('premiumSum', {}).get('words', ''),
                '保险起始日期': license_data.get('result', {}).get('startDate', {}).get('words', ''),
                '保险截止日期': license_data.get('result', {}).get('endDate', {}).get('words', ''),
                '保单章': license_data.get('result', {}).get('seal', {}).get('words', ''),
                '特别约定第一受益人': special,
            }
            license_summary.setdefault(classify, []).append(insurance_ocr_result)
        # DDA
        elif classify == consts.DDA_CLASSIFY:
            pro = ocr_data.get('confidence', 0)
            if pro < consts.DDA_PRO_MIN:
                return
            dda_ocr_result = {}
            for key, value in license_data.get('result', {}).items():
                dda_ocr_result[key] = value.get('words', '')
            dda_ocr_result[consts.DDA_PRO] = pro
            license_summary.setdefault(classify, []).append(dda_ocr_result)
        # 抵押登记豁免函
        elif classify == consts.HMH_CLASSIFY:
            hmh_ocr_result = {}
            for key, value in license_data.get('words_result', {}).items():
                hmh_ocr_result[key] = value.get('words', '')
            license_summary.setdefault(classify, []).append(hmh_ocr_result)
        # 二手车交易凭证
        elif classify == consts.JYPZ_CLASSIFY:
            jypz_ocr_result = {}
            for key, value in license_data.get('result', {}).items():
                jypz_ocr_result[key] = value.get('words', '')
            license_summary.setdefault(classify, []).append(jypz_ocr_result)
        # 车辆登记证 3/4页结果整合
        elif classify == consts.MVC_CLASSIFY:
            rebuild_data_dict = {}
            mvc_page = license_data.pop('page', 'VehicleRCI')
            mvc_res = license_data.pop('results', {})
            if mvc_page == 'VehicleRegArea':
                rebuild_data_dict['机动车登记证书编号'] = mvc_res.get('机动车登记证书编号', {}).get('words', '')
                for register_info in mvc_res.get('登记信息', []):
                    register_info.pop('register_type', None)
                    register_info.pop('register_type_name', None)
                    for cn_key, detail_dict in register_info.items():
                        rebuild_data_dict.setdefault(cn_key, []).append(
                            detail_dict.get('words', ''))
            else:
                for cn_key, detail_dict in mvc_res.items():
                    rebuild_data_dict[cn_key] = detail_dict.get('words', '')
            del mvc_res
            license_summary.setdefault(classify, []).append(rebuild_data_dict)

        # 身份证真伪
        elif classify == consts.IC_CLASSIFY:
            id_card_dict = {}
            card_type = license_data.get('type', '')
            is_ic = card_type.startswith('身份证')
            is_info_side = card_type.endswith('信息面')
            id_card_dict['类别'] = '0' if is_ic else '1'
            if is_ic:
                field_map = consts.IC_MAP_0 if is_info_side else consts.IC_MAP_1
            else:
                field_map = consts.RP_MAP_0 if is_info_side else consts.RP_MAP_1
            for write_field, search_field in field_map:
                id_card_dict[write_field] = license_data.get('words_result', {}).get(search_field, {}).get('words', '')
            if not is_info_side:
                start_time = license_data.get('words_result', {}).get('签发日期', {}).get('words', '')
                end_time = license_data.get('words_result', {}).get('失效日期', {}).get('words', '')
                id_card_dict['有效期限'] = '{0}-{1}'.format(start_time, end_time)

            id_card_dict[consts.IC_TURE_OR_FALSE] = consts.IC_RES_MAPPING.get(1)
            license_summary.setdefault(classify, []).append(id_card_dict)
        # 购车发票 & 二手车发票
        elif classify == consts.MVI_CLASSIFY or classify == consts.UCI_CLASSIFY:
            rebuild_data_dict = {}
            mvi_res = license_data.pop('result', {})
            for en_key, detail_dict in mvi_res.items():
                rebuild_data_dict[detail_dict.get('chinese_key', '')] = detail_dict.get('words', '')
            rebuild_data_dict['新旧版式'] = license_data.get('layout', '')
            license_summary.setdefault(classify, []).append(rebuild_data_dict)
        # 其他
        else:
            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 = {}

            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 ocr_data in data_list:
                                    # part_idx = part_idx + 1
                                    self.license1_process(ocr_data, license_summary, classify)

                wb = BSWorkbook(set(), 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}] [speed_time={2}]'.format(
                        self.log_base, img_path, speed_time))
                    return ocr_res
            else:
                self.folder_log.warn('{0} [ocr failed] [img_path={1}]'.format(self.log_base, img_path))
                
    def images_process(self, img_path_list, classify, excel_path):
        all_res = {}
        for img_path in 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)

    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()))
                raise e
            else:
                self.images_process(pdf_handler.img_path_list, classify, excel_path)
                shutil.move(path, pdf_save_path)

    def tif_process(self, name, path, classify, img_output_dir, wb_output_dir, tiff_output_dir):
        if os.path.exists(path):
            try:
                img_save_path, excel_path, tiff_save_path = self.get_path(name, img_output_dir, wb_output_dir, tiff_output_dir)
                self.folder_log.info('{0} [tiff to img start] [path={1}]'.format(self.log_base, path))
                tiff_handler = TIFFHandler(path, img_save_path)
                tiff_handler.extract_image()
                self.folder_log.info('{0} [tiff to img end] [path={1}]'.format(self.log_base, path))
            except Exception as e:
                self.folder_log.error('{0} [tiff to img error] [path={1}] [error={2}]'.format(
                    self.log_base, path, traceback.format_exc()))
                raise e
            else:
                self.images_process(tiff_handler.img_path_list, classify, excel_path)
                shutil.move(path, tiff_save_path)

    def img_process(self, name, path, classify, wb_output_dir, img_output_dir, pdf_output_dir):
        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:
            ocr_res = self.ocr_process(path, classify)
            all_res = {path: ocr_res}
            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')
        tiff_output_dir = os.path.join(output_dir, 'tiff')
        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(tiff_output_dir, exist_ok=True)
        os.makedirs(failed_output_dir, exist_ok=True)
        os_error_filename_set = set()
        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 and len(os_error_filename_set) == 0:
                self.folder_log.info('{0} [input dir empty] [input_dir={1}]'.format(self.log_base, input_dir))
                time.sleep(self.sleep_time)
                continue
            all_file_set = set(list_dir)
            true_file_set = all_file_set - os_error_filename_set
            if len(true_file_set) == 0 and len(os_error_filename_set) > 0:
                true_file_set.add(os_error_filename_set.pop())
            for name in true_file_set:
                path = os.path.join(input_dir, name)

                try:
                    if not os.path.exists(path):
                        self.folder_log.info('{0} [path is not exists] [path={1}]'.format(self.log_base, path))
                        continue
                    elif os.path.isfile(path):
                        self.folder_log.info('{0} [file start] [path={1}]'.format(self.log_base, path))
                        if name.endswith('.pdf') or name.endswith('.PDF'):
                            self.pdf_process(name, path, classify, img_output_dir, wb_output_dir, pdf_output_dir)
                        elif name.endswith('.tif') or name.endswith('.TIF') or name.endswith('.tiff') or \
                                name.endswith('.TIFF'):
                            self.tif_process(name, path, classify, img_output_dir, wb_output_dir, tiff_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, path))
                        failed_path = os.path.join(failed_output_dir, '{0}_{1}'.format(time.time(), name))
                        shutil.move(path, failed_path)
                except OSError:
                    os_error_filename_set.add(name)
                    self.folder_log.error('{0} [os error] [path={1}] [error={2}]'.format(
                        self.log_base, path, traceback.format_exc()))
                except Exception as e:
                    try:
                        self.folder_log.error('{0} [file error] [path={1}] [error={2}]'.format(self.log_base, path,
                                                                                               traceback.format_exc()))
                        failed_path = os.path.join(failed_output_dir, '{0}_{1}'.format(time.time(), name))
                        shutil.move(path, failed_path)
                    except Exception as e:
                        os_error_filename_set.add(name)
                        self.folder_log.error('{0} [file move error] [path={1}] [error={2}]'.format(
                            self.log_base, path, traceback.format_exc()))

    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))