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

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

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

model_config.__use_inside_model__ = True

app = FastAPI()

30
31
pdf_extensions = [".pdf"]
office_extensions = [".ppt", ".pptx", ".doc", ".docx"]
32
image_extensions = [".png", ".jpg", ".jpeg"]
33

34
35
36
class MemoryDataWriter(DataWriter):
    def __init__(self):
        self.buffer = StringIO()
37

38
39
40
    def write(self, path: str, data: bytes) -> None:
        if isinstance(data, str):
            self.buffer.write(data)
41
        else:
shniubobo's avatar
shniubobo committed
42
            self.buffer.write(data.decode("utf-8"))
43

44
45
    def write_string(self, path: str, data: str) -> None:
        self.buffer.write(data)
46

47
48
    def get_value(self) -> str:
        return self.buffer.getvalue()
49

50
51
    def close(self):
        self.buffer.close()
52

shniubobo's avatar
shniubobo committed
53

54
def init_writers(
55
56
    file_path: str = None,
    file: UploadFile = None,
57
58
    output_path: str = None,
    output_image_path: str = None,
shniubobo's avatar
shniubobo committed
59
60
61
62
63
) -> Tuple[
    Union[S3DataWriter, FileBasedDataWriter],
    Union[S3DataWriter, FileBasedDataWriter],
    bytes,
]:
64
65
    """
    Initialize writers based on path type
icecraft's avatar
icecraft committed
66

67
    Args:
JesseChen1031's avatar
JesseChen1031 committed
68
69
        file_path: file path (local path or S3 path)
        file: Uploaded file object
70
71
72
73
        output_path: Output directory path
        output_image_path: Image output directory path

    Returns:
JesseChen1031's avatar
JesseChen1031 committed
74
        Tuple[writer, image_writer, file_bytes]: Returns initialized writer tuple and file content
75
    """
76
77
78
    file_extension:str = None
    if file_path:
        is_s3_path = file_path.startswith("s3://")
79
        if is_s3_path:
80
            bucket = get_bucket_name(file_path)
81
82
            ak, sk, endpoint = get_s3_config(bucket)

shniubobo's avatar
shniubobo committed
83
84
85
86
87
88
            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
            )
89
            # 临时创建reader读取文件内容
shniubobo's avatar
shniubobo committed
90
91
92
            temp_reader = S3DataReader(
                "", bucket=bucket, ak=ak, sk=sk, endpoint_url=endpoint
            )
93
94
            file_bytes = temp_reader.read(file_path)
            file_extension = os.path.splitext(file_path)[1]
icecraft's avatar
icecraft committed
95
        else:
96
97
98
            writer = FileBasedDataWriter(output_path)
            image_writer = FileBasedDataWriter(output_image_path)
            os.makedirs(output_image_path, exist_ok=True)
99
100
101
            with open(file_path, "rb") as f:
                file_bytes = f.read()
            file_extension = os.path.splitext(file_path)[1]
102
103
    else:
        # 处理上传的文件
104
105
        file_bytes = file.file.read()
        file_extension = os.path.splitext(file.filename)[1]
106

107
108
109
110
        writer = FileBasedDataWriter(output_path)
        image_writer = FileBasedDataWriter(output_image_path)
        os.makedirs(output_image_path, exist_ok=True)

111
    return writer, image_writer, file_bytes, file_extension
112

shniubobo's avatar
shniubobo committed
113

114
115
116
def process_file(
    file_bytes: bytes,
    file_extension: str,
117
    parse_method: str,
shniubobo's avatar
shniubobo committed
118
    image_writer: Union[S3DataWriter, FileBasedDataWriter],
119
120
121
122
123
) -> Tuple[InferenceResult, PipeResult]:
    """
    Process PDF file content

    Args:
JesseChen1031's avatar
JesseChen1031 committed
124
125
        file_bytes: Binary content of file
        file_extension: file extension
126
127
        parse_method: Parse method ('ocr', 'txt', 'auto')
        image_writer: Image writer
128

129
130
131
    Returns:
        Tuple[InferenceResult, PipeResult]: Returns inference result and pipeline result
    """
132

133
    ds: Union[PymuDocDataset, ImageDataset] = None
134
135
136
137
138
139
140
141
142
143
144
145
146
147
    if file_extension in pdf_extensions:
        ds = PymuDocDataset(file_bytes)
    elif file_extension in office_extensions:
        # 需要使用office解析
        temp_dir = tempfile.mkdtemp()
        with open(os.path.join(temp_dir, f"temp_file.{file_extension}"), "wb") as f:
            f.write(file_bytes)
        ds = read_local_office(temp_dir)[0]
    elif file_extension in image_extensions:
        # 需要使用ocr解析
        temp_dir = tempfile.mkdtemp()
        with open(os.path.join(temp_dir, f"temp_file.{file_extension}"), "wb") as f:
            f.write(file_bytes)
        ds = read_local_images(temp_dir)[0]
shniubobo's avatar
shniubobo committed
148
149
    infer_result: InferenceResult = None
    pipe_result: PipeResult = None
150

shniubobo's avatar
shniubobo committed
151
    if parse_method == "ocr":
152
153
        infer_result = ds.apply(doc_analyze, ocr=True)
        pipe_result = infer_result.pipe_ocr_mode(image_writer)
shniubobo's avatar
shniubobo committed
154
    elif parse_method == "txt":
155
156
157
158
159
160
161
162
163
        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)
164

165
    return infer_result, pipe_result
166

shniubobo's avatar
shniubobo committed
167

168
169
170
171
172
173
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
174
@app.post(
JesseChen1031's avatar
JesseChen1031 committed
175
    "/file_parse",
shniubobo's avatar
shniubobo committed
176
    tags=["projects"],
JesseChen1031's avatar
JesseChen1031 committed
177
    summary="Parse files (supports local files and S3)",
shniubobo's avatar
shniubobo committed
178
)
179
180
async def file_parse(
    file: UploadFile = None,
181
182
183
184
185
186
187
188
    file_path: str = Form(None),
    parse_method: str = Form("auto"),
    is_json_md_dump: bool = Form(False),
    output_dir: str = Form("output"),
    return_layout: bool = Form(False),
    return_info: bool = Form(False),
    return_content_list: bool = Form(False),
    return_images: bool = Form(False),
189
):
190
191
192
193
    """
    Execute the process of converting PDF to JSON and MD, outputting MD and JSON files
    to the specified directory.

194
    Args:
JesseChen1031's avatar
JesseChen1031 committed
195
196
197
198
        file: The PDF file to be parsed. Must not be specified together with
            `file_path`
        file_path: The path to the PDF file to be parsed. Must not be specified together
            with `file`
199
200
201
202
203
204
205
206
207
208
        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
209
    """
210
    try:
211
212
        if (file is None and file_path is None) or (
            file is not None and file_path is not None
213
214
        ):
            return JSONResponse(
215
                content={"error": "Must provide either file or file_path"},
216
                status_code=400,
shniubobo's avatar
shniubobo committed
217
            )
218
219

        # Get PDF filename
220
        file_name = os.path.basename(file_path if file_path else file.filename).split(
shniubobo's avatar
shniubobo committed
221
222
            "."
        )[0]
223
        output_path = f"{output_dir}/{file_name}"
224
225
226
        output_image_path = f"{output_path}/images"

        # Initialize readers/writers and get PDF content
227
228
229
        writer, image_writer, file_bytes, file_extension = init_writers(
            file_path=file_path,
            file=file,
230
            output_path=output_path,
shniubobo's avatar
shniubobo committed
231
            output_image_path=output_image_path,
232
233
234
        )

        # Process PDF
235
        infer_result, pipe_result = process_file(file_bytes, file_extension, parse_method, image_writer)
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253

        # 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
254
        if is_json_md_dump:
shniubobo's avatar
shniubobo committed
255
            writer.write_string(
256
                f"{file_name}_content_list.json", content_list_writer.get_value()
shniubobo's avatar
shniubobo committed
257
            )
258
            writer.write_string(f"{file_name}.md", md_content)
shniubobo's avatar
shniubobo committed
259
            writer.write_string(
260
                f"{file_name}_middle.json", middle_json_writer.get_value()
shniubobo's avatar
shniubobo committed
261
262
            )
            writer.write_string(
263
                f"{file_name}_model.json",
shniubobo's avatar
shniubobo committed
264
265
                json.dumps(model_json, indent=4, ensure_ascii=False),
            )
266
            # Save visualization results
267
268
            pipe_result.draw_layout(os.path.join(output_path, f"{file_name}_layout.pdf"))
            pipe_result.draw_span(os.path.join(output_path, f"{file_name}_spans.pdf"))
shniubobo's avatar
shniubobo committed
269
            pipe_result.draw_line_sort(
270
                os.path.join(output_path, f"{file_name}_line_sort.pdf")
shniubobo's avatar
shniubobo committed
271
            )
272
            infer_result.draw_model(os.path.join(output_path, f"{file_name}_model.pdf"))
273
274
275
276

        # Build return data
        data = {}
        if return_layout:
shniubobo's avatar
shniubobo committed
277
            data["layout"] = model_json
278
        if return_info:
shniubobo's avatar
shniubobo committed
279
            data["info"] = middle_json
280
        if return_content_list:
shniubobo's avatar
shniubobo committed
281
            data["content_list"] = content_list
282
283
284
285
286
287
288
289
        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
290
        data["md_content"] = md_content  # md_content is always returned
291
292
293
294
295
296

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

297
298
299
300
        return JSONResponse(data, status_code=200)

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

303

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