app.py 9.63 KB
Newer Older
1
2
import json
import os
3
4
from base64 import b64encode
from glob import glob
5
6
from io import StringIO
from typing import Tuple, Union
7
8

import uvicorn
9
from fastapi import FastAPI, HTTPException, UploadFile
10
11
from fastapi.responses import JSONResponse
from loguru import logger
12
13

import magic_pdf.model as model_config
icecraft's avatar
icecraft committed
14
from magic_pdf.config.enums import SupportedPdfParseMethod
15
16
from magic_pdf.data.data_reader_writer import DataWriter, FileBasedDataWriter
from magic_pdf.data.data_reader_writer.s3 import S3DataReader, S3DataWriter
icecraft's avatar
icecraft committed
17
from magic_pdf.data.dataset import PymuDocDataset
18
from magic_pdf.libs.config_reader import get_bucket_name, get_s3_config
icecraft's avatar
icecraft committed
19
from magic_pdf.model.doc_analyze_by_custom_model import doc_analyze
20
from magic_pdf.operators.models import InferenceResult
21
from magic_pdf.operators.pipes import PipeResult
22
23
24
25
26

model_config.__use_inside_model__ = True

app = FastAPI()

27

28
29
30
class MemoryDataWriter(DataWriter):
    def __init__(self):
        self.buffer = StringIO()
31

32
33
34
    def write(self, path: str, data: bytes) -> None:
        if isinstance(data, str):
            self.buffer.write(data)
35
        else:
shniubobo's avatar
shniubobo committed
36
            self.buffer.write(data.decode("utf-8"))
37

38
39
    def write_string(self, path: str, data: str) -> None:
        self.buffer.write(data)
40

41
42
    def get_value(self) -> str:
        return self.buffer.getvalue()
43

44
45
    def close(self):
        self.buffer.close()
46

shniubobo's avatar
shniubobo committed
47

48
49
50
51
52
def init_writers(
    pdf_path: str = None,
    pdf_file: UploadFile = None,
    output_path: str = None,
    output_image_path: str = None,
shniubobo's avatar
shniubobo committed
53
54
55
56
57
) -> Tuple[
    Union[S3DataWriter, FileBasedDataWriter],
    Union[S3DataWriter, FileBasedDataWriter],
    bytes,
]:
58
59
    """
    Initialize writers based on path type
icecraft's avatar
icecraft committed
60

61
62
63
64
65
66
67
    Args:
        pdf_path: PDF file path (local path or S3 path)
        pdf_file: Uploaded PDF file object
        output_path: Output directory path
        output_image_path: Image output directory path

    Returns:
shniubobo's avatar
shniubobo committed
68
69
        Tuple[writer, image_writer, pdf_bytes]: Returns initialized writer tuple and PDF
        file content
70
71
    """
    if pdf_path:
shniubobo's avatar
shniubobo committed
72
        is_s3_path = pdf_path.startswith("s3://")
73
74
75
76
        if is_s3_path:
            bucket = get_bucket_name(pdf_path)
            ak, sk, endpoint = get_s3_config(bucket)

shniubobo's avatar
shniubobo committed
77
78
79
80
81
82
            writer = S3DataWriter(
                output_path, bucket=bucket, ak=ak, sk=sk, endpoint_url=endpoint
            )
            image_writer = S3DataWriter(
                output_image_path, bucket=bucket, ak=ak, sk=sk, endpoint_url=endpoint
            )
83
            # 临时创建reader读取文件内容
shniubobo's avatar
shniubobo committed
84
85
86
            temp_reader = S3DataReader(
                "", bucket=bucket, ak=ak, sk=sk, endpoint_url=endpoint
            )
87
            pdf_bytes = temp_reader.read(pdf_path)
icecraft's avatar
icecraft committed
88
        else:
89
90
91
            writer = FileBasedDataWriter(output_path)
            image_writer = FileBasedDataWriter(output_image_path)
            os.makedirs(output_image_path, exist_ok=True)
shniubobo's avatar
shniubobo committed
92
            with open(pdf_path, "rb") as f:
93
94
95
96
97
98
99
100
101
102
                pdf_bytes = f.read()
    else:
        # 处理上传的文件
        pdf_bytes = pdf_file.file.read()
        writer = FileBasedDataWriter(output_path)
        image_writer = FileBasedDataWriter(output_image_path)
        os.makedirs(output_image_path, exist_ok=True)

    return writer, image_writer, pdf_bytes

shniubobo's avatar
shniubobo committed
103

104
105
106
def process_pdf(
    pdf_bytes: bytes,
    parse_method: str,
shniubobo's avatar
shniubobo committed
107
    image_writer: Union[S3DataWriter, FileBasedDataWriter],
108
109
110
111
112
113
114
115
) -> Tuple[InferenceResult, PipeResult]:
    """
    Process PDF file content

    Args:
        pdf_bytes: Binary content of PDF file
        parse_method: Parse method ('ocr', 'txt', 'auto')
        image_writer: Image writer
116

117
118
119
120
    Returns:
        Tuple[InferenceResult, PipeResult]: Returns inference result and pipeline result
    """
    ds = PymuDocDataset(pdf_bytes)
shniubobo's avatar
shniubobo committed
121
122
    infer_result: InferenceResult = None
    pipe_result: PipeResult = None
123

shniubobo's avatar
shniubobo committed
124
    if parse_method == "ocr":
125
126
        infer_result = ds.apply(doc_analyze, ocr=True)
        pipe_result = infer_result.pipe_ocr_mode(image_writer)
shniubobo's avatar
shniubobo committed
127
    elif parse_method == "txt":
128
129
130
131
132
133
134
135
136
        infer_result = ds.apply(doc_analyze, ocr=False)
        pipe_result = infer_result.pipe_txt_mode(image_writer)
    else:  # auto
        if ds.classify() == SupportedPdfParseMethod.OCR:
            infer_result = ds.apply(doc_analyze, ocr=True)
            pipe_result = infer_result.pipe_ocr_mode(image_writer)
        else:
            infer_result = ds.apply(doc_analyze, ocr=False)
            pipe_result = infer_result.pipe_txt_mode(image_writer)
137

138
    return infer_result, pipe_result
139

shniubobo's avatar
shniubobo committed
140

141
142
143
144
145
146
def encode_image(image_path: str) -> str:
    """Encode image using base64"""
    with open(image_path, "rb") as f:
        return b64encode(f.read()).decode()


shniubobo's avatar
shniubobo committed
147
148
149
150
151
@app.post(
    "/pdf_parse",
    tags=["projects"],
    summary="Parse PDF files (supports local files and S3)",
)
152
153
154
async def pdf_parse(
    pdf_file: UploadFile = None,
    pdf_path: str = None,
shniubobo's avatar
shniubobo committed
155
    parse_method: str = "auto",
156
    is_json_md_dump: bool = False,
shniubobo's avatar
shniubobo committed
157
    output_dir: str = "output",
158
159
160
    return_layout: bool = False,
    return_info: bool = False,
    return_content_list: bool = False,
161
    return_images: bool = False,
162
):
163
164
165
166
    """
    Execute the process of converting PDF to JSON and MD, outputting MD and JSON files
    to the specified directory.

167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
    Args:
        pdf_file: The PDF file to be parsed. Must not be specified together with
            `pdf_path`
        pdf_path: The path to the PDF file to be parsed. Must not be specified together
            with `pdf_file`
        parse_method: Parsing method, can be auto, ocr, or txt. Default is auto. If
            results are not satisfactory, try ocr
        is_json_md_dump: Whether to write parsed data to .json and .md files. Default
            to False. Different stages of data will be written to different .json files
            (3 in total), md content will be saved to .md file
        output_dir: Output directory for results. A folder named after the PDF file
            will be created to store all results
        return_layout: Whether to return parsed PDF layout. Default to False
        return_info: Whether to return parsed PDF info. Default to False
        return_content_list: Whether to return parsed PDF content list. Default to False
182
    """
183
    try:
184
185
186
187
188
189
        if (pdf_file is None and pdf_path is None) or (
            pdf_file is not None and pdf_path is not None
        ):
            return JSONResponse(
                content={"error": "Must provide either pdf_file or pdf_path"},
                status_code=400,
shniubobo's avatar
shniubobo committed
190
            )
191
192

        # Get PDF filename
shniubobo's avatar
shniubobo committed
193
194
195
        pdf_name = os.path.basename(pdf_path if pdf_path else pdf_file.filename).split(
            "."
        )[0]
196
197
198
199
200
201
202
203
        output_path = f"{output_dir}/{pdf_name}"
        output_image_path = f"{output_path}/images"

        # Initialize readers/writers and get PDF content
        writer, image_writer, pdf_bytes = init_writers(
            pdf_path=pdf_path,
            pdf_file=pdf_file,
            output_path=output_path,
shniubobo's avatar
shniubobo committed
204
            output_image_path=output_image_path,
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
        )

        # Process PDF
        infer_result, pipe_result = process_pdf(pdf_bytes, parse_method, image_writer)

        # Use MemoryDataWriter to get results
        content_list_writer = MemoryDataWriter()
        md_content_writer = MemoryDataWriter()
        middle_json_writer = MemoryDataWriter()

        # Use PipeResult's dump method to get data
        pipe_result.dump_content_list(content_list_writer, "", "images")
        pipe_result.dump_md(md_content_writer, "", "images")
        pipe_result.dump_middle_json(middle_json_writer, "")

        # Get content
        content_list = json.loads(content_list_writer.get_value())
        md_content = md_content_writer.get_value()
        middle_json = json.loads(middle_json_writer.get_value())
        model_json = infer_result.get_infer_res()

        # If results need to be saved
227
        if is_json_md_dump:
shniubobo's avatar
shniubobo committed
228
229
230
            writer.write_string(
                f"{pdf_name}_content_list.json", content_list_writer.get_value()
            )
231
            writer.write_string(f"{pdf_name}.md", md_content)
shniubobo's avatar
shniubobo committed
232
233
234
235
236
237
238
            writer.write_string(
                f"{pdf_name}_middle.json", middle_json_writer.get_value()
            )
            writer.write_string(
                f"{pdf_name}_model.json",
                json.dumps(model_json, indent=4, ensure_ascii=False),
            )
239
            # Save visualization results
shniubobo's avatar
shniubobo committed
240
241
242
243
244
245
            pipe_result.draw_layout(os.path.join(output_path, f"{pdf_name}_layout.pdf"))
            pipe_result.draw_span(os.path.join(output_path, f"{pdf_name}_spans.pdf"))
            pipe_result.draw_line_sort(
                os.path.join(output_path, f"{pdf_name}_line_sort.pdf")
            )
            infer_result.draw_model(os.path.join(output_path, f"{pdf_name}_model.pdf"))
246
247
248
249

        # Build return data
        data = {}
        if return_layout:
shniubobo's avatar
shniubobo committed
250
            data["layout"] = model_json
251
        if return_info:
shniubobo's avatar
shniubobo committed
252
            data["info"] = middle_json
253
        if return_content_list:
shniubobo's avatar
shniubobo committed
254
            data["content_list"] = content_list
255
256
257
258
259
260
261
262
        if return_images:
            image_paths = glob(f"{output_image_path}/*.jpg")
            data["images"] = {
                os.path.basename(
                    image_path
                ): f"data:image/jpeg;base64,{encode_image(image_path)}"
                for image_path in image_paths
            }
shniubobo's avatar
shniubobo committed
263
        data["md_content"] = md_content  # md_content is always returned
264
265
266
267
268
269

        # Clean up memory writers
        content_list_writer.close()
        md_content_writer.close()
        middle_json_writer.close()

270
271
272
273
        return JSONResponse(data, status_code=200)

    except Exception as e:
        logger.exception(e)
shniubobo's avatar
shniubobo committed
274
        return JSONResponse(content={"error": str(e)}, status_code=500)
275

276

shniubobo's avatar
shniubobo committed
277
278
if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8888)