hanlp-haystack 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- hanlp_haystack-1.0.0.dist-info/METADATA +46 -0
- hanlp_haystack-1.0.0.dist-info/RECORD +7 -0
- hanlp_haystack-1.0.0.dist-info/WHEEL +4 -0
- hanlp_haystack-1.0.0.dist-info/licenses/LICENSE.txt +73 -0
- haystack_integrations/components/preprocessors/hanlp/__init__.py +8 -0
- haystack_integrations/components/preprocessors/hanlp/chinese_document_splitter.py +545 -0
- haystack_integrations/components/preprocessors/py.typed +0 -0
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: hanlp-haystack
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: An integration of Han Language Processing - HanLP as a ChineseDocumentSplitter component.
|
|
5
|
+
Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/hanlp#readme
|
|
6
|
+
Project-URL: Issues, https://github.com/deepset-ai/haystack-core-integrations/issues
|
|
7
|
+
Project-URL: Source, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/hanlp
|
|
8
|
+
Author-email: deepset GmbH <info@deepset.ai>
|
|
9
|
+
License-Expression: Apache-2.0
|
|
10
|
+
License-File: LICENSE.txt
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
13
|
+
Classifier: Programming Language :: Python
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
20
|
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
21
|
+
Requires-Python: >=3.9
|
|
22
|
+
Requires-Dist: hanlp>=2.1.1
|
|
23
|
+
Requires-Dist: haystack-ai>=2.13.1
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# hanlp-haystack
|
|
27
|
+
|
|
28
|
+
[](https://pypi.org/project/hanlp-haystack)
|
|
29
|
+
[](https://pypi.org/project/hanlp-haystack)
|
|
30
|
+
|
|
31
|
+
-----
|
|
32
|
+
|
|
33
|
+
## Table of Contents
|
|
34
|
+
|
|
35
|
+
- [Installation](#installation)
|
|
36
|
+
- [License](#license)
|
|
37
|
+
|
|
38
|
+
## Installation
|
|
39
|
+
|
|
40
|
+
```console
|
|
41
|
+
pip install hanlp-haystack
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## License
|
|
45
|
+
|
|
46
|
+
`hanlp-haystack` is distributed under the terms of the [Apache-2.0](https://spdx.org/licenses/Apache-2.0.html) license.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
haystack_integrations/components/preprocessors/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
haystack_integrations/components/preprocessors/hanlp/__init__.py,sha256=rOGxZ9m4HojVY-R2s1BrJuTxPLs9mf0jeXC98JbpEFQ,219
|
|
3
|
+
haystack_integrations/components/preprocessors/hanlp/chinese_document_splitter.py,sha256=u_Y9izoo9jqmu-wGzjMimlo_nla70oYcAvQQmLC2_5A,23505
|
|
4
|
+
hanlp_haystack-1.0.0.dist-info/METADATA,sha256=00PNo4VQYDY0sfz0MvGOOFPmDi3pzG4T2EhGVHej7v0,1776
|
|
5
|
+
hanlp_haystack-1.0.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
6
|
+
hanlp_haystack-1.0.0.dist-info/licenses/LICENSE.txt,sha256=B05uMshqTA74s-0ltyHKI6yoPfJ3zYgQbvcXfDVGFf8,10280
|
|
7
|
+
hanlp_haystack-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
|
10
|
+
|
|
11
|
+
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
|
12
|
+
|
|
13
|
+
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
|
14
|
+
|
|
15
|
+
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
|
16
|
+
|
|
17
|
+
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
|
18
|
+
|
|
19
|
+
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
|
20
|
+
|
|
21
|
+
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
|
22
|
+
|
|
23
|
+
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
|
24
|
+
|
|
25
|
+
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
|
26
|
+
|
|
27
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
|
28
|
+
|
|
29
|
+
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
|
30
|
+
|
|
31
|
+
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
|
32
|
+
|
|
33
|
+
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
|
34
|
+
|
|
35
|
+
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
|
36
|
+
|
|
37
|
+
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
|
|
38
|
+
|
|
39
|
+
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
|
40
|
+
|
|
41
|
+
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
|
|
42
|
+
|
|
43
|
+
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
|
44
|
+
|
|
45
|
+
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
|
46
|
+
|
|
47
|
+
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
|
48
|
+
|
|
49
|
+
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
|
50
|
+
|
|
51
|
+
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
|
52
|
+
|
|
53
|
+
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
|
54
|
+
|
|
55
|
+
END OF TERMS AND CONDITIONS
|
|
56
|
+
|
|
57
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
58
|
+
|
|
59
|
+
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
|
|
60
|
+
|
|
61
|
+
Copyright [yyyy] [name of copyright owner]
|
|
62
|
+
|
|
63
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
64
|
+
you may not use this file except in compliance with the License.
|
|
65
|
+
You may obtain a copy of the License at
|
|
66
|
+
|
|
67
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
68
|
+
|
|
69
|
+
Unless required by applicable law or agreed to in writing, software
|
|
70
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
71
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
72
|
+
See the License for the specific language governing permissions and
|
|
73
|
+
limitations under the License.
|
|
@@ -0,0 +1,545 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2025-present deepset GmbH <info@deepset.ai>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
5
|
+
from copy import deepcopy
|
|
6
|
+
from typing import Any, Callable, Dict, List, Literal, Optional, Tuple
|
|
7
|
+
|
|
8
|
+
from haystack import Document, component, logging
|
|
9
|
+
from haystack.core.serialization import default_from_dict, default_to_dict
|
|
10
|
+
from haystack.utils import deserialize_callable, serialize_callable
|
|
11
|
+
from more_itertools import windowed
|
|
12
|
+
|
|
13
|
+
import hanlp
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
# mapping of split by character, 'function' and 'sentence' don't split by character
|
|
18
|
+
_CHARACTER_SPLIT_BY_MAPPING = {"page": "\f", "passage": "\n\n", "period": ".", "word": " ", "line": "\n"}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@component
|
|
22
|
+
class ChineseDocumentSplitter:
|
|
23
|
+
"""
|
|
24
|
+
A DocumentSplitter for Chinese text.
|
|
25
|
+
|
|
26
|
+
'coarse' represents coarse granularity Chinese word segmentation, 'fine' represents fine granularity word
|
|
27
|
+
segmentation, default is coarse granularity word segmentation.
|
|
28
|
+
|
|
29
|
+
Unlike English where words are usually separated by spaces,
|
|
30
|
+
Chinese text is written continuously without spaces between words.
|
|
31
|
+
Chinese words can consist of multiple characters.
|
|
32
|
+
For example, the English word "America" is translated to "美国" in Chinese,
|
|
33
|
+
which consists of two characters but is treated as a single word.
|
|
34
|
+
Similarly, "Portugal" is "葡萄牙" in Chinese, three characters but one word.
|
|
35
|
+
Therefore, splitting by word means splitting by these multi-character tokens,
|
|
36
|
+
not simply by single characters or spaces.
|
|
37
|
+
|
|
38
|
+
### Usage example
|
|
39
|
+
```python
|
|
40
|
+
doc = Document(content=
|
|
41
|
+
"这是第一句话,这是第二句话,这是第三句话。"
|
|
42
|
+
"这是第四句话,这是第五句话,这是第六句话!"
|
|
43
|
+
"这是第七句话,这是第八句话,这是第九句话?"
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
splitter = ChineseDocumentSplitter(
|
|
47
|
+
split_by="word", split_length=10, split_overlap=3, respect_sentence_boundary=True
|
|
48
|
+
)
|
|
49
|
+
splitter.warm_up()
|
|
50
|
+
result = splitter.run(documents=[doc])
|
|
51
|
+
print(result["documents"])
|
|
52
|
+
```
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
def __init__(
|
|
56
|
+
self,
|
|
57
|
+
split_by: Literal["word", "sentence", "passage", "page", "line", "period", "function"] = "word",
|
|
58
|
+
split_length: int = 1000,
|
|
59
|
+
split_overlap: int = 200,
|
|
60
|
+
split_threshold: int = 0,
|
|
61
|
+
respect_sentence_boundary: bool = False,
|
|
62
|
+
splitting_function: Optional[Callable] = None,
|
|
63
|
+
granularity: Literal["coarse", "fine"] = "coarse",
|
|
64
|
+
):
|
|
65
|
+
"""
|
|
66
|
+
Initialize the ChineseDocumentSplitter component.
|
|
67
|
+
|
|
68
|
+
:param split_by: The unit for splitting your documents. Choose from:
|
|
69
|
+
- `word` for splitting by spaces (" ")
|
|
70
|
+
- `period` for splitting by periods (".")
|
|
71
|
+
- `page` for splitting by form feed ("\\f")
|
|
72
|
+
- `passage` for splitting by double line breaks ("\\n\\n")
|
|
73
|
+
- `line` for splitting each line ("\\n")
|
|
74
|
+
- `sentence` for splitting by HanLP sentence tokenizer
|
|
75
|
+
|
|
76
|
+
:param split_length: The maximum number of units in each split.
|
|
77
|
+
:param split_overlap: The number of overlapping units for each split.
|
|
78
|
+
:param split_threshold: The minimum number of units per split. If a split has fewer units
|
|
79
|
+
than the threshold, it's attached to the previous split.
|
|
80
|
+
:param respect_sentence_boundary: Choose whether to respect sentence boundaries when splitting by "word".
|
|
81
|
+
If True, uses HanLP to detect sentence boundaries, ensuring splits occur only between sentences.
|
|
82
|
+
:param splitting_function: Necessary when `split_by` is set to "function".
|
|
83
|
+
This is a function which must accept a single `str` as input and return a `list` of `str` as output,
|
|
84
|
+
representing the chunks after splitting.
|
|
85
|
+
:param granularity: The granularity of Chinese word segmentation, either 'coarse' or 'fine'.
|
|
86
|
+
|
|
87
|
+
:raises ValueError: If the granularity is not 'coarse' or 'fine'.
|
|
88
|
+
"""
|
|
89
|
+
self._validate_init_parameters(split_by, split_length, split_overlap, split_threshold, granularity)
|
|
90
|
+
self.split_by = split_by
|
|
91
|
+
self.split_length = split_length
|
|
92
|
+
self.split_overlap = split_overlap
|
|
93
|
+
self.split_threshold = split_threshold
|
|
94
|
+
self.respect_sentence_boundary = respect_sentence_boundary
|
|
95
|
+
self.splitting_function = splitting_function
|
|
96
|
+
self.granularity = granularity
|
|
97
|
+
|
|
98
|
+
@staticmethod
|
|
99
|
+
def _validate_init_parameters(
|
|
100
|
+
split_by: Literal["word", "sentence", "passage", "page", "line", "period", "function"] = "word",
|
|
101
|
+
split_length: int = 1000,
|
|
102
|
+
split_overlap: int = 200,
|
|
103
|
+
split_threshold: int = 0,
|
|
104
|
+
granularity: Literal["coarse", "fine"] = "coarse",
|
|
105
|
+
) -> None:
|
|
106
|
+
"""
|
|
107
|
+
Validate the init parameters.
|
|
108
|
+
|
|
109
|
+
:param split_by: The unit for splitting your documents.
|
|
110
|
+
:param split_length: The maximum number of units in each split.
|
|
111
|
+
:param split_overlap: The number of overlapping units for each split.
|
|
112
|
+
:param split_threshold: The minimum number of units per split. If a split has fewer units
|
|
113
|
+
than the threshold, it's attached to the previous split.
|
|
114
|
+
:param granularity: The granularity of Chinese word segmentation, either 'coarse' or 'fine'.
|
|
115
|
+
|
|
116
|
+
:raises ValueError:
|
|
117
|
+
If the split_length is not positive.
|
|
118
|
+
If the split_overlap is negative.
|
|
119
|
+
If the split_overlap is greater than or equal to the split_length.
|
|
120
|
+
If the split_threshold is negative.
|
|
121
|
+
If the split_threshold is greater than the split_length.
|
|
122
|
+
If the split_by is not one of 'word', 'sentence', 'passage', 'page', 'line', 'period', 'function'.
|
|
123
|
+
If the granularity is not one of 'coarse', 'fine'.
|
|
124
|
+
"""
|
|
125
|
+
|
|
126
|
+
if split_length <= 0:
|
|
127
|
+
msg = f"split_length must be positive, but got {split_length}"
|
|
128
|
+
raise ValueError(msg)
|
|
129
|
+
if split_overlap < 0:
|
|
130
|
+
msg = f"split_overlap must be non-negative, but got {split_overlap}"
|
|
131
|
+
raise ValueError(msg)
|
|
132
|
+
if split_overlap >= split_length:
|
|
133
|
+
msg = f"split_overlap must be less than split_length, but got {split_overlap} >= {split_length}"
|
|
134
|
+
raise ValueError(msg)
|
|
135
|
+
if split_threshold < 0:
|
|
136
|
+
msg = f"split_threshold must be non-negative, but got {split_threshold}"
|
|
137
|
+
raise ValueError(msg)
|
|
138
|
+
if split_threshold > split_length:
|
|
139
|
+
msg = f"split_threshold must be less than split_length, but got {split_threshold} > {split_length}"
|
|
140
|
+
raise ValueError(msg)
|
|
141
|
+
if split_by not in {"word", "sentence", "passage", "page", "line", "period", "function"}:
|
|
142
|
+
msg = (
|
|
143
|
+
f"split_by must be one of 'word', 'sentence', 'passage', 'page', 'line', 'period', 'function', "
|
|
144
|
+
f"but got {split_by}"
|
|
145
|
+
)
|
|
146
|
+
raise ValueError(msg)
|
|
147
|
+
if granularity not in {"coarse", "fine"}:
|
|
148
|
+
msg = f"granularity must be one of 'coarse', 'fine', but got {granularity}"
|
|
149
|
+
raise ValueError(msg)
|
|
150
|
+
|
|
151
|
+
def run(self, documents: List[Document]) -> Dict[str, List[Document]]:
|
|
152
|
+
"""
|
|
153
|
+
Split documents into smaller chunks.
|
|
154
|
+
|
|
155
|
+
:param documents: The documents to split.
|
|
156
|
+
:return: A dictionary containing the split documents.
|
|
157
|
+
|
|
158
|
+
:raises RuntimeError: If the Chinese word segmentation model is not loaded.
|
|
159
|
+
"""
|
|
160
|
+
if self.split_sent is None:
|
|
161
|
+
msg = "The Chinese word segmentation model is not loaded. Please run 'warm_up()' before calling 'run()'."
|
|
162
|
+
raise RuntimeError(msg)
|
|
163
|
+
|
|
164
|
+
split_docs = []
|
|
165
|
+
for doc in documents:
|
|
166
|
+
split_docs.extend(self._split_document(doc))
|
|
167
|
+
return {"documents": split_docs}
|
|
168
|
+
|
|
169
|
+
def warm_up(self) -> None:
|
|
170
|
+
"""Warm up the component by loading the necessary models."""
|
|
171
|
+
if self.granularity == "coarse":
|
|
172
|
+
self.chinese_tokenizer = hanlp.load(hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH)
|
|
173
|
+
if self.granularity == "fine":
|
|
174
|
+
self.chinese_tokenizer = hanlp.load(hanlp.pretrained.tok.FINE_ELECTRA_SMALL_ZH)
|
|
175
|
+
self.split_sent = hanlp.load(hanlp.pretrained.eos.UD_CTB_EOS_MUL)
|
|
176
|
+
|
|
177
|
+
def _split_by_character(self, doc: Document) -> List[Document]:
|
|
178
|
+
"""
|
|
179
|
+
Define a function to handle Chinese clauses
|
|
180
|
+
|
|
181
|
+
:param doc: The document to split.
|
|
182
|
+
:return: A list of split documents.
|
|
183
|
+
"""
|
|
184
|
+
if doc.content is None:
|
|
185
|
+
return []
|
|
186
|
+
|
|
187
|
+
split_at = _CHARACTER_SPLIT_BY_MAPPING[self.split_by]
|
|
188
|
+
|
|
189
|
+
units = self.chinese_tokenizer(doc.content)
|
|
190
|
+
|
|
191
|
+
for i in range(len(units) - 1):
|
|
192
|
+
units[i] += split_at
|
|
193
|
+
text_splits, splits_pages, splits_start_idxs = self._concatenate_units(
|
|
194
|
+
units, self.split_length, self.split_overlap, self.split_threshold
|
|
195
|
+
)
|
|
196
|
+
metadata = deepcopy(doc.meta)
|
|
197
|
+
metadata["source_id"] = doc.id
|
|
198
|
+
|
|
199
|
+
return self._create_docs_from_splits(
|
|
200
|
+
text_splits=text_splits, splits_pages=splits_pages, splits_start_idxs=splits_start_idxs, meta=metadata
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
# Define a function to handle Chinese clauses
|
|
204
|
+
def chinese_sentence_split(self, text: str) -> List[Dict[str, Any]]:
|
|
205
|
+
"""
|
|
206
|
+
Split Chinese text into sentences.
|
|
207
|
+
|
|
208
|
+
:param text: The text to split.
|
|
209
|
+
:return: A list of split sentences.
|
|
210
|
+
"""
|
|
211
|
+
# Split sentences
|
|
212
|
+
sentences = self.split_sent(text)
|
|
213
|
+
|
|
214
|
+
# Organize the format of segmented sentences
|
|
215
|
+
results = []
|
|
216
|
+
start = 0
|
|
217
|
+
for sentence in sentences:
|
|
218
|
+
start = text.find(sentence, start)
|
|
219
|
+
end = start + len(sentence)
|
|
220
|
+
results.append({"sentence": sentence, "start": start, "end": end})
|
|
221
|
+
start = end
|
|
222
|
+
|
|
223
|
+
return results
|
|
224
|
+
|
|
225
|
+
def _split_document(self, doc: Document) -> List[Document]:
|
|
226
|
+
if self.split_by == "sentence" or self.respect_sentence_boundary:
|
|
227
|
+
return self._split_by_hanlp_sentence(doc)
|
|
228
|
+
|
|
229
|
+
if self.split_by == "function" and self.splitting_function is not None:
|
|
230
|
+
return self._split_by_function(doc)
|
|
231
|
+
|
|
232
|
+
return self._split_by_character(doc)
|
|
233
|
+
|
|
234
|
+
def _concatenate_sentences_based_on_word_amount(
|
|
235
|
+
self, sentences: List[str], split_length: int, split_overlap: int, granularity: str
|
|
236
|
+
) -> Tuple[List[str], List[int], List[int]]:
|
|
237
|
+
"""
|
|
238
|
+
Groups the sentences into chunks of `split_length` words while respecting sentence boundaries.
|
|
239
|
+
|
|
240
|
+
This function is only used when splitting by `word` and `respect_sentence_boundary` is set to `True`, i.e.:
|
|
241
|
+
with HanLP sentence tokenizer.
|
|
242
|
+
|
|
243
|
+
:param sentences: The list of sentences to split.
|
|
244
|
+
:param split_length: The maximum number of words in each split.
|
|
245
|
+
:param split_overlap: The number of overlapping words in each split.
|
|
246
|
+
:returns: A tuple containing the concatenated sentences, the start page numbers, and the start indices.
|
|
247
|
+
"""
|
|
248
|
+
|
|
249
|
+
# chunk information
|
|
250
|
+
chunk_word_count = 0
|
|
251
|
+
chunk_starting_page_number = 1
|
|
252
|
+
chunk_start_idx = 0
|
|
253
|
+
current_chunk: List[str] = []
|
|
254
|
+
|
|
255
|
+
# output lists
|
|
256
|
+
split_start_page_numbers = []
|
|
257
|
+
list_of_splits: List[List[str]] = []
|
|
258
|
+
split_start_indices = []
|
|
259
|
+
|
|
260
|
+
for sentence_idx, sentence in enumerate(sentences):
|
|
261
|
+
current_chunk.append(sentence)
|
|
262
|
+
chunk_word_count += len(self.chinese_tokenizer(sentence))
|
|
263
|
+
next_sentence_word_count = (
|
|
264
|
+
len(self.chinese_tokenizer(sentences[sentence_idx + 1])) if sentence_idx < len(sentences) - 1 else 0
|
|
265
|
+
)
|
|
266
|
+
|
|
267
|
+
# Number of words in the current chunk plus the next sentence is larger than the split_length,
|
|
268
|
+
# or we reached the last sentence
|
|
269
|
+
if (chunk_word_count + next_sentence_word_count) > split_length or sentence_idx == len(sentences) - 1:
|
|
270
|
+
# Save current chunk and start a new one
|
|
271
|
+
list_of_splits.append(current_chunk)
|
|
272
|
+
split_start_page_numbers.append(chunk_starting_page_number)
|
|
273
|
+
split_start_indices.append(chunk_start_idx)
|
|
274
|
+
|
|
275
|
+
# Get the number of sentences that overlap with the next chunk
|
|
276
|
+
num_sentences_to_keep = self._number_of_sentences_to_keep(
|
|
277
|
+
sentences=current_chunk,
|
|
278
|
+
split_length=split_length,
|
|
279
|
+
split_overlap=split_overlap,
|
|
280
|
+
)
|
|
281
|
+
# Set up information for the new chunk
|
|
282
|
+
if num_sentences_to_keep > 0:
|
|
283
|
+
# Processed sentences are the ones that are not overlapping with the next chunk
|
|
284
|
+
processed_sentences = current_chunk[:-num_sentences_to_keep]
|
|
285
|
+
chunk_starting_page_number += sum(sent.count("\f") for sent in processed_sentences)
|
|
286
|
+
chunk_start_idx += len("".join(processed_sentences))
|
|
287
|
+
|
|
288
|
+
# Next chunk starts with the sentences that were overlapping with the previous chunk
|
|
289
|
+
current_chunk = current_chunk[-num_sentences_to_keep:]
|
|
290
|
+
chunk_word_count = sum(len(s.split()) for s in current_chunk)
|
|
291
|
+
else:
|
|
292
|
+
# Here processed_sentences is the same as current_chunk since there is no overlap
|
|
293
|
+
chunk_starting_page_number += sum(sent.count("\f") for sent in current_chunk)
|
|
294
|
+
chunk_start_idx += len("".join(current_chunk))
|
|
295
|
+
current_chunk = []
|
|
296
|
+
chunk_word_count = 0
|
|
297
|
+
|
|
298
|
+
# Concatenate the sentences together within each split
|
|
299
|
+
text_splits = []
|
|
300
|
+
for split in list_of_splits:
|
|
301
|
+
text = "".join(split)
|
|
302
|
+
if len(text) > 0:
|
|
303
|
+
text_splits.append(text)
|
|
304
|
+
|
|
305
|
+
return text_splits, split_start_page_numbers, split_start_indices
|
|
306
|
+
|
|
307
|
+
def _split_by_hanlp_sentence(self, doc: Document) -> List[Document]:
|
|
308
|
+
"""
|
|
309
|
+
Split Chinese text into sentences.
|
|
310
|
+
|
|
311
|
+
:param doc: The document to split.
|
|
312
|
+
:return: A list of split documents.
|
|
313
|
+
"""
|
|
314
|
+
if doc.content is None:
|
|
315
|
+
return []
|
|
316
|
+
|
|
317
|
+
split_docs = []
|
|
318
|
+
result = self.chinese_sentence_split(doc.content)
|
|
319
|
+
units = [sentence["sentence"] for sentence in result]
|
|
320
|
+
|
|
321
|
+
if self.respect_sentence_boundary:
|
|
322
|
+
text_splits, splits_pages, splits_start_idxs = self._concatenate_sentences_based_on_word_amount(
|
|
323
|
+
sentences=units,
|
|
324
|
+
split_length=self.split_length,
|
|
325
|
+
split_overlap=self.split_overlap,
|
|
326
|
+
granularity=self.granularity,
|
|
327
|
+
)
|
|
328
|
+
else:
|
|
329
|
+
text_splits, splits_pages, splits_start_idxs = self._concatenate_units(
|
|
330
|
+
elements=units,
|
|
331
|
+
split_length=self.split_length,
|
|
332
|
+
split_overlap=self.split_overlap,
|
|
333
|
+
split_threshold=self.split_threshold,
|
|
334
|
+
)
|
|
335
|
+
metadata = deepcopy(doc.meta)
|
|
336
|
+
metadata["source_id"] = doc.id
|
|
337
|
+
split_docs += self._create_docs_from_splits(
|
|
338
|
+
text_splits=text_splits, splits_pages=splits_pages, splits_start_idxs=splits_start_idxs, meta=metadata
|
|
339
|
+
)
|
|
340
|
+
|
|
341
|
+
return split_docs
|
|
342
|
+
|
|
343
|
+
def _concatenate_units(
|
|
344
|
+
self, elements: List[str], split_length: int, split_overlap: int, split_threshold: int
|
|
345
|
+
) -> Tuple[List[str], List[int], List[int]]:
|
|
346
|
+
"""
|
|
347
|
+
Concatenates the elements into parts of split_length units.
|
|
348
|
+
|
|
349
|
+
Keeps track of the original page number that each element belongs. If the length of the current units is less
|
|
350
|
+
than the pre-defined `split_threshold`, it does not create a new split. Instead, it concatenates the current
|
|
351
|
+
units with the last split, preventing the creation of excessively small splits.
|
|
352
|
+
"""
|
|
353
|
+
|
|
354
|
+
# If the text is empty or consists only of whitespace, return empty lists
|
|
355
|
+
if not elements or all(not elem.strip() for elem in elements):
|
|
356
|
+
return [], [], []
|
|
357
|
+
|
|
358
|
+
# If the text is too short to split, return it as a single chunk
|
|
359
|
+
if len(elements) <= split_length:
|
|
360
|
+
text = "".join(elements)
|
|
361
|
+
return [text], [1], [0]
|
|
362
|
+
|
|
363
|
+
# Otherwise, proceed as before
|
|
364
|
+
step = split_length - split_overlap
|
|
365
|
+
step = max(step, 1)
|
|
366
|
+
text_splits: List[str] = []
|
|
367
|
+
splits_pages: List[int] = []
|
|
368
|
+
splits_start_idxs: List[int] = []
|
|
369
|
+
cur_start_idx = 0
|
|
370
|
+
cur_page = 1
|
|
371
|
+
segments = windowed(elements, n=split_length, step=step)
|
|
372
|
+
|
|
373
|
+
for seg in segments:
|
|
374
|
+
current_units = [unit for unit in seg if unit is not None]
|
|
375
|
+
txt = "".join(current_units)
|
|
376
|
+
|
|
377
|
+
# check if length of current units is below split_threshold
|
|
378
|
+
if len(current_units) < split_threshold and len(text_splits) > 0:
|
|
379
|
+
# concatenate the last split with the current one
|
|
380
|
+
text_splits[-1] += txt
|
|
381
|
+
|
|
382
|
+
# NOTE: This line skips documents that have content=""
|
|
383
|
+
elif len(txt) > 0:
|
|
384
|
+
text_splits.append(txt)
|
|
385
|
+
splits_pages.append(cur_page)
|
|
386
|
+
splits_start_idxs.append(cur_start_idx)
|
|
387
|
+
|
|
388
|
+
processed_units = current_units[: split_length - split_overlap]
|
|
389
|
+
cur_start_idx += len("".join(processed_units))
|
|
390
|
+
|
|
391
|
+
if self.split_by == "page":
|
|
392
|
+
num_page_breaks = len(processed_units)
|
|
393
|
+
else:
|
|
394
|
+
num_page_breaks = sum(processed_unit.count("\f") for processed_unit in processed_units)
|
|
395
|
+
|
|
396
|
+
cur_page += num_page_breaks
|
|
397
|
+
|
|
398
|
+
return text_splits, splits_pages, splits_start_idxs
|
|
399
|
+
|
|
400
|
+
def _create_docs_from_splits(
|
|
401
|
+
self, text_splits: List[str], splits_pages: List[int], splits_start_idxs: List[int], meta: Dict[str, Any]
|
|
402
|
+
) -> List[Document]:
|
|
403
|
+
"""
|
|
404
|
+
Creates Document objects from splits enriching them with page number and the metadata of the original document.
|
|
405
|
+
"""
|
|
406
|
+
documents: List[Document] = []
|
|
407
|
+
|
|
408
|
+
for i, (txt, split_idx) in enumerate(zip(text_splits, splits_start_idxs)):
|
|
409
|
+
copied_meta = deepcopy(meta)
|
|
410
|
+
copied_meta["page_number"] = splits_pages[i]
|
|
411
|
+
copied_meta["split_id"] = i
|
|
412
|
+
copied_meta["split_idx_start"] = split_idx
|
|
413
|
+
doc = Document(content=txt, meta=copied_meta)
|
|
414
|
+
documents.append(doc)
|
|
415
|
+
|
|
416
|
+
if self.split_overlap <= 0:
|
|
417
|
+
continue
|
|
418
|
+
|
|
419
|
+
doc.meta["_split_overlap"] = []
|
|
420
|
+
|
|
421
|
+
if i == 0:
|
|
422
|
+
continue
|
|
423
|
+
|
|
424
|
+
doc_start_idx = splits_start_idxs[i]
|
|
425
|
+
previous_doc = documents[i - 1]
|
|
426
|
+
previous_doc_start_idx = splits_start_idxs[i - 1]
|
|
427
|
+
self._add_split_overlap_information(doc, doc_start_idx, previous_doc, previous_doc_start_idx)
|
|
428
|
+
|
|
429
|
+
for d in documents:
|
|
430
|
+
if d.content is not None:
|
|
431
|
+
d.content = d.content.replace(" ", "")
|
|
432
|
+
return documents
|
|
433
|
+
|
|
434
|
+
@staticmethod
|
|
435
|
+
def _add_split_overlap_information(
|
|
436
|
+
current_doc: Document, current_doc_start_idx: int, previous_doc: Document, previous_doc_start_idx: int
|
|
437
|
+
) -> None:
|
|
438
|
+
"""
|
|
439
|
+
Adds split overlap information to the current and previous Document's meta.
|
|
440
|
+
|
|
441
|
+
:param current_doc: The Document that is being split.
|
|
442
|
+
:param current_doc_start_idx: The starting index of the current Document.
|
|
443
|
+
:param previous_doc: The Document that was split before the current Document.
|
|
444
|
+
:param previous_doc_start_idx: The starting index of the previous Document.
|
|
445
|
+
"""
|
|
446
|
+
if previous_doc.content is None or current_doc.content is None:
|
|
447
|
+
return
|
|
448
|
+
|
|
449
|
+
overlapping_range = (current_doc_start_idx - previous_doc_start_idx, len(previous_doc.content))
|
|
450
|
+
|
|
451
|
+
if overlapping_range[0] < overlapping_range[1]:
|
|
452
|
+
overlapping_str = previous_doc.content[overlapping_range[0] : overlapping_range[1]]
|
|
453
|
+
|
|
454
|
+
if current_doc.content.startswith(overlapping_str):
|
|
455
|
+
# add split overlap information to this Document regarding the previous Document
|
|
456
|
+
current_doc.meta["_split_overlap"].append({"doc_id": previous_doc.id, "range": overlapping_range})
|
|
457
|
+
|
|
458
|
+
# add split overlap information to previous Document regarding this Document
|
|
459
|
+
overlapping_range = (0, overlapping_range[1] - overlapping_range[0])
|
|
460
|
+
previous_doc.meta["_split_overlap"].append({"doc_id": current_doc.id, "range": overlapping_range})
|
|
461
|
+
|
|
462
|
+
def _number_of_sentences_to_keep(self, sentences: List[str], split_length: int, split_overlap: int) -> int:
|
|
463
|
+
"""
|
|
464
|
+
Returns the number of sentences to keep in the next chunk based on the `split_overlap` and `split_length`.
|
|
465
|
+
|
|
466
|
+
:param sentences: The list of sentences to split.
|
|
467
|
+
:param split_length: The maximum number of words in each split.
|
|
468
|
+
:param split_overlap: The number of overlapping words in each split.
|
|
469
|
+
:returns: The number of sentences to keep in the next chunk.
|
|
470
|
+
"""
|
|
471
|
+
# If the split_overlap is 0, we don't need to keep any sentences
|
|
472
|
+
if split_overlap == 0:
|
|
473
|
+
return 0
|
|
474
|
+
|
|
475
|
+
num_sentences_to_keep = 0
|
|
476
|
+
num_words = 0
|
|
477
|
+
|
|
478
|
+
for sent in reversed(sentences[1:]):
|
|
479
|
+
num_words += len(self.chinese_tokenizer(sent))
|
|
480
|
+
# If the number of words is larger than the split_length then don't add any more sentences
|
|
481
|
+
if num_words > split_length:
|
|
482
|
+
break
|
|
483
|
+
num_sentences_to_keep += 1
|
|
484
|
+
if num_words > split_overlap:
|
|
485
|
+
break
|
|
486
|
+
return num_sentences_to_keep
|
|
487
|
+
|
|
488
|
+
def _split_by_function(self, doc: Document) -> List[Document]:
|
|
489
|
+
"""
|
|
490
|
+
Split a document using a custom splitting function.
|
|
491
|
+
|
|
492
|
+
:param doc: The document to split.
|
|
493
|
+
:return: A list of split documents.
|
|
494
|
+
"""
|
|
495
|
+
if doc.content is None:
|
|
496
|
+
return []
|
|
497
|
+
|
|
498
|
+
if self.splitting_function is None:
|
|
499
|
+
msg = "No splitting function provided."
|
|
500
|
+
raise ValueError(msg)
|
|
501
|
+
|
|
502
|
+
splits = self.splitting_function(doc.content)
|
|
503
|
+
if not isinstance(splits, list):
|
|
504
|
+
msg = "The splitting function must return a list of strings."
|
|
505
|
+
raise ValueError(msg)
|
|
506
|
+
|
|
507
|
+
metadata = deepcopy(doc.meta)
|
|
508
|
+
metadata["source_id"] = doc.id
|
|
509
|
+
|
|
510
|
+
return self._create_docs_from_splits(
|
|
511
|
+
text_splits=splits,
|
|
512
|
+
splits_pages=[1] * len(splits),
|
|
513
|
+
splits_start_idxs=[0] * len(splits),
|
|
514
|
+
meta=metadata,
|
|
515
|
+
)
|
|
516
|
+
|
|
517
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
518
|
+
"""
|
|
519
|
+
Serializes the component to a dictionary.
|
|
520
|
+
"""
|
|
521
|
+
serialized = default_to_dict(
|
|
522
|
+
self,
|
|
523
|
+
split_by=self.split_by,
|
|
524
|
+
split_length=self.split_length,
|
|
525
|
+
split_overlap=self.split_overlap,
|
|
526
|
+
split_threshold=self.split_threshold,
|
|
527
|
+
respect_sentence_boundary=self.respect_sentence_boundary,
|
|
528
|
+
granularity=self.granularity,
|
|
529
|
+
)
|
|
530
|
+
if self.splitting_function:
|
|
531
|
+
serialized["init_parameters"]["splitting_function"] = serialize_callable(self.splitting_function)
|
|
532
|
+
return serialized
|
|
533
|
+
|
|
534
|
+
@classmethod
|
|
535
|
+
def from_dict(cls, data: Dict[str, Any]) -> "ChineseDocumentSplitter":
|
|
536
|
+
"""
|
|
537
|
+
Deserializes the component from a dictionary.
|
|
538
|
+
"""
|
|
539
|
+
init_params = data.get("init_parameters", {})
|
|
540
|
+
|
|
541
|
+
splitting_function = init_params.get("splitting_function", None)
|
|
542
|
+
if splitting_function:
|
|
543
|
+
init_params["splitting_function"] = deserialize_callable(splitting_function)
|
|
544
|
+
|
|
545
|
+
return default_from_dict(cls, data)
|
|
File without changes
|