operators.py 6.96 KB
Newer Older
icecraft's avatar
icecraft committed
1
import copy
icecraft's avatar
icecraft committed
2
3
import json
import os
xu rui's avatar
xu rui committed
4
from typing import Callable
icecraft's avatar
icecraft committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

from magic_pdf.config.make_content_config import DropMode, MakeMode
from magic_pdf.data.data_reader_writer import DataWriter
from magic_pdf.data.dataset import Dataset
from magic_pdf.dict2md.ocr_mkcontent import union_make
from magic_pdf.libs.draw_bbox import (draw_layout_bbox, draw_line_sort_bbox,
                                      draw_span_bbox)
from magic_pdf.libs.json_compressor import JsonCompressor


class PipeResult:
    def __init__(self, pipe_res, dataset: Dataset):
        """Initialized.

        Args:
            pipe_res (list[dict]): the pipeline processed result of model inference result
            dataset (Dataset): the dataset associated with pipe_res
        """
        self._pipe_res = pipe_res
        self._dataset = dataset

icecraft's avatar
icecraft committed
26
27
28
29
30
31
    def get_markdown(
        self,
        img_dir_or_bucket_prefix: str,
        drop_mode=DropMode.WHOLE_PDF,
        md_make_mode=MakeMode.MM_MD,
    ) -> str:
icecraft's avatar
icecraft committed
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
        """Get markdown content.

        Args:
            img_dir_or_bucket_prefix (str): The s3 bucket prefix or local file directory which used to store the figure
            drop_mode (str, optional): Drop strategy when some page which is corrupted or inappropriate. Defaults to DropMode.WHOLE_PDF.
            md_make_mode (str, optional): The content Type of Markdown be made. Defaults to MakeMode.MM_MD.

        Returns:
            str: return markdown content
        """
        pdf_info_list = self._pipe_res['pdf_info']
        md_content = union_make(
            pdf_info_list, md_make_mode, drop_mode, img_dir_or_bucket_prefix
        )
        return md_content

icecraft's avatar
icecraft committed
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
    def dump_md(
        self,
        writer: DataWriter,
        file_path: str,
        img_dir_or_bucket_prefix: str,
        drop_mode=DropMode.WHOLE_PDF,
        md_make_mode=MakeMode.MM_MD,
    ):
        """Dump The Markdown.

        Args:
            writer (DataWriter): File writer handle
            file_path (str): The file location of markdown
            img_dir_or_bucket_prefix (str): The s3 bucket prefix or local file directory which used to store the figure
            drop_mode (str, optional): Drop strategy when some page which is corrupted or inappropriate. Defaults to DropMode.WHOLE_PDF.
            md_make_mode (str, optional): The content Type of Markdown be made. Defaults to MakeMode.MM_MD.
        """
icecraft's avatar
icecraft committed
65

icecraft's avatar
icecraft committed
66
67
68
        md_content = self.get_markdown(
            img_dir_or_bucket_prefix, drop_mode=drop_mode, md_make_mode=md_make_mode
        )
icecraft's avatar
icecraft committed
69
70
        writer.write_string(file_path, md_content)

icecraft's avatar
icecraft committed
71
72
73
74
75
76
    def get_content_list(
        self,
        image_dir_or_bucket_prefix: str,
        drop_mode=DropMode.NONE,
        md_make_mode=MakeMode.STANDARD_FORMAT,
    ) -> str:
icecraft's avatar
icecraft committed
77
78
79
80
81
82
83
84
85
86
        """Get Content List.

        Args:
            image_dir_or_bucket_prefix (str): The s3 bucket prefix or local file directory which used to store the figure
            drop_mode (str, optional): Drop strategy when some page which is corrupted or inappropriate. Defaults to DropMode.NONE.
            md_make_mode (str, optional): The content Type of Markdown be made. Defaults to MakeMode.STANDARD_FORMAT.

        Returns:
            str: content list content
        """
icecraft's avatar
icecraft committed
87
        pdf_info_list = self._pipe_res['pdf_info']
icecraft's avatar
icecraft committed
88
89
90
91
92
        content_list = union_make(
            pdf_info_list,
            md_make_mode,
            drop_mode,
            image_dir_or_bucket_prefix,
icecraft's avatar
icecraft committed
93
        )
icecraft's avatar
icecraft committed
94
        return content_list
icecraft's avatar
icecraft committed
95
96

    def dump_content_list(
icecraft's avatar
icecraft committed
97
98
99
100
101
        self,
        writer: DataWriter,
        file_path: str,
        image_dir_or_bucket_prefix: str,
        drop_mode=DropMode.NONE,
icecraft's avatar
icecraft committed
102
        md_make_mode=MakeMode.STANDARD_FORMAT,
icecraft's avatar
icecraft committed
103
104
105
106
107
108
109
    ):
        """Dump Content List.

        Args:
            writer (DataWriter): File writer handle
            file_path (str): The file location of content list
            image_dir_or_bucket_prefix (str): The s3 bucket prefix or local file directory which used to store the figure
icecraft's avatar
icecraft committed
110
111
            drop_mode (str, optional): Drop strategy when some page which is corrupted or inappropriate. Defaults to DropMode.NONE.
            md_make_mode (str, optional): The content Type of Markdown be made. Defaults to MakeMode.STANDARD_FORMAT.
icecraft's avatar
icecraft committed
112
        """
icecraft's avatar
icecraft committed
113
114
115
        content_list = self.get_content_list(
            image_dir_or_bucket_prefix, drop_mode=drop_mode, md_make_mode=md_make_mode
        )
icecraft's avatar
icecraft committed
116
117
118
119
        writer.write_string(
            file_path, json.dumps(content_list, ensure_ascii=False, indent=4)
        )

icecraft's avatar
icecraft committed
120
121
122
123
124
125
126
127
    def get_middle_json(self) -> str:
        """Get middle json.

        Returns:
            str: The content of middle json
        """
        return json.dumps(self._pipe_res, ensure_ascii=False, indent=4)

icecraft's avatar
icecraft committed
128
129
130
131
132
133
134
    def dump_middle_json(self, writer: DataWriter, file_path: str):
        """Dump the result of pipeline.

        Args:
            writer (DataWriter): File writer handler
            file_path (str): The file location of middle json
        """
icecraft's avatar
icecraft committed
135
136
        middle_json = self.get_middle_json()
        writer.write_string(file_path, middle_json)
icecraft's avatar
icecraft committed
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

    def draw_layout(self, file_path: str) -> None:
        """Draw the layout.

        Args:
            file_path (str): The file location of layout result file
        """
        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)
        pdf_info = self._pipe_res['pdf_info']
        draw_layout_bbox(pdf_info, self._dataset.data_bits(), dir_name, base_name)

    def draw_span(self, file_path: str):
        """Draw the Span.

        Args:
            file_path (str): The file location of span result file
        """
        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)
        pdf_info = self._pipe_res['pdf_info']
        draw_span_bbox(pdf_info, self._dataset.data_bits(), dir_name, base_name)

    def draw_line_sort(self, file_path: str):
        """Draw line sort.

        Args:
            file_path (str): The file location of line sort result file
        """
        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)
        pdf_info = self._pipe_res['pdf_info']
        draw_line_sort_bbox(pdf_info, self._dataset.data_bits(), dir_name, base_name)

    def get_compress_pdf_mid_data(self):
        """Compress the pipeline result.

        Returns:
            str: compress the pipeline result and return
        """
icecraft's avatar
icecraft committed
183
        return JsonCompressor.compress_json(self._pipe_res)
xu rui's avatar
xu rui committed
184
185
186
187
188
189
190
191
192
193
194
195

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

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

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