ocr_controller.py 20.9 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 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
import os
from flask import request, Blueprint,json
import random
import re
import time
import pymysql
from paddleocr import PaddleOCR, draw_ocr
from PIL import Image
import requests
import numpy as np

# 创建一个蓝图
ocr_classfication_bp  = Blueprint("ocr_classfication", __name__)


conn_dev = pymysql.connect(
    host="192.168.3.227",
    port=3306,
    user="dev_user",
    password="df234fl",
    database="glsx_car_service",
    charset="utf8",
)
# 得到一个可以执行SQL语句的光标对象
cursor_dev = conn_dev.cursor()

# load model
# Paddleocr目前支持中英文、英文、法语、德语、韩语、日语,可以通过修改 lang参数进行切换
# lang参数依次为`ch`, `en`, `french`, `german`, `korean`, `japan`
ocr = PaddleOCR(
    use_angle_cls=True,
    # use_angle_cls=False,
    lang="ch",
    # use_gpu=False,
    use_gpu=True,
    use_tensorrt=True,
    det_algorithm="DB",
    # det_algorithm="EAST",
    det_db_score_mode="slow",
    # use_space_char=False, #不可用
    det_model_dir="ch_ppocr_server_v4.0_det_infer/",
    cls_model_dir="ch_ppocr_mobile_v4.0_cls_infer/",
    rec_model_dir="ch_ppocr_server_v4.0_rec_infer/",
    det_db_thresh=0.1,
    det_db_box_thresh=0.1,
    det_db_unclip_ratio=2.0,
    max_batch_size=20,
    use_dilation=True,
    # rec_algorithm="SVTR_LCNet",
)

# 定义要执行的SQL语句
# SQL = """
#       select * from sys_order_file_ocr_sn sofon limit 5
# """
# # 执行SQL语句
# cursor_dev.execute(SQL)
#
# # 获取查询结果
# result = cursor_dev.fetchall()


def generate_random_filename():
    timestamp = int(time.time())  # 获取当前时间戳
    random_number = random.randint(1000, 9999)  # 生成一个随机数
    filename = f"file_{timestamp}_{random_number}"  # 创建文件名
    return filename


def get_extension(filename):
    parts = filename.split(".")
    extension = parts[-1]
    return extension


def get_project_root():
    # 获取当前脚本文件的路径
    current_file = os.path.abspath(__file__)
    # 获取当前项目的根目录
    project_root = os.path.dirname(os.path.dirname(current_file))
    print(project_root)
    return project_root


def flatten_list(nested_list):
    flattened_list = []
    for item in nested_list:
        if isinstance(item, list):
            flattened_list.extend(flatten_list(item))
        elif isinstance(item, tuple):
            for value in item:
                if type(value) in (int, float):
                    if value > 1.0:
                        flattened_list.append(value)
                else:
                    flattened_list.append(value)
        else:
            # flattened_list.append(item)
            pass
    return flattened_list


def validate_vin(item):
    pattern = r"^(?=.*[0-9A-HJ-NPR-Z])(?!(.*[IOQ]))([0-9A-HJ-NPR-Z]{17})$"
    # pattern 是匹配车牌号的正则表达式

    match = re.match(pattern, str(item))
    if match:
        return True
    else:
        return False


def extract_sn(string):
    string = re.sub(r"O", "0", string)
    string = re.sub(r"I", "1", string)
    pattern = r"\b(\d{10,11})\b"
    match = re.search(pattern, string)
    if match:
        sn = match.group()
        return sn
    else:
        return None

def extract_vin(string):
    string = re.sub(r"O", "0", string)
    string = re.sub(r"I", "1", string)
    pattern = r"(?=.*[0-9A-HJ-NPR-Z])(?!(.*[IOQ]))([0-9A-HJ-NPR-Z]{17})"
    # pattern = r"(?=.*[0-9A-HJ-NPR-Z])(?!(.*[IOQ]))([0-9A-HJ-NPR-Z\s\u4e00-\u9fa5]{17})"
    # pattern = r"[0-9A-HJ-NPR-Z]{17}"
    # pattern = r"^[A-HJ-NPR-Z\d]{17}$"
    match = re.search(pattern, string)
    if match:
        vin = match.group()
        pattern01 = r"^\d+$"
        match = re.match(pattern01, vin)
        # 如果全是数字 则不是车架号
        if bool(match):
            return None
        else:
            return vin
    else:
        return None

def flip_image_45(image):
    # 逆时针旋转45度
    print("逆时针旋转45度")
    # rotated_image = cv2.transpose(image)
    # rotated_image = cv2.flip(rotated_image, 0)
    rotated_image = image.rotate(45)
    return rotated_image


def flip_image_90(image):
    # 逆时针旋转90度
    print("逆时针旋转90度")
    # rotated_image = cv2.transpose(image)
    # rotated_image = cv2.flip(rotated_image, 0)
    rotated_image = image.rotate(90)
    return rotated_image


def flip_image_180(image):
    # 旋转180度
    print("逆时针旋转180度")
    rotated_image = image.rotate(180)
    return rotated_image


def handle_process(order_id, file_path, sns, vin):
    print("recognition handle_process:", order_id, file_path, sns, vin)

    # 删除数据库里的旧数据
    delete_sql1 = "DELETE FROM sys_order_ocr_sn_result WHERE order_id = {}".format(order_id)
    print(delete_sql1)
    cursor_dev.execute(delete_sql1)
    conn_dev.commit()
    delete_sql2 = "DELETE FROM sys_order_ocr_vin_result WHERE order_id = {}".format(order_id)
    print(delete_sql2)
    cursor_dev.execute(delete_sql2)
    conn_dev.commit()

    filename = generate_random_filename()
    network_img_path = file_path
    print("network_img_path", network_img_path)
    extension = get_extension(network_img_path)
    complete_filename = f"{filename}.{extension}"
    try:
        response = requests.get(network_img_path)
    except Exception as e:
        response = requests.get(network_img_path)
    path = os.path.join(
        get_project_root(), "Identify_sn", "train", "threecode", complete_filename
    )
    dirname = os.path.dirname(path)
    if not os.path.exists(dirname):
        os.makedirs(dirname)
    with open(path, "wb") as file:
        file.write(response.content)
    # urllib.request.urlretrieve(network_img_path, path)
    time.sleep(0.001)
    print("File downloaded successfully.")

    original_image = Image.open(path)

    if original_image.mode == "RGBA":
        original_image = original_image.convert("RGB")

    print(original_image.mode)

    # 放大图片
    scale_factor = 5  # 放大倍数
    # scaled_image = original_image.resize(
    #     (original_image.width * scale_factor, original_image.height * scale_factor)
    # )

    dst = original_image.resize(
        (original_image.width * scale_factor, original_image.height * scale_factor)
    )

    result = ocr.ocr(np.asarray(dst), cls=True)
    # result = ocr.ocr(image_path.replace("train", "validation"), cls=True)
    for line in result:
        print(line)
        # print(line[0][1][0])

    result_list = flatten_list(result)
    print("result_list", result_list)
    with open("./log01.txt", "a+", encoding="utf-8") as file:
        if result_list is not None:
            file.write(path + "----" + str(result_list) + "\n")
        else:
            file.write(path + "----" + "NULL" + "\n")

    # 使用正则表达式进行过滤 获取车架号
    sn_str = ""
    flag = True
    for item in result_list:
        print(item)
        sn_check = extract_sn(item)
        if sn_check is not None:
            flag = False
            sn_str = sn_check
            if sn_str:
                print(sn_str)
                # 定义要执行的SQL语句
                SQL01 = f"""
                    INSERT INTO sys_order_ocr_sn_result (order_id,file_id,db_sn,ocr_sn,create_time,update_time)
                    VALUES ({order_id},null,'{sns}','{sn_str}',sysdate(),sysddate())
                    """
                # 执行SQL语句
                print(SQL01)
                cursor_dev.execute(SQL01)
                conn_dev.commit()
    if flag:
        # 旋转45
        dst = flip_image_45(dst)
        result = ocr.ocr(np.asarray(dst), cls=True)
        # result = ocr.ocr(image_path.replace("train", "validation"), cls=True)
        for line in result:
            print(line)
            # print(line[0][1][0])

        result_list = flatten_list(result)
        print("result_list", result_list)
        with open("./log01.txt", "a+", encoding="utf-8") as file:
            if result_list is not None:
                file.write(path + "----" + str(result_list) + "\n")
            else:
                file.write(path + "----" + "NULL" + "\n")

        # 使用正则表达式进行过滤 获取车架号
        sn_str = ""
        for item in result_list:
            print(item)
            sn_check = extract_sn(item)
            if sn_check is not None:
                flag = False
                sn_str = sn_check
                if sn_str:
                    print(sn_str)
                    # 定义要执行的SQL语句
                    SQL01 = f"""
                        INSERT INTO sys_order_ocr_sn_result (order_id,file_id,db_sn,ocr_sn,create_time,update_time)
                        VALUES ({order_id},null,'{sns}','{sn_str}',sysdate(),sysddate())
                        """
                    # 执行SQL语句
                    print(SQL01)
                    cursor_dev.execute(SQL01)
                    conn_dev.commit()
    if flag:
        # 旋转90
        dst = flip_image_45(dst)
        result = ocr.ocr(np.asarray(dst), cls=True)
        # result = ocr.ocr(image_path.replace("train", "validation"), cls=True)
        for line in result:
            print(line)
            # print(line[0][1][0])

        result_list = flatten_list(result)
        print("result_list", result_list)
        with open("./log01.txt", "a+", encoding="utf-8") as file:
            if result_list is not None:
                file.write(path + "----" + str(result_list) + "\n")
            else:
                file.write(path + "----" + "NULL" + "\n")

        # 使用正则表达式进行过滤 获取车架号
        sn_str = ""
        for item in result_list:
            print(item)
            sn_check = extract_sn(item)
            if sn_check is not None:
                flag = False
                sn_str = sn_check
                if sn_str:
                    print(sn_str)
                    # 定义要执行的SQL语句
                    SQL01 = f"""
                        INSERT INTO sys_order_ocr_sn_result (order_id,file_id,db_sn,ocr_sn,create_time,update_time)
                        VALUES ({order_id},null,'{sns}','{sn_str}',sysdate(),sysddate())
                        """
                    # 执行SQL语句
                    print(SQL01)
                    cursor_dev.execute(SQL01)
                    conn_dev.commit()
    if flag:
        # 旋转180
        dst = flip_image_90(dst)
        result = ocr.ocr(np.asarray(dst), cls=True)
        # result = ocr.ocr(image_path.replace("train", "validation"), cls=True)
        for line in result:
            print(line)
            # print(line[0][1][0])

        result_list = flatten_list(result)
        print("result_list", result_list)
        with open("./log01.txt", "a+", encoding="utf-8") as file:
            if result_list is not None:
                file.write(path + "----" + str(result_list) + "\n")
            else:
                file.write(path + "----" + "NULL" + "\n")

        # 使用正则表达式进行过滤 获取车架号
        sn_str = ""
        for item in result_list:
            print(item)
            sn_check = extract_sn(item)
            if sn_check is not None:
                flag = False
                sn_str = sn_check
                if sn_str:
                    print(sn_str)
                    # 定义要执行的SQL语句
                    SQL01 = f"""
                         INSERT INTO sys_order_ocr_sn_result (order_id,file_id,db_sn,ocr_sn,create_time,update_time)
                         VALUES ({order_id},null,'{sns}','{sn_str}',sysdate(),sysddate())
                         """
                    # 执行SQL语句
                    print(SQL01)
                    cursor_dev.execute(SQL01)
                    conn_dev.commit()
    if flag:
        # 定义要执行的SQL语句
        SQL02 = f"""
            INSERT INTO sys_order_ocr_sn_result (order_id,file_id,db_sn,ocr_sn,create_time,update_time)
            VALUES ({order_id},null,'{sns}',null,sysdate(),sysddate())
            """
        # 执行SQL语句
        print(SQL02)
        cursor_dev.execute(SQL02)
        conn_dev.commit()


    print("==========================处理vin==================================")
    # 创建对比度增强器
    # enhancer = ImageEnhance.Contrast(original_image)

    # 增强对比度(将对比度增强为原来的2倍)
    # factor = 2.0
    # original_image = enhancer.enhance(factor)

    # 放大图片
    scale_factor = 3  # 放大倍数
    # scaled_image = original_image.resize(
    #     (original_image.width * scale_factor, original_image.height * scale_factor)
    # )

    dst = original_image.resize(
        (original_image.width * scale_factor, original_image.height * scale_factor)
    )

    result = ocr.ocr(np.asarray(dst), cls=True)
    # result = ocr.ocr(image_path.replace("train", "validation"), cls=True)
    for line in result:
        print(line)
        # print(line[0][1][0])

    result_list = flatten_list(result)
    print("result_list", result_list)
    with open("./log10.txt", "a+", encoding="utf-8") as file:
        if result_list is not None:
            file.write(path + "----" + str(result_list) + "\n")
        else:
            file.write(path + "----" + "NULL" + "\n")

    # 使用正则表达式进行过滤 获取车架号
    vin_str = ""
    for item in result_list:
        print(item)
        vin_check = extract_vin(item)
        if vin_check is not None:
            vin_str = vin_check
            break

    if vin_str:
        print(vin_str)
        # 定义要执行的SQL语句
        SQL01 = f"""
               INSERT INTO sys_order_ocr_vin_result (order_id,file_id,db_vin,ocr_vin,create_time,update_time)
               VALUES ({order_id},null,'{vin}','{vin_str}',sysdate(),sysdate())
               """
        # 执行SQL语句
        print(SQL01)
        cursor_dev.execute(SQL01)
        conn_dev.commit()
    else:
        # 旋转90度宠重新识别
        dst = flip_image_45(dst)
        result = ocr.ocr(np.asarray(dst), cls=True)
        # result = ocr.ocr(image_path.replace("train", "validation"), cls=True)
        for line in result:
            print(line)
            # print(line[0][1][0])
        result_list = flatten_list(result)
        print("result_list", result_list)
        with open("./log10.txt", "a+", encoding="utf-8") as file:
            if result_list is not None:
                file.write(path + "----" + str(result_list) + "\n")
            else:
                file.write(path + "----" + "NULL" + "\n")
        vin_str = ""
        for item in result_list:
            print(item)
            vin_check = extract_vin(item)
            if vin_check is not None:
                vin_str = vin_check
                break

        if vin_str:
            print(vin_str)
            # 定义要执行的SQL语句
            SQL01 = f"""
                   INSERT INTO sys_order_ocr_vin_result (order_id,file_id,db_vin,ocr_vin,create_time,update_time)
                   VALUES ({order_id},null,'{vin}','{vin_str}',sysdate(),sysdate())
                   """
            # 执行SQL语句
            print(SQL01)
            cursor_dev.execute(SQL01)
            conn_dev.commit()
        else:
            dst = flip_image_45(dst)
            result = ocr.ocr(np.asarray(dst), cls=True)
            # result = ocr.ocr(image_path.replace("train", "validation"), cls=True)
            for line in result:
                print(line)
                # print(line[0][1][0])
            result_list = flatten_list(result)
            print("result_list", result_list)
            with open("./log10.txt", "a+", encoding="utf-8") as file:
                if result_list is not None:
                    file.write(path + "----" + str(result_list) + "\n")
                else:
                    file.write(path + "----" + "NULL" + "\n")
            vin_str = ""
            for item in result_list:
                print(item)
                vin_check = extract_vin(item)
                if vin_check is not None:
                    vin_str = vin_check
                    break

            if vin_str:
                print(vin_str)
                # 定义要执行的SQL语句
                SQL01 = f"""
                       INSERT INTO sys_order_ocr_vin_result (order_id,file_id,db_vin,ocr_vin,create_time,update_time)
                       VALUES ({order_id},null,'{vin}','{vin_str}',sysdate(),sysdate())
                       """
                # 执行SQL语句
                print(SQL01)
                cursor_dev.execute(SQL01)
                conn_dev.commit()
            else:
                dst = flip_image_90(dst)
                result = ocr.ocr(np.asarray(dst), cls=True)
                # result = ocr.ocr(image_path.replace("train", "validation"), cls=True)
                for line in result:
                    print(line)
                    # print(line[0][1][0])
                result_list = flatten_list(result)
                print("result_list", result_list)
                with open("./log10.txt", "a+", encoding="utf-8") as file:
                    if result_list is not None:
                        file.write(path + "----" + str(result_list) + "\n")
                    else:
                        file.write(path + "----" + "NULL" + "\n")
                vin_str = ""
                for item in result_list:
                    print(item)
                    vin_check = extract_vin(item)
                    if vin_check is not None:
                        vin_str = vin_check
                        break

                if vin_str:
                    print(vin_str)
                    # 定义要执行的SQL语句
                    SQL01 = f"""
                           INSERT INTO sys_order_ocr_vin_result (order_id,file_id,db_vin,ocr_vin,create_time,update_time)
                           VALUES ({order_id},null,'{vin}','{vin_str}',sysdate(),sysdate())
                           """
                    # 执行SQL语句
                    print(SQL01)
                    cursor_dev.execute(SQL01)
                    conn_dev.commit()
                else:
                    # 如果识别不了 直接再放大图片
                    scale_factor = 5
                    dst = original_image.resize(
                        (
                            original_image.width * scale_factor,
                            original_image.height * scale_factor,
                        )
                    )
                    result = ocr.ocr(np.asarray(dst), cls=True)
                    # result = ocr.ocr(image_path.replace("train", "validation"), cls=True)
                    for line in result:
                        print(line)
                        # print(line[0][1][0])
                    result_list = flatten_list(result)
                    print("result_list", result_list)
                    with open("./log10.txt", "a+", encoding="utf-8") as file:
                        if result_list is not None:
                            file.write(path + "----" + str(result_list) + "\n")
                        else:
                            file.write(path + "----" + "NULL" + "\n")
                    vin_str = ""
                    for item in result_list:
                        print(item)
                        vin_check = extract_vin(item)
                        if vin_check is not None:
                            vin_str = vin_check
                            break

                    if vin_str:
                        print(vin_str)
                        # 定义要执行的SQL语句
                        SQL01 = f"""
                               INSERT INTO sys_order_ocr_vin_result (order_id,file_id,db_vin,ocr_vin,create_time,update_time)
                               VALUES ({order_id},null,'{vin}','{vin_str}',sysdate(),sysdate())
                               """
                        # 执行SQL语句
                        print(SQL01)
                        cursor_dev.execute(SQL01)
                        conn_dev.commit()
                    else:
                        # 定义要执行的SQL语句
                        SQL02 = f"""
                               INSERT INTO sys_order_ocr_vin_result (order_id,file_id,db_vin,ocr_vin,create_time,update_time)
                               VALUES ({order_id},null,'{vin}',null,sysdate(),sysdate())
                           """
                        # 执行SQL语句
                        print(SQL02)
                        cursor_dev.execute(SQL02)
                        conn_dev.commit()
    try:
        os.remove(path)
        print("文件删除成功")
    except FileNotFoundError:
        print("文件不存在")
    except PermissionError:
        print("权限不足,无法删除文件")


# 在蓝图中定义路由和视图函数
@ocr_classfication_bp.route("/recognition", methods=["POST"])
def identify():

    data = request.get_data()
    json_data = json.loads(data.decode("UTF-8"))

    order_id = json_data.get("orderId")
    file_path = json_data.get("filePath")
    sns = json_data.get("sns")
    vin = json_data.get("vin")

    handle_process(order_id,file_path,sns,vin)