diff --git a/.github/labeler.yml b/.github/labeler.yml index 386580c65..72d93019b 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -69,6 +69,11 @@ integration:google-vertex: - any-glob-to-any-file: "integrations/google_vertex/**/*" - any-glob-to-any-file: ".github/workflows/google_vertex.yml" +integration:hanlp: + - changed-files: + - any-glob-to-any-file: "integrations/hanlp/**/*" + - any-glob-to-any-file: ".github/workflows/hanlp.yml" + integration:jina: - changed-files: - any-glob-to-any-file: "integrations/jina/**/*" diff --git a/.github/workflows/hanlp.yml b/.github/workflows/hanlp.yml new file mode 100644 index 000000000..7734892f9 --- /dev/null +++ b/.github/workflows/hanlp.yml @@ -0,0 +1,88 @@ +# This workflow comes from https://github.com/ofek/hatch-mypyc +# https://github.com/ofek/hatch-mypyc/blob/5a198c0ba8660494d02716cfc9d79ce4adfb1442/.github/workflows/test.yml +name: Test / hanlp + +on: + schedule: + - cron: "0 0 * * *" + pull_request: + paths: + - "integrations/hanlp/**" + - "!integrations/hanlp/*.md" + - ".github/workflows/hanlp.yml" + +defaults: + run: + working-directory: integrations/hanlp + +concurrency: + group: hanlp-${{ github.head_ref }} + cancel-in-progress: true + +env: + PYTHONUNBUFFERED: "1" + FORCE_COLOR: "1" + +jobs: + run: + name: Python ${{ matrix.python-version }} on ${{ startsWith(matrix.os, 'macos-') && 'macOS' || startsWith(matrix.os, 'windows-') && 'Windows' || 'Linux' }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest, macos-latest] + python-version: ["3.9", "3.13"] + + # sentencepiece cannot be installed on Windows with Python 3.13 + # https://github.com/google/sentencepiece/issues/1111 + exclude: + - os: windows-latest + python-version: "3.13" + + steps: + - name: Support longpaths + if: matrix.os == 'windows-latest' + working-directory: . + run: git config --system core.longpaths true + + - uses: actions/checkout@v4 + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + + - name: Install Hatch + run: pip install --upgrade hatch + + - name: Lint + if: matrix.python-version == '3.9' && runner.os == 'Linux' + run: hatch run fmt-check && hatch run test:types + + - name: Generate docs + if: matrix.python-version == '3.9' && runner.os == 'Linux' + run: hatch run docs + + - name: Run tests + run: hatch run test:cov-retry + + - name: Run unit tests with lowest direct dependencies + run: | + hatch run uv pip compile pyproject.toml --resolution lowest-direct --output-file requirements_lowest_direct.txt + hatch run uv pip install -r requirements_lowest_direct.txt + hatch run test:unit + + - name: Nightly - run unit tests with Haystack main branch + if: github.event_name == 'schedule' + run: | + hatch env prune + hatch run uv pip install git+https://github.com/deepset-ai/haystack.git@main + hatch run test:unit + + - name: Send event to Datadog for nightly failures + if: failure() && github.event_name == 'schedule' + uses: ./.github/actions/send_failure + with: + title: | + Core integrations nightly tests failure: ${{ github.workflow }} + api-key: ${{ secrets.CORE_DATADOG_API_KEY }} diff --git a/README.md b/README.md index 00fc98f34..897b577c1 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,7 @@ Please check out our [Contribution Guidelines](CONTRIBUTING.md) for all the deta | [google-ai-haystack](integrations/google_ai/) | Generator | [![PyPI - Version](https://img.shields.io/pypi/v/google-ai-haystack.svg)](https://pypi.org/project/google-ai-haystack) | [![Test / google-ai](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/google_ai.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/google_ai.yml) | | [google-genai-haystack](integrations/google_genai/) | Embedder, Generator | [![PyPI - Version](https://img.shields.io/pypi/v/google-genai-haystack.svg)](https://pypi.org/project/google-genai-haystack) | [![Test / google-genai](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/google_genai.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/google_genai.yml) | | [google-vertex-haystack](integrations/google_vertex/) | Embedder, Generator | [![PyPI - Version](https://img.shields.io/pypi/v/google-vertex-haystack.svg)](https://pypi.org/project/google-vertex-haystack) | [![Test / google-vertex](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/google_vertex.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/google_vertex.yml) | +| [hanlp-haystack](integrations/hanlp/) | Preprocessor | [![PyPI - Version](https://img.shields.io/pypi/v/hanlp-haystack.svg)](https://pypi.org/project/hanlp-haystack) | [![Test / hanlp](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/hanlp.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/hanlp.yml) | | [jina-haystack](integrations/jina/) | Connector, Embedder, Ranker | [![PyPI - Version](https://img.shields.io/pypi/v/jina-haystack.svg)](https://pypi.org/project/jina-haystack) | [![Test / jina](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/jina.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/jina.yml) | | [langfuse-haystack](integrations/langfuse/) | Tracer | [![PyPI - Version](https://img.shields.io/pypi/v/langfuse-haystack.svg?color=orange)](https://pypi.org/project/langfuse-haystack) | [![Test / langfuse](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/langfuse.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/langfuse.yml) | | [llama-cpp-haystack](integrations/llama_cpp/) | Generator | [![PyPI - Version](https://img.shields.io/pypi/v/llama-cpp-haystack.svg?color=orange)](https://pypi.org/project/llama-cpp-haystack) | [![Test / llama-cpp](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/llama_cpp.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/llama_cpp.yml) | diff --git a/integrations/hanlp/LICENSE.txt b/integrations/hanlp/LICENSE.txt new file mode 100644 index 000000000..137069b82 --- /dev/null +++ b/integrations/hanlp/LICENSE.txt @@ -0,0 +1,73 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"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. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"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. + +"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). + +"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. + +"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." + +"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. + +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. + +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. + +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: + + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and + + (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 + + (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. + + 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. + +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. + +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. + +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. + +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. + +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. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +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. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/integrations/hanlp/README.md b/integrations/hanlp/README.md new file mode 100644 index 000000000..cf16e8dbf --- /dev/null +++ b/integrations/hanlp/README.md @@ -0,0 +1,21 @@ +# hanlp-haystack + +[![PyPI - Version](https://img.shields.io/pypi/v/hanlp-haystack.svg)](https://pypi.org/project/hanlp-haystack) +[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/hanlp-haystack.svg)](https://pypi.org/project/hanlp-haystack) + +----- + +## Table of Contents + +- [Installation](#installation) +- [License](#license) + +## Installation + +```console +pip install hanlp-haystack +``` + +## License + +`hanlp-haystack` is distributed under the terms of the [Apache-2.0](https://spdx.org/licenses/Apache-2.0.html) license. diff --git a/integrations/hanlp/pydoc/config.yml b/integrations/hanlp/pydoc/config.yml new file mode 100644 index 000000000..3491322fa --- /dev/null +++ b/integrations/hanlp/pydoc/config.yml @@ -0,0 +1,29 @@ +loaders: + - type: haystack_pydoc_tools.loaders.CustomPythonLoader + search_path: [../src] + modules: [ + "haystack_integrations.components.preprocessors.hanlp.chinese_document_splitter", + ] + ignore_when_discovered: ["__init__"] +processors: + - type: filter + expression: + documented_only: true + do_not_filter_modules: false + skip_empty_modules: true + - type: smart + - type: crossref +renderer: + type: haystack_pydoc_tools.renderers.ReadmeIntegrationRenderer + excerpt: HanLP integration for Haystack + category_slug: integrations-api + title: HanLP + slug: integrations-hanlp + order: 100 + markdown: + descriptive_class_title: false + classdef_code_block: false + descriptive_module_title: true + add_method_class_prefix: true + add_member_class_prefix: false + filename: _readme_github.md \ No newline at end of file diff --git a/integrations/hanlp/pyproject.toml b/integrations/hanlp/pyproject.toml new file mode 100644 index 000000000..41342bce8 --- /dev/null +++ b/integrations/hanlp/pyproject.toml @@ -0,0 +1,171 @@ +[build-system] +requires = ["hatchling", "hatch-vcs"] +build-backend = "hatchling.build" + +[project] +name = "hanlp-haystack" +dynamic = ["version"] +description = 'An integration of Han Language Processing - HanLP as a ChineseDocumentSplitter component.' +readme = "README.md" +requires-python = ">=3.9" +license = "Apache-2.0" +keywords = [] +authors = [{ name = "deepset GmbH", email = "info@deepset.ai" }] +classifiers = [ + "License :: OSI Approved :: Apache Software License", + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", +] +dependencies = [ + "haystack-ai>=2.13.1", + "hanlp>=2.1.1" +] + +[project.urls] +Documentation = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/hanlp#readme" +Issues = "https://github.com/deepset-ai/haystack-core-integrations/issues" +Source = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/hanlp" + +[tool.hatch.build.targets.wheel] +packages = ["src/haystack_integrations"] + +[tool.hatch.version] +source = "vcs" +tag-pattern = 'integrations\/hanlp-v(?P.*)' + +[tool.hatch.version.raw-options] +root = "../.." +git_describe_command = 'git describe --tags --match="integrations/hanlp-v[0-9]*"' + +[tool.hatch.envs.default] +installer = "uv" +dependencies = ["haystack-pydoc-tools", "ruff"] + +[tool.hatch.envs.default.scripts] +docs = ["pydoc-markdown pydoc/config.yml"] +fmt = "ruff check --fix {args} && ruff format {args}" +fmt-check = "ruff check {args} && ruff format --check {args}" + +[tool.hatch.envs.test] +dependencies = [ + "pytest", + "pytest-asyncio", + "pytest-cov", + "pytest-rerunfailures", + "mypy", + "pip" +] + +[tool.hatch.envs.test.scripts] +unit = 'pytest -m "not integration" {args:tests}' +integration = 'pytest -m "integration" {args:tests}' +all = 'pytest {args:tests}' +cov-retry = 'all --cov=haystack_integrations --reruns 3 --reruns-delay 30 -x' +types = """mypy -p haystack_integrations.components.preprocessors.hanlp {args}""" + +[tool.mypy] +install_types = true +non_interactive = true +check_untyped_defs = true +disallow_incomplete_defs = true + +[[tool.mypy.overrides]] +module = [ +"hanlp.*", +] +ignore_missing_imports = true + +[tool.black] +target-version = ["py38"] +line-length = 120 +skip-string-normalization = true + +[tool.ruff] +target-version = "py38" +line-length = 120 + +[tool.ruff.lint] +select = [ + "A", + "ARG", + "B", + "C", + "DTZ", + "E", + "EM", + "F", + "I", + "ICN", + "ISC", + "N", + "PLC", + "PLE", + "PLR", + "PLW", + "Q", + "RUF", + "S", + "T", + "TID", + "UP", + "W", + "YTT", +] +ignore = [ + # Allow non-abstract empty methods in abstract base classes + "B027", + # Ignore checks for possible passwords + "S105", + "S106", + "S107", + # Ignore complexity + "C901", + "PLR0911", + "PLR0912", + "PLR0913", + "PLR0915", + # Ignore unused params + "ARG001", + "ARG002", + "ARG005", + "RUF001", + "RUF002", +] +unfixable = [ + # Don't touch unused imports + "F401", +] + +[tool.ruff.lint.isort] +known-first-party = ["haystack_integrations"] + +[tool.ruff.lint.flake8-tidy-imports] +ban-relative-imports = "parents" + +[tool.ruff.lint.per-file-ignores] +# Tests can use magic values, assertions, and relative imports +"tests/**/*" = ["PLR2004", "S101", "TID252"] + +[tool.coverage.run] +source = ["haystack_integrations"] +branch = true +parallel = false + +[tool.coverage.report] +omit = ["*/tests/*", "*/__init__.py"] +show_missing = true +exclude_lines = ["no cov", "if __name__ == .__main__.:", "if TYPE_CHECKING:"] + +[tool.pytest.ini_options] +addopts = "--strict-markers" +markers = [ + "integration: integration tests", +] +log_cli = true diff --git a/integrations/hanlp/src/haystack_integrations/components/preprocessors/hanlp/__init__.py b/integrations/hanlp/src/haystack_integrations/components/preprocessors/hanlp/__init__.py new file mode 100644 index 000000000..c6cb8827d --- /dev/null +++ b/integrations/hanlp/src/haystack_integrations/components/preprocessors/hanlp/__init__.py @@ -0,0 +1,8 @@ +# SPDX-FileCopyrightText: 2025-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +from .chinese_document_splitter import ChineseDocumentSplitter + +__all__ = [ + "ChineseDocumentSplitter", +] diff --git a/integrations/hanlp/src/haystack_integrations/components/preprocessors/hanlp/chinese_document_splitter.py b/integrations/hanlp/src/haystack_integrations/components/preprocessors/hanlp/chinese_document_splitter.py new file mode 100644 index 000000000..79f5654f1 --- /dev/null +++ b/integrations/hanlp/src/haystack_integrations/components/preprocessors/hanlp/chinese_document_splitter.py @@ -0,0 +1,545 @@ +# SPDX-FileCopyrightText: 2025-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +from copy import deepcopy +from typing import Any, Callable, Dict, List, Literal, Optional, Tuple + +from haystack import Document, component, logging +from haystack.core.serialization import default_from_dict, default_to_dict +from haystack.utils import deserialize_callable, serialize_callable +from more_itertools import windowed + +import hanlp + +logger = logging.getLogger(__name__) + +# mapping of split by character, 'function' and 'sentence' don't split by character +_CHARACTER_SPLIT_BY_MAPPING = {"page": "\f", "passage": "\n\n", "period": ".", "word": " ", "line": "\n"} + + +@component +class ChineseDocumentSplitter: + """ + A DocumentSplitter for Chinese text. + + 'coarse' represents coarse granularity Chinese word segmentation, 'fine' represents fine granularity word + segmentation, default is coarse granularity word segmentation. + + Unlike English where words are usually separated by spaces, + Chinese text is written continuously without spaces between words. + Chinese words can consist of multiple characters. + For example, the English word "America" is translated to "美国" in Chinese, + which consists of two characters but is treated as a single word. + Similarly, "Portugal" is "葡萄牙" in Chinese, three characters but one word. + Therefore, splitting by word means splitting by these multi-character tokens, + not simply by single characters or spaces. + + ### Usage example + ```python + doc = Document(content= + "这是第一句话,这是第二句话,这是第三句话。" + "这是第四句话,这是第五句话,这是第六句话!" + "这是第七句话,这是第八句话,这是第九句话?" + ) + + splitter = ChineseDocumentSplitter( + split_by="word", split_length=10, split_overlap=3, respect_sentence_boundary=True + ) + splitter.warm_up() + result = splitter.run(documents=[doc]) + print(result["documents"]) + ``` + """ + + def __init__( + self, + split_by: Literal["word", "sentence", "passage", "page", "line", "period", "function"] = "word", + split_length: int = 1000, + split_overlap: int = 200, + split_threshold: int = 0, + respect_sentence_boundary: bool = False, + splitting_function: Optional[Callable] = None, + granularity: Literal["coarse", "fine"] = "coarse", + ): + """ + Initialize the ChineseDocumentSplitter component. + + :param split_by: The unit for splitting your documents. Choose from: + - `word` for splitting by spaces (" ") + - `period` for splitting by periods (".") + - `page` for splitting by form feed ("\\f") + - `passage` for splitting by double line breaks ("\\n\\n") + - `line` for splitting each line ("\\n") + - `sentence` for splitting by HanLP sentence tokenizer + + :param split_length: The maximum number of units in each split. + :param split_overlap: The number of overlapping units for each split. + :param split_threshold: The minimum number of units per split. If a split has fewer units + than the threshold, it's attached to the previous split. + :param respect_sentence_boundary: Choose whether to respect sentence boundaries when splitting by "word". + If True, uses HanLP to detect sentence boundaries, ensuring splits occur only between sentences. + :param splitting_function: Necessary when `split_by` is set to "function". + This is a function which must accept a single `str` as input and return a `list` of `str` as output, + representing the chunks after splitting. + :param granularity: The granularity of Chinese word segmentation, either 'coarse' or 'fine'. + + :raises ValueError: If the granularity is not 'coarse' or 'fine'. + """ + self._validate_init_parameters(split_by, split_length, split_overlap, split_threshold, granularity) + self.split_by = split_by + self.split_length = split_length + self.split_overlap = split_overlap + self.split_threshold = split_threshold + self.respect_sentence_boundary = respect_sentence_boundary + self.splitting_function = splitting_function + self.granularity = granularity + + @staticmethod + def _validate_init_parameters( + split_by: Literal["word", "sentence", "passage", "page", "line", "period", "function"] = "word", + split_length: int = 1000, + split_overlap: int = 200, + split_threshold: int = 0, + granularity: Literal["coarse", "fine"] = "coarse", + ) -> None: + """ + Validate the init parameters. + + :param split_by: The unit for splitting your documents. + :param split_length: The maximum number of units in each split. + :param split_overlap: The number of overlapping units for each split. + :param split_threshold: The minimum number of units per split. If a split has fewer units + than the threshold, it's attached to the previous split. + :param granularity: The granularity of Chinese word segmentation, either 'coarse' or 'fine'. + + :raises ValueError: + If the split_length is not positive. + If the split_overlap is negative. + If the split_overlap is greater than or equal to the split_length. + If the split_threshold is negative. + If the split_threshold is greater than the split_length. + If the split_by is not one of 'word', 'sentence', 'passage', 'page', 'line', 'period', 'function'. + If the granularity is not one of 'coarse', 'fine'. + """ + + if split_length <= 0: + msg = f"split_length must be positive, but got {split_length}" + raise ValueError(msg) + if split_overlap < 0: + msg = f"split_overlap must be non-negative, but got {split_overlap}" + raise ValueError(msg) + if split_overlap >= split_length: + msg = f"split_overlap must be less than split_length, but got {split_overlap} >= {split_length}" + raise ValueError(msg) + if split_threshold < 0: + msg = f"split_threshold must be non-negative, but got {split_threshold}" + raise ValueError(msg) + if split_threshold > split_length: + msg = f"split_threshold must be less than split_length, but got {split_threshold} > {split_length}" + raise ValueError(msg) + if split_by not in {"word", "sentence", "passage", "page", "line", "period", "function"}: + msg = ( + f"split_by must be one of 'word', 'sentence', 'passage', 'page', 'line', 'period', 'function', " + f"but got {split_by}" + ) + raise ValueError(msg) + if granularity not in {"coarse", "fine"}: + msg = f"granularity must be one of 'coarse', 'fine', but got {granularity}" + raise ValueError(msg) + + def run(self, documents: List[Document]) -> Dict[str, List[Document]]: + """ + Split documents into smaller chunks. + + :param documents: The documents to split. + :return: A dictionary containing the split documents. + + :raises RuntimeError: If the Chinese word segmentation model is not loaded. + """ + if self.split_sent is None: + msg = "The Chinese word segmentation model is not loaded. Please run 'warm_up()' before calling 'run()'." + raise RuntimeError(msg) + + split_docs = [] + for doc in documents: + split_docs.extend(self._split_document(doc)) + return {"documents": split_docs} + + def warm_up(self) -> None: + """Warm up the component by loading the necessary models.""" + if self.granularity == "coarse": + self.chinese_tokenizer = hanlp.load(hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH) + if self.granularity == "fine": + self.chinese_tokenizer = hanlp.load(hanlp.pretrained.tok.FINE_ELECTRA_SMALL_ZH) + self.split_sent = hanlp.load(hanlp.pretrained.eos.UD_CTB_EOS_MUL) + + def _split_by_character(self, doc: Document) -> List[Document]: + """ + Define a function to handle Chinese clauses + + :param doc: The document to split. + :return: A list of split documents. + """ + if doc.content is None: + return [] + + split_at = _CHARACTER_SPLIT_BY_MAPPING[self.split_by] + + units = self.chinese_tokenizer(doc.content) + + for i in range(len(units) - 1): + units[i] += split_at + text_splits, splits_pages, splits_start_idxs = self._concatenate_units( + units, self.split_length, self.split_overlap, self.split_threshold + ) + metadata = deepcopy(doc.meta) + metadata["source_id"] = doc.id + + return self._create_docs_from_splits( + text_splits=text_splits, splits_pages=splits_pages, splits_start_idxs=splits_start_idxs, meta=metadata + ) + + # Define a function to handle Chinese clauses + def chinese_sentence_split(self, text: str) -> List[Dict[str, Any]]: + """ + Split Chinese text into sentences. + + :param text: The text to split. + :return: A list of split sentences. + """ + # Split sentences + sentences = self.split_sent(text) + + # Organize the format of segmented sentences + results = [] + start = 0 + for sentence in sentences: + start = text.find(sentence, start) + end = start + len(sentence) + results.append({"sentence": sentence, "start": start, "end": end}) + start = end + + return results + + def _split_document(self, doc: Document) -> List[Document]: + if self.split_by == "sentence" or self.respect_sentence_boundary: + return self._split_by_hanlp_sentence(doc) + + if self.split_by == "function" and self.splitting_function is not None: + return self._split_by_function(doc) + + return self._split_by_character(doc) + + def _concatenate_sentences_based_on_word_amount( + self, sentences: List[str], split_length: int, split_overlap: int, granularity: str + ) -> Tuple[List[str], List[int], List[int]]: + """ + Groups the sentences into chunks of `split_length` words while respecting sentence boundaries. + + This function is only used when splitting by `word` and `respect_sentence_boundary` is set to `True`, i.e.: + with HanLP sentence tokenizer. + + :param sentences: The list of sentences to split. + :param split_length: The maximum number of words in each split. + :param split_overlap: The number of overlapping words in each split. + :returns: A tuple containing the concatenated sentences, the start page numbers, and the start indices. + """ + + # chunk information + chunk_word_count = 0 + chunk_starting_page_number = 1 + chunk_start_idx = 0 + current_chunk: List[str] = [] + + # output lists + split_start_page_numbers = [] + list_of_splits: List[List[str]] = [] + split_start_indices = [] + + for sentence_idx, sentence in enumerate(sentences): + current_chunk.append(sentence) + chunk_word_count += len(self.chinese_tokenizer(sentence)) + next_sentence_word_count = ( + len(self.chinese_tokenizer(sentences[sentence_idx + 1])) if sentence_idx < len(sentences) - 1 else 0 + ) + + # Number of words in the current chunk plus the next sentence is larger than the split_length, + # or we reached the last sentence + if (chunk_word_count + next_sentence_word_count) > split_length or sentence_idx == len(sentences) - 1: + # Save current chunk and start a new one + list_of_splits.append(current_chunk) + split_start_page_numbers.append(chunk_starting_page_number) + split_start_indices.append(chunk_start_idx) + + # Get the number of sentences that overlap with the next chunk + num_sentences_to_keep = self._number_of_sentences_to_keep( + sentences=current_chunk, + split_length=split_length, + split_overlap=split_overlap, + ) + # Set up information for the new chunk + if num_sentences_to_keep > 0: + # Processed sentences are the ones that are not overlapping with the next chunk + processed_sentences = current_chunk[:-num_sentences_to_keep] + chunk_starting_page_number += sum(sent.count("\f") for sent in processed_sentences) + chunk_start_idx += len("".join(processed_sentences)) + + # Next chunk starts with the sentences that were overlapping with the previous chunk + current_chunk = current_chunk[-num_sentences_to_keep:] + chunk_word_count = sum(len(s.split()) for s in current_chunk) + else: + # Here processed_sentences is the same as current_chunk since there is no overlap + chunk_starting_page_number += sum(sent.count("\f") for sent in current_chunk) + chunk_start_idx += len("".join(current_chunk)) + current_chunk = [] + chunk_word_count = 0 + + # Concatenate the sentences together within each split + text_splits = [] + for split in list_of_splits: + text = "".join(split) + if len(text) > 0: + text_splits.append(text) + + return text_splits, split_start_page_numbers, split_start_indices + + def _split_by_hanlp_sentence(self, doc: Document) -> List[Document]: + """ + Split Chinese text into sentences. + + :param doc: The document to split. + :return: A list of split documents. + """ + if doc.content is None: + return [] + + split_docs = [] + result = self.chinese_sentence_split(doc.content) + units = [sentence["sentence"] for sentence in result] + + if self.respect_sentence_boundary: + text_splits, splits_pages, splits_start_idxs = self._concatenate_sentences_based_on_word_amount( + sentences=units, + split_length=self.split_length, + split_overlap=self.split_overlap, + granularity=self.granularity, + ) + else: + text_splits, splits_pages, splits_start_idxs = self._concatenate_units( + elements=units, + split_length=self.split_length, + split_overlap=self.split_overlap, + split_threshold=self.split_threshold, + ) + metadata = deepcopy(doc.meta) + metadata["source_id"] = doc.id + split_docs += self._create_docs_from_splits( + text_splits=text_splits, splits_pages=splits_pages, splits_start_idxs=splits_start_idxs, meta=metadata + ) + + return split_docs + + def _concatenate_units( + self, elements: List[str], split_length: int, split_overlap: int, split_threshold: int + ) -> Tuple[List[str], List[int], List[int]]: + """ + Concatenates the elements into parts of split_length units. + + Keeps track of the original page number that each element belongs. If the length of the current units is less + than the pre-defined `split_threshold`, it does not create a new split. Instead, it concatenates the current + units with the last split, preventing the creation of excessively small splits. + """ + + # If the text is empty or consists only of whitespace, return empty lists + if not elements or all(not elem.strip() for elem in elements): + return [], [], [] + + # If the text is too short to split, return it as a single chunk + if len(elements) <= split_length: + text = "".join(elements) + return [text], [1], [0] + + # Otherwise, proceed as before + step = split_length - split_overlap + step = max(step, 1) + text_splits: List[str] = [] + splits_pages: List[int] = [] + splits_start_idxs: List[int] = [] + cur_start_idx = 0 + cur_page = 1 + segments = windowed(elements, n=split_length, step=step) + + for seg in segments: + current_units = [unit for unit in seg if unit is not None] + txt = "".join(current_units) + + # check if length of current units is below split_threshold + if len(current_units) < split_threshold and len(text_splits) > 0: + # concatenate the last split with the current one + text_splits[-1] += txt + + # NOTE: This line skips documents that have content="" + elif len(txt) > 0: + text_splits.append(txt) + splits_pages.append(cur_page) + splits_start_idxs.append(cur_start_idx) + + processed_units = current_units[: split_length - split_overlap] + cur_start_idx += len("".join(processed_units)) + + if self.split_by == "page": + num_page_breaks = len(processed_units) + else: + num_page_breaks = sum(processed_unit.count("\f") for processed_unit in processed_units) + + cur_page += num_page_breaks + + return text_splits, splits_pages, splits_start_idxs + + def _create_docs_from_splits( + self, text_splits: List[str], splits_pages: List[int], splits_start_idxs: List[int], meta: Dict[str, Any] + ) -> List[Document]: + """ + Creates Document objects from splits enriching them with page number and the metadata of the original document. + """ + documents: List[Document] = [] + + for i, (txt, split_idx) in enumerate(zip(text_splits, splits_start_idxs)): + copied_meta = deepcopy(meta) + copied_meta["page_number"] = splits_pages[i] + copied_meta["split_id"] = i + copied_meta["split_idx_start"] = split_idx + doc = Document(content=txt, meta=copied_meta) + documents.append(doc) + + if self.split_overlap <= 0: + continue + + doc.meta["_split_overlap"] = [] + + if i == 0: + continue + + doc_start_idx = splits_start_idxs[i] + previous_doc = documents[i - 1] + previous_doc_start_idx = splits_start_idxs[i - 1] + self._add_split_overlap_information(doc, doc_start_idx, previous_doc, previous_doc_start_idx) + + for d in documents: + if d.content is not None: + d.content = d.content.replace(" ", "") + return documents + + @staticmethod + def _add_split_overlap_information( + current_doc: Document, current_doc_start_idx: int, previous_doc: Document, previous_doc_start_idx: int + ) -> None: + """ + Adds split overlap information to the current and previous Document's meta. + + :param current_doc: The Document that is being split. + :param current_doc_start_idx: The starting index of the current Document. + :param previous_doc: The Document that was split before the current Document. + :param previous_doc_start_idx: The starting index of the previous Document. + """ + if previous_doc.content is None or current_doc.content is None: + return + + overlapping_range = (current_doc_start_idx - previous_doc_start_idx, len(previous_doc.content)) + + if overlapping_range[0] < overlapping_range[1]: + overlapping_str = previous_doc.content[overlapping_range[0] : overlapping_range[1]] + + if current_doc.content.startswith(overlapping_str): + # add split overlap information to this Document regarding the previous Document + current_doc.meta["_split_overlap"].append({"doc_id": previous_doc.id, "range": overlapping_range}) + + # add split overlap information to previous Document regarding this Document + overlapping_range = (0, overlapping_range[1] - overlapping_range[0]) + previous_doc.meta["_split_overlap"].append({"doc_id": current_doc.id, "range": overlapping_range}) + + def _number_of_sentences_to_keep(self, sentences: List[str], split_length: int, split_overlap: int) -> int: + """ + Returns the number of sentences to keep in the next chunk based on the `split_overlap` and `split_length`. + + :param sentences: The list of sentences to split. + :param split_length: The maximum number of words in each split. + :param split_overlap: The number of overlapping words in each split. + :returns: The number of sentences to keep in the next chunk. + """ + # If the split_overlap is 0, we don't need to keep any sentences + if split_overlap == 0: + return 0 + + num_sentences_to_keep = 0 + num_words = 0 + + for sent in reversed(sentences[1:]): + num_words += len(self.chinese_tokenizer(sent)) + # If the number of words is larger than the split_length then don't add any more sentences + if num_words > split_length: + break + num_sentences_to_keep += 1 + if num_words > split_overlap: + break + return num_sentences_to_keep + + def _split_by_function(self, doc: Document) -> List[Document]: + """ + Split a document using a custom splitting function. + + :param doc: The document to split. + :return: A list of split documents. + """ + if doc.content is None: + return [] + + if self.splitting_function is None: + msg = "No splitting function provided." + raise ValueError(msg) + + splits = self.splitting_function(doc.content) + if not isinstance(splits, list): + msg = "The splitting function must return a list of strings." + raise ValueError(msg) + + metadata = deepcopy(doc.meta) + metadata["source_id"] = doc.id + + return self._create_docs_from_splits( + text_splits=splits, + splits_pages=[1] * len(splits), + splits_start_idxs=[0] * len(splits), + meta=metadata, + ) + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + """ + serialized = default_to_dict( + self, + split_by=self.split_by, + split_length=self.split_length, + split_overlap=self.split_overlap, + split_threshold=self.split_threshold, + respect_sentence_boundary=self.respect_sentence_boundary, + granularity=self.granularity, + ) + if self.splitting_function: + serialized["init_parameters"]["splitting_function"] = serialize_callable(self.splitting_function) + return serialized + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "ChineseDocumentSplitter": + """ + Deserializes the component from a dictionary. + """ + init_params = data.get("init_parameters", {}) + + splitting_function = init_params.get("splitting_function", None) + if splitting_function: + init_params["splitting_function"] = deserialize_callable(splitting_function) + + return default_from_dict(cls, data) diff --git a/integrations/hanlp/src/haystack_integrations/components/preprocessors/py.typed b/integrations/hanlp/src/haystack_integrations/components/preprocessors/py.typed new file mode 100644 index 000000000..e69de29bb diff --git a/integrations/hanlp/tests/__init__.py b/integrations/hanlp/tests/__init__.py new file mode 100644 index 000000000..d391382c6 --- /dev/null +++ b/integrations/hanlp/tests/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2025-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/integrations/hanlp/tests/test_chinese_document_splitter.py b/integrations/hanlp/tests/test_chinese_document_splitter.py new file mode 100644 index 000000000..6f1844817 --- /dev/null +++ b/integrations/hanlp/tests/test_chinese_document_splitter.py @@ -0,0 +1,260 @@ +# SPDX-FileCopyrightText: 2025-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +import pytest +from haystack import Document +from haystack.utils import deserialize_callable, serialize_callable + +from haystack_integrations.components.preprocessors.hanlp import ChineseDocumentSplitter + + +# custom split function for testing +def custom_split(text: str) -> list[str]: + return text.split(".") + + +class TestChineseDocumentSplitter: + @pytest.fixture + def sample_text(self) -> str: + return ( + "这是第一句话,也是故事的开端,紧接着是第二句话,渐渐引出了背景;随后,翻开新/f的一页," + "我们读到了这一页的第一句话,继续延展出情节的发展,直到这页的第二句话将整段文字温柔地收束于平静之中。" + ) + + def test_to_dict(self): + """ + Test the to_dict method of the DocumentSplitter class. + """ + splitter = ChineseDocumentSplitter(split_by="word", split_length=10, split_overlap=2, split_threshold=5) + serialized = splitter.to_dict() + + expected_type = ( + "haystack_integrations.components.preprocessors.hanlp.chinese_document_splitter.ChineseDocumentSplitter" + ) + assert serialized["type"] == expected_type + assert serialized["init_parameters"]["split_by"] == "word" + assert serialized["init_parameters"]["split_length"] == 10 + assert serialized["init_parameters"]["split_overlap"] == 2 + assert serialized["init_parameters"]["split_threshold"] == 5 + assert "splitting_function" not in serialized["init_parameters"] + + def test_to_dict_with_splitting_function(self): + """ + Test the to_dict method of the DocumentSplitter class when a custom splitting function is provided. + """ + + splitter = ChineseDocumentSplitter(split_by="function", splitting_function=custom_split) + serialized = splitter.to_dict() + + expected_type = ( + "haystack_integrations.components.preprocessors.hanlp.chinese_document_splitter.ChineseDocumentSplitter" + ) + assert serialized["type"] == expected_type + assert serialized["init_parameters"]["split_by"] == "function" + assert "splitting_function" in serialized["init_parameters"] + assert callable(deserialize_callable(serialized["init_parameters"]["splitting_function"])) + + def test_from_dict(self): + """ + Test the from_dict class method of the DocumentSplitter class. + """ + data = { + "type": ( + "haystack_integrations.components.preprocessors.hanlp.chinese_document_splitter.ChineseDocumentSplitter" + ), + "init_parameters": {"split_by": "word", "split_length": 10, "split_overlap": 2, "split_threshold": 5}, + } + splitter = ChineseDocumentSplitter.from_dict(data) + + assert splitter.split_by == "word" + assert splitter.split_length == 10 + assert splitter.split_overlap == 2 + assert splitter.split_threshold == 5 + assert splitter.splitting_function is None + + def test_from_dict_with_splitting_function(self): + """ + Test the from_dict class method of the DocumentSplitter class when a custom splitting function is provided. + """ + + data = { + "type": ( + "haystack_integrations.components.preprocessors.hanlp.chinese_document_splitter.ChineseDocumentSplitter" + ), + "init_parameters": {"split_by": "function", "splitting_function": serialize_callable(custom_split)}, + } + splitter = ChineseDocumentSplitter.from_dict(data) + + assert splitter.split_by == "function" + assert callable(splitter.splitting_function) + assert splitter.splitting_function("a.b.c") == ["a", "b", "c"] + + @pytest.mark.integration + def test_empty_list(self): + splitter = ChineseDocumentSplitter() + splitter.warm_up() + results = splitter.run(documents=[]) + assert results == {"documents": []} + + @pytest.mark.integration + def test_empty_document(self): + splitter = ChineseDocumentSplitter() + documents = [Document(content="")] + splitter.warm_up() + results = splitter.run(documents=documents) + assert results == {"documents": []} + + @pytest.mark.integration + def test_whitespace_only_document(self): + splitter = ChineseDocumentSplitter() + documents = [Document(content=" ")] + splitter.warm_up() + results = splitter.run(documents=documents) + assert len(results["documents"]) == 0 + + @pytest.mark.integration + def test_metadata_copied_to_split_documents(self): + documents = [ + Document(content="这是测试文本。", meta={"name": "doc 0"}), + Document(content="这是另一个测试文本。", meta={"name": "doc 1"}), + ] + splitter = ChineseDocumentSplitter(split_by="word", split_length=5, split_overlap=2) + splitter.warm_up() + result = splitter.run(documents=documents) + assert len(result["documents"]) == 2 + for doc, split_doc in zip(documents, result["documents"]): + assert doc.meta.items() <= split_doc.meta.items() + + @pytest.mark.integration + def test_source_id_stored_in_metadata(self): + documents = [ + Document(content="这是第一个测试文本。"), + Document(content="这是第二个测试文本。"), + ] + splitter = ChineseDocumentSplitter(split_by="word", split_length=5, split_overlap=2) + splitter.warm_up() + result = splitter.run(documents=documents) + assert len(result["documents"]) == 2 + for doc, split_doc in zip(documents, result["documents"]): + assert doc.id == split_doc.meta["source_id"] + + @pytest.mark.integration + def test_split_by_word(self, sample_text): + splitter = ChineseDocumentSplitter(split_by="word", granularity="coarse", split_length=5, split_overlap=0) + splitter.warm_up() + result = splitter.run(documents=[Document(content=sample_text)]) + docs = result["documents"] + assert all(isinstance(doc, Document) for doc in docs) + expected_lengths = [9, 9, 8, 8, 6, 6, 6, 8, 8, 6, 7, 8, 5] + actual_lengths = [len(doc.content) for doc in docs] + assert actual_lengths == expected_lengths + + @pytest.mark.integration + def test_split_by_sentence(self, sample_text): + splitter = ChineseDocumentSplitter(split_by="sentence", granularity="coarse", split_length=10, split_overlap=0) + splitter.warm_up() + result = splitter.run(documents=[Document(content=sample_text)]) + docs = result["documents"] + assert all(isinstance(doc, Document) for doc in docs), "All docs should be instances of Document" + assert all(doc.content != "" for doc in docs), "All docs should have content" + assert docs[-1].content.endswith("。"), "Last chunk should end with '。'" + + @pytest.mark.integration + def test_respect_sentence_boundary(self): + doc = Document( + content="这是第一句话,这是第二句话,这是第三句话。" + "这是第四句话,这是第五句话,这是第六句话!" + "这是第七句话,这是第八句话,这是第九句话?" + ) + splitter = ChineseDocumentSplitter( + split_by="word", split_length=10, split_overlap=3, respect_sentence_boundary=True + ) + splitter.warm_up() + result = splitter.run(documents=[doc]) + docs = result["documents"] + + assert len(docs) == 3 + assert all(doc.content.endswith(("。", "!", "?")) for doc in docs), "Sentence was cut off!" + + @pytest.mark.integration + def test_overlap_chunks_with_long_text(self): + doc = Document( + content="月光轻轻洒落,林中传来阵阵狼嚎,夜色悄然笼罩一切。" + "树叶在微风中沙沙作响,影子在地面上摇曳不定。" + "一只猫头鹰静静地眨了眨眼,从枝头注视着四周……" + "远处的小溪哗啦啦地流淌,仿佛在向石头倾诉着什么。" + "“咔嚓”一声,某处的树枝突然断裂,然后恢复了寂静。" + "空气中弥漫着松树与湿土的气息,令人心安。" + "一只狐狸悄然出现,又迅速消失在灌木丛中。" + "天上的星星闪烁着,仿佛在诉说古老的故事。" + "时间仿佛停滞了……" + "万物静候,聆听着夜的呼吸!" + ) + + splitter = ChineseDocumentSplitter(split_by="word", split_length=30, split_overlap=10, granularity="coarse") + splitter.warm_up() + result = splitter.run(documents=[doc]) + docs = result["documents"] + assert len(docs) == 6 + expected_lengths = [48, 46, 47, 45, 46, 47] + actual_lengths = [len(doc.content) for doc in docs] + assert actual_lengths == expected_lengths + + def has_any_overlap(suffix: str, prefix: str) -> bool: + """ + Check if suffix and prefix have at least one continuous overlapping character sequence. + Tries from the longest possible overlap down to 1 character. + Returns True if any overlap found. + """ + max_check_len = min(len(suffix), len(prefix)) + for length in range(max_check_len, 0, -1): + if suffix[-length:] == prefix[:length]: + return True + return False + + for i in range(1, len(docs)): + prev_chunk = docs[i - 1].content + curr_chunk = docs[i].content + + # Take last 20 chars of prev chunk and first 20 chars of current chunk to check overlap + overlap_prev = prev_chunk[-20:] + overlap_curr = curr_chunk[:20] + + assert has_any_overlap(overlap_prev, overlap_curr), ( + f"Chunks {i} and {i + 1} do not overlap. " + f"Tail (up to 20 chars): '{overlap_prev}' vs Head (up to 20 chars): '{overlap_curr}'" + ) + + def test_validate_init_parameters(self): + ChineseDocumentSplitter._validate_init_parameters( + split_by="word", + split_length=1000, + split_overlap=200, + split_threshold=0, + granularity="coarse", + ) + + with pytest.raises(ValueError, match="split_length must be positive"): + ChineseDocumentSplitter._validate_init_parameters(split_length=0) + + with pytest.raises(ValueError, match="split_overlap must be non-negative"): + ChineseDocumentSplitter._validate_init_parameters(split_overlap=-1) + + with pytest.raises(ValueError, match="split_overlap must be less than split_length"): + ChineseDocumentSplitter._validate_init_parameters(split_overlap=1000, split_length=500) + + with pytest.raises(ValueError, match="split_threshold must be non-negative"): + ChineseDocumentSplitter._validate_init_parameters(split_threshold=-1) + + with pytest.raises(ValueError, match="split_threshold must be less than split_length"): + ChineseDocumentSplitter._validate_init_parameters(split_threshold=1001, split_length=1000) + + with pytest.raises( + ValueError, + match="split_by must be one of 'word', 'sentence', 'passage', 'page', 'line', 'period', 'function'", + ): + ChineseDocumentSplitter._validate_init_parameters(split_by="invalid") + + with pytest.raises(ValueError, match="granularity must be one of 'coarse', 'fine'"): + ChineseDocumentSplitter._validate_init_parameters(granularity="invalid")