doc_analyze_by_custom_model.py 4.83 KB
Newer Older
1
2
import time

赵小蒙's avatar
赵小蒙 committed
3
4
import fitz
import numpy as np
5
from loguru import logger
6

7
from magic_pdf.libs.config_reader import get_local_models_dir, get_device, get_table_recog_config
8
from magic_pdf.model.model_list import MODEL
9
import magic_pdf.model as model_config
赵小蒙's avatar
赵小蒙 committed
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26


def dict_compare(d1, d2):
    return d1.items() == d2.items()


def remove_duplicates_dicts(lst):
    unique_dicts = []
    for dict_item in lst:
        if not any(
                dict_compare(dict_item, existing_dict) for existing_dict in unique_dicts
        ):
            unique_dicts.append(dict_item)
    return unique_dicts


def load_images_from_pdf(pdf_bytes: bytes, dpi=200) -> list:
27
28
29
    try:
        from PIL import Image
    except ImportError:
赵小蒙's avatar
update:  
赵小蒙 committed
30
31
32
        logger.error("Pillow not installed, please install by pip.")
        exit(1)

赵小蒙's avatar
赵小蒙 committed
33
34
35
36
37
38
39
    images = []
    with fitz.open("pdf", pdf_bytes) as doc:
        for index in range(0, doc.page_count):
            page = doc[index]
            mat = fitz.Matrix(dpi / 72, dpi / 72)
            pm = page.get_pixmap(matrix=mat, alpha=False)

40
41
            # If the width or height exceeds 9000 after scaling, do not scale further.
            if pm.width > 9000 or pm.height > 9000:
42
                pm = page.get_pixmap(matrix=fitz.Matrix(1, 1), alpha=False)
赵小蒙's avatar
赵小蒙 committed
43

赵小蒙's avatar
update:  
赵小蒙 committed
44
45
            img = Image.frombytes("RGB", (pm.width, pm.height), pm.samples)
            img = np.array(img)
赵小蒙's avatar
赵小蒙 committed
46
47
48
49
50
            img_dict = {"img": img, "width": pm.width, "height": pm.height}
            images.append(img_dict)
    return images


51
52
53
54
55
56
57
58
59
class ModelSingleton:
    _instance = None
    _models = {}

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

60
    def get_model(self, ocr: bool, show_log: bool, lang=None):
61
        key = (ocr, show_log, lang)
62
        if key not in self._models:
63
            self._models[key] = custom_model_init(ocr=ocr, show_log=show_log, lang=lang)
64
65
66
        return self._models[key]


67
def custom_model_init(ocr: bool = False, show_log: bool = False, lang=None):
68
69
70
    model = None

    if model_config.__model_mode__ == "lite":
71
72
        logger.warning("The Lite mode is provided for developers to conduct testing only, and the output quality is "
                       "not guaranteed to be reliable.")
73
74
75
76
        model = MODEL.Paddle
    elif model_config.__model_mode__ == "full":
        model = MODEL.PEK

77
    if model_config.__use_inside_model__:
78
        model_init_start = time.time()
79
80
        if model == MODEL.Paddle:
            from magic_pdf.model.pp_structure_v2 import CustomPaddleModel
81
            custom_model = CustomPaddleModel(ocr=ocr, show_log=show_log, lang=lang)
82
83
        elif model == MODEL.PEK:
            from magic_pdf.model.pdf_extract_kit import CustomPEKModel
84
85
86
            # 从配置文件读取model-dir和device
            local_models_dir = get_local_models_dir()
            device = get_device()
87
88
89
90
91
            table_config = get_table_recog_config()
            model_input = {"ocr": ocr,
                           "show_log": show_log,
                           "models_dir": local_models_dir,
                           "device": device,
92
93
94
                           "table_config": table_config,
                           "lang": lang,
                           }
95
            custom_model = CustomPEKModel(**model_input)
96
97
98
        else:
            logger.error("Not allow model_name!")
            exit(1)
99
100
        model_init_cost = time.time() - model_init_start
        logger.info(f"model init cost: {model_init_cost}")
101
102
103
104
    else:
        logger.error("use_inside_model is False, not allow to use inside model")
        exit(1)

105
106
107
    return custom_model


108
def doc_analyze(pdf_bytes: bytes, ocr: bool = False, show_log: bool = False,
109
                start_page_id=0, end_page_id=None, lang=None):
110
111

    model_manager = ModelSingleton()
112
    custom_model = model_manager.get_model(ocr, show_log, lang)
113

赵小蒙's avatar
赵小蒙 committed
114
115
    images = load_images_from_pdf(pdf_bytes)

116
117
    # end_page_id = end_page_id if end_page_id else len(images) - 1
    end_page_id = end_page_id if end_page_id is not None and end_page_id >= 0 else len(images) - 1
118
119
120
121
122

    if end_page_id > len(images) - 1:
        logger.warning("end_page_id is out of range, use images length")
        end_page_id = len(images) - 1

123
    model_json = []
124
    doc_analyze_start = time.time()
125

126
127
128
129
    for index, img_dict in enumerate(images):
        img = img_dict["img"]
        page_width = img_dict["width"]
        page_height = img_dict["height"]
130
131
132
133
        if start_page_id <= index <= end_page_id:
            result = custom_model(img)
        else:
            result = []
134
135
136
137
138
        page_info = {"page_no": index, "height": page_height, "width": page_width}
        page_dict = {"layout_dets": result, "page_info": page_info}
        model_json.append(page_dict)
    doc_analyze_cost = time.time() - doc_analyze_start
    logger.info(f"doc analyze cost: {doc_analyze_cost}")
赵小蒙's avatar
update:  
赵小蒙 committed
139

赵小蒙's avatar
赵小蒙 committed
140
    return model_json