models.py 5.11 KB
Newer Older
icecraft's avatar
icecraft committed
1
2
3
4
5
import copy
import json
import os
from typing import Callable

icecraft's avatar
icecraft committed
6
from magic_pdf.config.constants import PARSE_TYPE_OCR, PARSE_TYPE_TXT
icecraft's avatar
icecraft committed
7
8
9
10
from magic_pdf.config.enums import SupportedPdfParseMethod
from magic_pdf.data.data_reader_writer import DataWriter
from magic_pdf.data.dataset import Dataset
from magic_pdf.libs.draw_bbox import draw_model_bbox
icecraft's avatar
icecraft committed
11
from magic_pdf.libs.version import __version__
icecraft's avatar
icecraft committed
12
from magic_pdf.operators.pipes import PipeResult
icecraft's avatar
icecraft committed
13
from magic_pdf.pdf_parse_union_core_v2 import pdf_parse_union
icecraft's avatar
icecraft committed
14

icecraft's avatar
icecraft committed
15

icecraft's avatar
icecraft committed
16
class InferenceResult:
icecraft's avatar
icecraft committed
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
    def __init__(self, inference_results: list, dataset: Dataset):
        """Initialized method.

        Args:
            inference_results (list): the inference result generated by model
            dataset (Dataset): the dataset related with model inference result
        """
        self._infer_res = inference_results
        self._dataset = dataset

    def draw_model(self, file_path: str) -> None:
        """Draw model inference result.

        Args:
            file_path (str): the output file path
        """
        dir_name = os.path.dirname(file_path)
        base_name = os.path.basename(file_path)
        if not os.path.exists(dir_name):
            os.makedirs(dir_name, exist_ok=True)
        draw_model_bbox(
            copy.deepcopy(self._infer_res), self._dataset, dir_name, base_name
        )

    def dump_model(self, writer: DataWriter, file_path: str):
        """Dump model inference result to file.

        Args:
            writer (DataWriter): writer handle
            file_path (str): the location of target file
        """
        writer.write_string(
            file_path, json.dumps(self._infer_res, ensure_ascii=False, indent=4)
        )

    def get_infer_res(self):
        """Get the inference result.

        Returns:
xu rui's avatar
xu rui committed
56
            list: the inference result generated by model
icecraft's avatar
icecraft committed
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
        """
        return self._infer_res

    def apply(self, proc: Callable, *args, **kwargs):
        """Apply callable method which.

        Args:
            proc (Callable): invoke proc as follows:
                proc(inference_result, *args, **kwargs)

        Returns:
            Any: return the result generated by proc
        """
        return proc(copy.deepcopy(self._infer_res), *args, **kwargs)

    def pipe_txt_mode(
        self,
        imageWriter: DataWriter,
        start_page_id=0,
        end_page_id=None,
        debug_mode=False,
        lang=None,
    ) -> PipeResult:
        """Post-proc the model inference result, Extract the text using the
        third library, such as `pymupdf`

        Args:
            imageWriter (DataWriter): the image writer handle
            start_page_id (int, optional): Defaults to 0. Let user select some pages He/She want to process
xu rui's avatar
xu rui committed
86
            end_page_id (int, optional):  Defaults to the last page index of dataset. Let user select some pages He/She want to process
icecraft's avatar
icecraft committed
87
            debug_mode (bool, optional): Defaults to False. will dump more log if enabled
xu rui's avatar
xu rui committed
88
            lang (str, optional): Defaults to None.
icecraft's avatar
icecraft committed
89
90
91
92
93
94
95

        Returns:
            PipeResult: the result
        """

        def proc(*args, **kwargs) -> PipeResult:
            res = pdf_parse_union(*args, **kwargs)
icecraft's avatar
icecraft committed
96
97
98
99
            res['_parse_type'] = PARSE_TYPE_TXT
            res['_version_name'] = __version__
            if 'lang' in kwargs and kwargs['lang'] is not None:
                res['lang'] = kwargs['lang']
icecraft's avatar
icecraft committed
100
101
            return PipeResult(res, self._dataset)

102
        res = self.apply(
icecraft's avatar
icecraft committed
103
104
105
106
107
108
109
110
111
            proc,
            self._dataset,
            imageWriter,
            SupportedPdfParseMethod.TXT,
            start_page_id=start_page_id,
            end_page_id=end_page_id,
            debug_mode=debug_mode,
            lang=lang,
        )
112
        return res
icecraft's avatar
icecraft committed
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127

    def pipe_ocr_mode(
        self,
        imageWriter: DataWriter,
        start_page_id=0,
        end_page_id=None,
        debug_mode=False,
        lang=None,
    ) -> PipeResult:
        """Post-proc the model inference result, Extract the text using `OCR`
        technical.

        Args:
            imageWriter (DataWriter): the image writer handle
            start_page_id (int, optional): Defaults to 0. Let user select some pages He/She want to process
xu rui's avatar
xu rui committed
128
            end_page_id (int, optional):  Defaults to the last page index of dataset. Let user select some pages He/She want to process
icecraft's avatar
icecraft committed
129
            debug_mode (bool, optional): Defaults to False. will dump more log if enabled
xu rui's avatar
xu rui committed
130
            lang (str, optional): Defaults to None.
icecraft's avatar
icecraft committed
131
132
133
134
135
136
137

        Returns:
            PipeResult: the result
        """

        def proc(*args, **kwargs) -> PipeResult:
            res = pdf_parse_union(*args, **kwargs)
icecraft's avatar
icecraft committed
138
139
140
141
            res['_parse_type'] = PARSE_TYPE_OCR
            res['_version_name'] = __version__
            if 'lang' in kwargs and kwargs['lang'] is not None:
                res['lang'] = kwargs['lang']
icecraft's avatar
icecraft committed
142
143
            return PipeResult(res, self._dataset)

144
        res = self.apply(
icecraft's avatar
icecraft committed
145
146
147
            proc,
            self._dataset,
            imageWriter,
icecraft's avatar
icecraft committed
148
            SupportedPdfParseMethod.OCR,
icecraft's avatar
icecraft committed
149
150
151
152
153
            start_page_id=start_page_id,
            end_page_id=end_page_id,
            debug_mode=debug_mode,
            lang=lang,
        )
icecraft's avatar
icecraft committed
154
        return res