user_api.py 4.85 KB
Newer Older
赵小蒙's avatar
赵小蒙 committed
1
2
3
4
5
6
7
8
9
10
11
12
13
"""
用户输入:
    model数组,每个元素代表一个页面
    pdf在s3的路径
    截图保存的s3位置

然后:
    1)根据s3路径,调用spark集群的api,拿到ak,sk,endpoint,构造出s3PDFReader
    2)根据用户输入的s3地址,调用spark集群的api,拿到ak,sk,endpoint,构造出s3ImageWriter

其余部分至于构造s3cli, 获取ak,sk都在code-clean里写代码完成。不要反向依赖!!!

"""
14
15
import re

赵小蒙's avatar
赵小蒙 committed
16
17
from loguru import logger

赵小蒙's avatar
赵小蒙 committed
18
from magic_pdf.libs.version import __version__
赵小蒙's avatar
赵小蒙 committed
19
from magic_pdf.model.doc_analyze_by_custom_model import doc_analyze
kernel.h@qq.com's avatar
kernel.h@qq.com committed
20
from magic_pdf.rw import AbsReaderWriter
21
from magic_pdf.pdf_parse_by_ocr_v2 import parse_pdf_by_ocr
许瑞's avatar
许瑞 committed
22
from magic_pdf.pdf_parse_by_txt_v2 import parse_pdf_by_txt
赵小蒙's avatar
赵小蒙 committed
23

kernel.h@qq.com's avatar
kernel.h@qq.com committed
24
25
26
PARSE_TYPE_TXT = "txt"
PARSE_TYPE_OCR = "ocr"

27

赵小蒙's avatar
赵小蒙 committed
28
29
30
31
32
33
34
35
36
37
38
39
40
def parse_txt_pdf(pdf_bytes: bytes, pdf_models: list, imageWriter: AbsReaderWriter, is_debug=False, start_page=0, *args,
                  **kwargs):
    """
    解析文本类pdf
    """
    pdf_info_dict = parse_pdf_by_txt(
        pdf_bytes,
        pdf_models,
        imageWriter,
        start_page_id=start_page,
        debug_mode=is_debug,
    )

kernel.h@qq.com's avatar
kernel.h@qq.com committed
41
    pdf_info_dict["_parse_type"] = PARSE_TYPE_TXT
赵小蒙's avatar
赵小蒙 committed
42

赵小蒙's avatar
赵小蒙 committed
43
    pdf_info_dict["_version_name"] = __version__
赵小蒙's avatar
赵小蒙 committed
44

赵小蒙's avatar
赵小蒙 committed
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
    return pdf_info_dict


def parse_ocr_pdf(pdf_bytes: bytes, pdf_models: list, imageWriter: AbsReaderWriter, is_debug=False, start_page=0, *args,
                  **kwargs):
    """
    解析ocr类pdf
    """
    pdf_info_dict = parse_pdf_by_ocr(
        pdf_bytes,
        pdf_models,
        imageWriter,
        start_page_id=start_page,
        debug_mode=is_debug,
    )

kernel.h@qq.com's avatar
kernel.h@qq.com committed
61
    pdf_info_dict["_parse_type"] = PARSE_TYPE_OCR
赵小蒙's avatar
赵小蒙 committed
62

赵小蒙's avatar
赵小蒙 committed
63
    pdf_info_dict["_version_name"] = __version__
赵小蒙's avatar
赵小蒙 committed
64

赵小蒙's avatar
赵小蒙 committed
65
66
67
68
    return pdf_info_dict


def parse_union_pdf(pdf_bytes: bytes, pdf_models: list, imageWriter: AbsReaderWriter, is_debug=False, start_page=0,
69
                    input_model_is_empty: bool = False,
赵小蒙's avatar
赵小蒙 committed
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
                    *args, **kwargs):
    """
    ocr和文本混合的pdf,全部解析出来
    """

    def parse_pdf(method):
        try:
            return method(
                pdf_bytes,
                pdf_models,
                imageWriter,
                start_page_id=start_page,
                debug_mode=is_debug,
            )
        except Exception as e:
85
            logger.exception(e)
赵小蒙's avatar
赵小蒙 committed
86
87
88
            return None

    pdf_info_dict = parse_pdf(parse_pdf_by_txt)
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
    # text_all = ""
    # for page_dict in pdf_info_dict['pdf_info']:
    #     for para_block in page_dict['para_blocks']:
    #         if para_block['type'] in ['title', 'text']:
    #             for line in para_block['lines']:
    #                 for span in line['spans']:
    #                     text_all += span['content']

    # def calculate_not_common_character_rate(text):
    #     garbage_regex = re.compile(r'[^\u4e00-\u9fa5\u0030-\u0039\u0041-\u005a\u0061-\u007a\u3000-\u303f\uff00-\uffef]')
    #     # 计算乱码字符的数量
    #     garbage_count = len(garbage_regex.findall(text))
    #     total = len(text)
    #     if total == 0:
    #         return 0  # 避免除以零的错误
    #     return garbage_count / total
    #
    # def calculate_not_printable_rate(text):
    #     printable_text = ""
    #     for c in text:
    #         if c.isprintable():
    #             printable_text += c
    #     printable_total = len(printable_text)
    #     total = len(text)
    #     if total == 0:
    #         return 0  # 避免除以零的错误
    #     return (total - printable_total) / total
    #
    # not_common_character_rate = calculate_not_common_character_rate(text_all)
    # not_printable_rate = calculate_not_printable_rate(text_all)
    # pdf_info_dict["_not_common_character_rate"] = not_common_character_rate
    # pdf_info_dict["_not_printable_rate"] = not_printable_rate
    # logger.info(f"not_common_character_rate: {not_common_character_rate}, not_printable_rate: {not_printable_rate}")
    '''新逻辑使用pdfminer识别乱码pdf,准确率高且不会误伤,已在解析流程之前进行处理'''
123
    # not_common_character_rate对小语种可能会有误伤,not_printable_rate对小语种较为友好
124
    if (pdf_info_dict is None
125
126
            or pdf_info_dict.get("_need_drop", False)
            # or not_printable_rate > 0.02  # 参考一些正常的pdf,这个值没有超过0.01的,阈值设为0.02
127
    ):
128
        logger.warning(f"parse_pdf_by_txt drop or error, switch to parse_pdf_by_ocr")
129
130
        if input_model_is_empty:
            pdf_models = doc_analyze(pdf_bytes, ocr=True)
赵小蒙's avatar
赵小蒙 committed
131
132
133
134
        pdf_info_dict = parse_pdf(parse_pdf_by_ocr)
        if pdf_info_dict is None:
            raise Exception("Both parse_pdf_by_txt and parse_pdf_by_ocr failed.")
        else:
kernel.h@qq.com's avatar
kernel.h@qq.com committed
135
            pdf_info_dict["_parse_type"] = PARSE_TYPE_OCR
赵小蒙's avatar
赵小蒙 committed
136
    else:
kernel.h@qq.com's avatar
kernel.h@qq.com committed
137
        pdf_info_dict["_parse_type"] = PARSE_TYPE_TXT
赵小蒙's avatar
赵小蒙 committed
138

赵小蒙's avatar
赵小蒙 committed
139
    pdf_info_dict["_version_name"] = __version__
赵小蒙's avatar
赵小蒙 committed
140

赵小蒙's avatar
赵小蒙 committed
141
    return pdf_info_dict