跳转到内容

预处理

预处理读取器 #

基类:EventBaseReader

Preprocess 是一项 API 服务,可将任何类型的文档分割为适用于语言模型任务的最优文本块。 Preprocess 将文档分割为保留原始文档布局和语义的文本块。 了解更多信息请访问 https://preprocess.co/。

参数:

名称 类型 描述 默认
api_key str

[必填] Preprocess API 密钥。 如果您尚未获取,请发送邮件至 support@preprocess.co 申请。 默认值:None

required
file_path str

[必需] 待预处理文档的路径(转换并分割为文本块)。 默认值:None

required
table_output_format str

文档中表格的输出格式。 可接受的值为 [text, markdown, html]。 默认值:text

required
repeat_table_header bool

如果 True,当表格被分割到多个块时,每个块将包含表格的行标题。 默认值:False

required
merge bool

如果 True,短片段将与其他片段合并以最大化片段长度。 默认值:False

required
repeat_title bool

如果 True,每个文本块将包含父段落或章节的标题。 默认值:False

required
keep_header bool

如果 True,每个页面页眉的内容将被包含在分块中。 默认值:True

required
smart_header bool

如果 True,则仅相关标题会被包含在文本块中,而不相关信息将被移除。 相关标题是指那些作为章节或段落标题的文本。 如果设置为 False,则仅考虑 keep_header 参数。如果 keep_headerFalse,则此参数将被忽略。 默认值:True

required
keep_footer bool

如果 True,每个页面的页脚内容将被包含在分块中。 默认值:False

required
image_text bool

如果 True,图像中包含的文本将被添加到分块中。 默认值:False

required

示例:

>>> loader = PreprocessReader(api_key="your-api-key", file_path="valid/path/to/file")
workflows/handler.py 中的源代码llama_index/readers/preprocess/base.py
 16
 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
 56
 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
 86
 87
 88
 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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
class PreprocessReader(BaseReader):
    """
    Preprocess is an API service that splits any kind of document into optimal chunks of text for use in language model tasks.
    Preprocess splits the documents into chunks of text that respect the layout and semantics of the original document.
    Learn more at https://preprocess.co/.

    Args:
        api_key (str):
            [Required] The Preprocess API Key.
            If you don't have one yet, please request it at support@preprocess.co.
            Default: `None`

        file_path (str):
            [Required] The path to the document to be preprocessed (convertend and split into chunks).
            Default: `None`

        table_output_format (str):
            The output format for tables within the document.
            Accepted values are [text, markdown, html].
            Default: `text`

        repeat_table_header (bool):
            If `True`, when tables are split across multiple chunks, each chunk will include the table's row header.
            Default: `False`

        merge (bool):
            If `True`, short chunks will be merged with others to maximize chunk length.
            Default: `False`

        repeat_title (bool):
            If `True`, each chunk will include the title of the parent paragraph or section.
            Default: `False`

        keep_header (bool):
            If `True`, the content of each page's header will be included in the chunks.
            Default: `True`

        smart_header (bool):
            If `True`, only relevant headers will be included in the chunks, while irrelevant information will be removed.
            Relevant headers are those that serve as section or paragraph titles.
            If set to `False`, only the `keep_header` parameter will be considered. If `keep_header` is `False`, this parameter will be ignored.
            Default: `True`

        keep_footer (bool):
            If `True`, the content of each page's footer will be included in the chunks.
            Default: `False`

        image_text (bool):
            If `True`, the text contained in images will be added to the chunks.
            Default: `False`


    Examples:
        >>> loader = PreprocessReader(api_key="your-api-key", file_path="valid/path/to/file")

    """

    def __init__(self, api_key: str, *args, **kwargs):
        """Initialise with parameters."""
        try:
            from pypreprocess import Preprocess
        except ImportError:
            raise ImportError(
                "`pypreprocess` package not found, please run `pip install"
                " pypreprocess`"
            )

        if api_key is None or api_key == "":
            raise ValueError(
                "Please provide an api key to be used while doing the auth with the system."
            )
        _info = {}
        self._preprocess = Preprocess(api_key)
        self._filepath = None
        self._process_id = None

        for key, value in kwargs.items():
            if key == "filepath":
                self._filepath = value
                self._preprocess.set_filepath(value)

            if key == "process_id":
                self._process_id = value
                self._preprocess.set_process_id(value)

            elif key in ["table_output_format", "table_output"]:
                _info["table_output_format"] = value

            elif key in ["repeat_table_header", "table_header"]:
                _info["repeat_table_header"] = value

            elif key in [
                "merge",
                "repeat_title",
                "keep_header",
                "keep_footer",
                "smart_header",
                "image_text",
            ]:
                _info[key] = value

        if _info != {}:
            self._preprocess.set_info(_info)

        if self._filepath is None and self._process_id is None:
            raise ValueError(
                "Please provide either filepath or process_id to handle the resutls."
            )

        self._chunks = None

    def load_data(self, return_whole_document=False) -> List[Document]:
        """
        Load data from Preprocess.

        Args:
            return_whole_document (bool):
                Returning a list of one element, that element containing the full document.
                Default: `false`

        Examples:
            >>> documents = loader.load_data()
            >>> documents = loader.load_data(return_whole_document=True)

        Returns:
            List[Document]:
                A list of documents each document containing a chunk from the original document.

        """
        if self._chunks is None:
            if self._process_id is not None:
                self._get_data_by_process()
            elif self._filepath is not None:
                self._get_data_by_filepath()

            if self._chunks is not None:
                if return_whole_document is True:
                    return [
                        Document(
                            text=" ".join(self._chunks),
                            metadata={"filename": os.path.basename(self._filepath)},
                        )
                    ]
                else:
                    return [
                        Document(
                            text=chunk,
                            metadata={"filename": os.path.basename(self._filepath)},
                        )
                        for chunk in self._chunks
                    ]
            else:
                raise Exception(
                    "There is error happened during handling your file, please try again."
                )

        else:
            if return_whole_document is True:
                return [
                    Document(
                        text=" ".join(self._chunks),
                        metadata={"filename": os.path.basename(self._filepath)},
                    )
                ]
            else:
                return [
                    Document(
                        text=chunk,
                        metadata={"filename": os.path.basename(self._filepath)},
                    )
                    for chunk in self._chunks
                ]

    def get_process_id(self):
        """
        Get process's hash id from Preprocess.

        Examples:
            >>> process_id = loader.get_process_id()

        Returns:
            str:
                Process's hash id.

        """
        return self._process_id

    def get_nodes(self) -> List[TextNode]:
        """
        Get nodes from Preprocess's chunks.

        Examples:
            >>> nodes = loader.get_nodes()

        Returns:
            List[TextNode]:
                List of nodes, each node will contains a chunk from the original document.

        """
        if self._chunks is None:
            self.load_data()

        nodes = []
        for chunk in self._chunks:
            text = str(chunk)
            id = hashlib.md5(text.encode()).hexdigest()
            nodes.append(TextNode(text=text, id_=id))

        if len(nodes) > 1:
            nodes[0].relationships[NodeRelationship.NEXT] = RelatedNodeInfo(
                node_id=nodes[1].node_id,
                metadata={"filename": os.path.basename(self._filepath)},
            )
            for i in range(1, len(nodes) - 1):
                nodes[i].relationships[NodeRelationship.NEXT] = RelatedNodeInfo(
                    node_id=nodes[i + 1].node_id,
                    metadata={"filename": os.path.basename(self._filepath)},
                )
                nodes[i].relationships[NodeRelationship.PREVIOUS] = RelatedNodeInfo(
                    node_id=nodes[i - 1].node_id,
                    metadata={"filename": os.path.basename(self._filepath)},
                )

            nodes[-1].relationships[NodeRelationship.PREVIOUS] = RelatedNodeInfo(
                node_id=nodes[-2].node_id,
                metadata={"filename": os.path.basename(self._filepath)},
            )
        return nodes

    def _get_data_by_filepath(self) -> None:
        pp_response = self._preprocess.chunk()
        if pp_response.status == "OK" and pp_response.success is True:
            self._process_id = pp_response.data["process"]["id"]
            response = self._preprocess.wait()
            if response.status == "OK" and response.success is True:
                # self._filepath = response.data['info']['file']['name']
                self._chunks = response.data["chunks"]

    def _get_data_by_process(self) -> None:
        response = self._preprocess.wait()
        if response.status == "OK" and response.success is True:
            self._filepath = response.data["info"]["file"]["name"]
            self._chunks = response.data["chunks"]

load_data #

load_data(return_whole_document=False) -> List[文档]

从预处理加载数据。

参数:

名称 类型 描述 默认
return_whole_document bool

返回一个包含单个元素的列表,该元素包含完整文档。 默认值:false

False

示例:

>>> documents = loader.load_data()
>>> documents = loader.load_data(return_whole_document=True)

返回:

类型 描述
List[文档]

List[Document]: 一个文档列表,每个文档包含原始文档的一个片段。

workflows/handler.py 中的源代码llama_index/readers/preprocess/base.py
127
128
129
130
131
132
133
134
135
136
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
183
184
185
186
187
def load_data(self, return_whole_document=False) -> List[Document]:
    """
    Load data from Preprocess.

    Args:
        return_whole_document (bool):
            Returning a list of one element, that element containing the full document.
            Default: `false`

    Examples:
        >>> documents = loader.load_data()
        >>> documents = loader.load_data(return_whole_document=True)

    Returns:
        List[Document]:
            A list of documents each document containing a chunk from the original document.

    """
    if self._chunks is None:
        if self._process_id is not None:
            self._get_data_by_process()
        elif self._filepath is not None:
            self._get_data_by_filepath()

        if self._chunks is not None:
            if return_whole_document is True:
                return [
                    Document(
                        text=" ".join(self._chunks),
                        metadata={"filename": os.path.basename(self._filepath)},
                    )
                ]
            else:
                return [
                    Document(
                        text=chunk,
                        metadata={"filename": os.path.basename(self._filepath)},
                    )
                    for chunk in self._chunks
                ]
        else:
            raise Exception(
                "There is error happened during handling your file, please try again."
            )

    else:
        if return_whole_document is True:
            return [
                Document(
                    text=" ".join(self._chunks),
                    metadata={"filename": os.path.basename(self._filepath)},
                )
            ]
        else:
            return [
                Document(
                    text=chunk,
                    metadata={"filename": os.path.basename(self._filepath)},
                )
                for chunk in self._chunks
            ]

get_process_id #

get_process_id()

从预处理中获取进程的哈希ID。

示例:

>>> process_id = loader.get_process_id()

返回:

名称 类型 描述
str

进程的哈希标识。

workflows/handler.py 中的源代码llama_index/readers/preprocess/base.py
189
190
191
192
193
194
195
196
197
198
199
200
201
def get_process_id(self):
    """
    Get process's hash id from Preprocess.

    Examples:
        >>> process_id = loader.get_process_id()

    Returns:
        str:
            Process's hash id.

    """
    return self._process_id

get_nodes #

get_nodes() -> List[TextNode]

从 Preprocess 的块中获取节点。

示例:

>>> nodes = loader.get_nodes()

返回:

类型 描述
List[TextNode]

List[TextNode]: 节点列表,每个节点包含原始文档的一个片段。

workflows/handler.py 中的源代码llama_index/readers/preprocess/base.py
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
def get_nodes(self) -> List[TextNode]:
    """
    Get nodes from Preprocess's chunks.

    Examples:
        >>> nodes = loader.get_nodes()

    Returns:
        List[TextNode]:
            List of nodes, each node will contains a chunk from the original document.

    """
    if self._chunks is None:
        self.load_data()

    nodes = []
    for chunk in self._chunks:
        text = str(chunk)
        id = hashlib.md5(text.encode()).hexdigest()
        nodes.append(TextNode(text=text, id_=id))

    if len(nodes) > 1:
        nodes[0].relationships[NodeRelationship.NEXT] = RelatedNodeInfo(
            node_id=nodes[1].node_id,
            metadata={"filename": os.path.basename(self._filepath)},
        )
        for i in range(1, len(nodes) - 1):
            nodes[i].relationships[NodeRelationship.NEXT] = RelatedNodeInfo(
                node_id=nodes[i + 1].node_id,
                metadata={"filename": os.path.basename(self._filepath)},
            )
            nodes[i].relationships[NodeRelationship.PREVIOUS] = RelatedNodeInfo(
                node_id=nodes[i - 1].node_id,
                metadata={"filename": os.path.basename(self._filepath)},
            )

        nodes[-1].relationships[NodeRelationship.PREVIOUS] = RelatedNodeInfo(
            node_id=nodes[-2].node_id,
            metadata={"filename": os.path.basename(self._filepath)},
        )
    return nodes

选项: 成员:- PreprocessReader