From a1f30c728c08781961c5e3098bbe3fb0a754966c Mon Sep 17 00:00:00 2001 From: mc112611 <307267954@qq.com> Date: Thu, 29 May 2025 16:36:33 +0800 Subject: [PATCH 01/34] Add Chinese DocumentSplitter support with examples --- .../test_chinese_document_spliter.py | 372 ++++++++++++++++++ 1 file changed, 372 insertions(+) create mode 100644 haystack/components/preprocessors/test_chinese_document_spliter.py diff --git a/haystack/components/preprocessors/test_chinese_document_spliter.py b/haystack/components/preprocessors/test_chinese_document_spliter.py new file mode 100644 index 000000000..c9b54ec54 --- /dev/null +++ b/haystack/components/preprocessors/test_chinese_document_spliter.py @@ -0,0 +1,372 @@ +''' +haystack-ai == 2.12.1 + +''' + + +from haystack.components.preprocessors import DocumentSplitter +from copy import deepcopy +from typing import Any, Callable, Dict, List, Literal, Optional, Tuple + +from more_itertools import windowed +import hanlp +from haystack import Document, component, logging +from haystack.components.preprocessors.sentence_tokenizer import Language, SentenceSplitter, nltk_imports +from haystack.core.serialization import default_from_dict, default_to_dict +from haystack.utils import deserialize_callable, serialize_callable + +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"} +chinese_tokenizer_coarse = hanlp.load( + hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH) +chinese_tokenizer_fine = hanlp.load(hanlp.pretrained.tok.FINE_ELECTRA_SMALL_ZH) +# 加载中文的句子切分器 +split_sent = hanlp.load(hanlp.pretrained.eos.UD_CTB_EOS_MUL) + + +@component +class chinese_DocumentSpliter(DocumentSplitter): + + def __init__(self, *args, particle_size: Literal["coarse", "fine"] = "coarse", **kwargs): + super(chinese_DocumentSpliter, self).__init__(*args, **kwargs) + + # coarse代表粗颗粒度中文分词,fine代表细颗粒度分词,默认为粗颗粒度分词 + # 'coarse' represents coarse granularity Chinese word segmentation, 'fine' represents fine granularity word segmentation, default is coarse granularity word segmentation + self.particle_size = particle_size + # self.chinese_tokenizer_coarse = hanlp.load(hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH) + # self.chinese_tokenizer_fine = 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) -> List[Document]: + split_at = _CHARACTER_SPLIT_BY_MAPPING[self.split_by] + if self.language == 'zh' and self.particle_size == "coarse": + units = chinese_tokenizer_coarse(doc.content) + + if self.language == 'zh' and self.particle_size == "fine": + units = chinese_tokenizer_fine(doc.content) + if self.language == 'en': + units = doc.content.split(split_at) + # Add the delimiter back to all units except the last one + 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 + ) + + # 定义一个函数用于处理中文分句 + def chinese_sentence_split(self, text: str) -> list: + # 分句 + sentences = split_sent(text) + + # 整理格式 + results = [] + start = 0 + for sentence in sentences: + start = text.find(sentence, start) + end = start + len(sentence) + results.append({ + 'sentence': sentence + '\n', + '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_nltk_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) + + @staticmethod + def _concatenate_sentences_based_on_word_amount( + sentences: List[str], split_length: int, split_overlap: int, language: str, particle_size: 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 NLTK 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 = [] + # chinese_tokenizer_coarse = hanlp.load(hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH) + # chinese_tokenizer_fine = hanlp.load(hanlp.pretrained.tok.FINE_ELECTRA_SMALL_ZH) + for sentence_idx, sentence in enumerate(sentences): + current_chunk.append(sentence) + if language == 'zh' and particle_size == "coarse": + chunk_word_count += len(chinese_tokenizer_coarse(sentence)) + next_sentence_word_count = ( + len(chinese_tokenizer_coarse( + sentences[sentence_idx + 1])) if sentence_idx < len(sentences) - 1 else 0 + ) + if language == 'zh' and particle_size == "fine": + chunk_word_count += len(chinese_tokenizer_fine(sentence)) + next_sentence_word_count = ( + len(chinese_tokenizer_fine( + 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 = chinese_DocumentSpliter._number_of_sentences_to_keep( + sentences=current_chunk, split_length=split_length, split_overlap=split_overlap, language=language, particle_size=particle_size + ) + # 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 + + # 增加中文句子切分,通过languge == "zh",进行启用 + def _split_by_nltk_sentence(self, doc: Document) -> List[Document]: + split_docs = [] + + if self.language == 'zh': + result = self.chinese_sentence_split(doc.content) + if self.language == 'en': + result = self.sentence_splitter.split_sentences( + doc.content) # type: ignore # None check is done in run() + + 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, language=self.language, + particle_size=self.particle_size) + 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. + """ + + 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=split_length - split_overlap) + + 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: + 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 + ): + """ + 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. + """ + overlapping_range = (current_doc_start_idx - previous_doc_start_idx, + len(previous_doc.content)) # type: ignore + + if overlapping_range[0] < overlapping_range[1]: + # type: ignore + overlapping_str = previous_doc.content[overlapping_range[0]: overlapping_range[1]] + + if current_doc.content.startswith(overlapping_str): # type: ignore + # 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}) + + @staticmethod + def _number_of_sentences_to_keep(sentences: List[str], split_length: int, split_overlap: int, language: str, particle_size: str) -> 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 + # chinese_tokenizer_coarse = hanlp.load(hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH) + # chinese_tokenizer_fine = hanlp.load(hanlp.pretrained.tok.FINE_ELECTRA_SMALL_ZH) + # Next overlapping Document should not start exactly the same as the previous one, so we skip the first sentence + for sent in reversed(sentences[1:]): + if language == 'zh' and particle_size == "coarse": + num_words += len(chinese_tokenizer_coarse(sent)) + # num_words += len(sent.split()) + if language == 'zh' and particle_size == "fine": + num_words += len(chinese_tokenizer_fine(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 + + +if __name__ == "__main__": + + from pprint import pprint + doc = Document(content="""月光轻轻洒落,林中传来阵阵狼嚎,夜色悄然笼罩一切。 + 树叶在微风中沙沙作响,影子在地面上摇曳不定。 + 一只猫头鹰静静地眨了眨眼,从枝头注视着四周…… + 远处的小溪哗啦啦地流淌,仿佛在向石头倾诉着什么。 + “咔嚓”一声,某处的树枝突然断裂,然后恢复了寂静。 + 空气中弥漫着松树与湿土的气息,令人心安。 + 一只狐狸悄然出现,又迅速消失在灌木丛中。 + 天上的星星闪烁着,仿佛在诉说古老的故事。 + 时间仿佛停滞了…… + 万物静候,聆听着夜的呼吸!""") + + # splitter = chinese_DocumentSpliter(split_by="sentence", split_length=3, split_overlap=1, language='zh') + splitter = chinese_DocumentSpliter(split_by="word", split_length=30, split_overlap=3,language='zh',respect_sentence_boundary=False) + splitter.warm_up() + result = splitter.run(documents=[doc]) + + pprint(result) From d4a665f6117d95baec6e45f51ba3852e1e45f9b8 Mon Sep 17 00:00:00 2001 From: mc112611 <307267954@qq.com> Date: Thu, 29 May 2025 17:20:49 +0800 Subject: [PATCH 02/34] fix: update tests and release notes --- .../test_chinese_document_spliter.py | 114 +++++++++--------- 1 file changed, 54 insertions(+), 60 deletions(-) diff --git a/haystack/components/preprocessors/test_chinese_document_spliter.py b/haystack/components/preprocessors/test_chinese_document_spliter.py index c9b54ec54..625d5dc0e 100644 --- a/haystack/components/preprocessors/test_chinese_document_spliter.py +++ b/haystack/components/preprocessors/test_chinese_document_spliter.py @@ -1,8 +1,7 @@ -''' +""" haystack-ai == 2.12.1 -''' - +""" from haystack.components.preprocessors import DocumentSplitter from copy import deepcopy @@ -18,10 +17,8 @@ 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"} -chinese_tokenizer_coarse = hanlp.load( - hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH) +_CHARACTER_SPLIT_BY_MAPPING = {"page": "\f", "passage": "\n\n", "period": ".", "word": " ", "line": "\n"} +chinese_tokenizer_coarse = hanlp.load(hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH) chinese_tokenizer_fine = hanlp.load(hanlp.pretrained.tok.FINE_ELECTRA_SMALL_ZH) # 加载中文的句子切分器 split_sent = hanlp.load(hanlp.pretrained.eos.UD_CTB_EOS_MUL) @@ -29,7 +26,6 @@ @component class chinese_DocumentSpliter(DocumentSplitter): - def __init__(self, *args, particle_size: Literal["coarse", "fine"] = "coarse", **kwargs): super(chinese_DocumentSpliter, self).__init__(*args, **kwargs) @@ -44,12 +40,12 @@ def __init__(self, *args, particle_size: Literal["coarse", "fine"] = "coarse", * def _split_by_character(self, doc) -> List[Document]: split_at = _CHARACTER_SPLIT_BY_MAPPING[self.split_by] - if self.language == 'zh' and self.particle_size == "coarse": + if self.language == "zh" and self.particle_size == "coarse": units = chinese_tokenizer_coarse(doc.content) - if self.language == 'zh' and self.particle_size == "fine": + if self.language == "zh" and self.particle_size == "fine": units = chinese_tokenizer_fine(doc.content) - if self.language == 'en': + if self.language == "en": units = doc.content.split(split_at) # Add the delimiter back to all units except the last one for i in range(len(units) - 1): @@ -74,11 +70,7 @@ def chinese_sentence_split(self, text: str) -> list: for sentence in sentences: start = text.find(sentence, start) end = start + len(sentence) - results.append({ - 'sentence': sentence + '\n', - 'start': start, - 'end': end - }) + results.append({"sentence": sentence + "\n", "start": start, "end": end}) start = end return results @@ -120,17 +112,17 @@ def _concatenate_sentences_based_on_word_amount( # chinese_tokenizer_fine = hanlp.load(hanlp.pretrained.tok.FINE_ELECTRA_SMALL_ZH) for sentence_idx, sentence in enumerate(sentences): current_chunk.append(sentence) - if language == 'zh' and particle_size == "coarse": + if language == "zh" and particle_size == "coarse": chunk_word_count += len(chinese_tokenizer_coarse(sentence)) next_sentence_word_count = ( - len(chinese_tokenizer_coarse( - sentences[sentence_idx + 1])) if sentence_idx < len(sentences) - 1 else 0 + len(chinese_tokenizer_coarse(sentences[sentence_idx + 1])) + if sentence_idx < len(sentences) - 1 + else 0 ) - if language == 'zh' and particle_size == "fine": + if language == "zh" and particle_size == "fine": chunk_word_count += len(chinese_tokenizer_fine(sentence)) next_sentence_word_count = ( - len(chinese_tokenizer_fine( - sentences[sentence_idx + 1])) if sentence_idx < len(sentences) - 1 else 0 + len(chinese_tokenizer_fine(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, @@ -143,24 +135,24 @@ def _concatenate_sentences_based_on_word_amount( # Get the number of sentences that overlap with the next chunk num_sentences_to_keep = chinese_DocumentSpliter._number_of_sentences_to_keep( - sentences=current_chunk, split_length=split_length, split_overlap=split_overlap, language=language, particle_size=particle_size + sentences=current_chunk, + split_length=split_length, + split_overlap=split_overlap, + language=language, + particle_size=particle_size, ) # 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) + 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) + 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_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 @@ -178,18 +170,21 @@ def _concatenate_sentences_based_on_word_amount( def _split_by_nltk_sentence(self, doc: Document) -> List[Document]: split_docs = [] - if self.language == 'zh': + if self.language == "zh": result = self.chinese_sentence_split(doc.content) - if self.language == 'en': - result = self.sentence_splitter.split_sentences( - doc.content) # type: ignore # None check is done in run() + if self.language == "en": + result = self.sentence_splitter.split_sentences(doc.content) # type: ignore # None check is done in run() 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, language=self.language, - particle_size=self.particle_size) + sentences=units, + split_length=self.split_length, + split_overlap=self.split_overlap, + language=self.language, + particle_size=self.particle_size, + ) else: text_splits, splits_pages, splits_start_idxs = self._concatenate_units( elements=units, @@ -221,8 +216,7 @@ def _concatenate_units( splits_start_idxs: List[int] = [] cur_start_idx = 0 cur_page = 1 - segments = windowed(elements, n=split_length, - step=split_length - split_overlap) + segments = windowed(elements, n=split_length, step=split_length - split_overlap) for seg in segments: current_units = [unit for unit in seg if unit is not None] @@ -245,8 +239,7 @@ def _concatenate_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) + num_page_breaks = sum(processed_unit.count("\f") for processed_unit in processed_units) cur_page += num_page_breaks @@ -279,11 +272,10 @@ def _create_docs_from_splits( 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) + self._add_split_overlap_information(doc, doc_start_idx, previous_doc, previous_doc_start_idx) for d in documents: - d.content=d.content.replace(" ","") + d.content = d.content.replace(" ", "") return documents @staticmethod @@ -298,26 +290,24 @@ def _add_split_overlap_information( :param previous_doc: The Document that was split before the current Document. :param previous_doc_start_idx: The starting index of the previous Document. """ - overlapping_range = (current_doc_start_idx - previous_doc_start_idx, - len(previous_doc.content)) # type: ignore + overlapping_range = (current_doc_start_idx - previous_doc_start_idx, len(previous_doc.content)) # type: ignore if overlapping_range[0] < overlapping_range[1]: # type: ignore - overlapping_str = previous_doc.content[overlapping_range[0]: overlapping_range[1]] + overlapping_str = previous_doc.content[overlapping_range[0] : overlapping_range[1]] if current_doc.content.startswith(overlapping_str): # type: ignore # 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}) + 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}) + overlapping_range = (0, overlapping_range[1] - overlapping_range[0]) + previous_doc.meta["_split_overlap"].append({"doc_id": current_doc.id, "range": overlapping_range}) @staticmethod - def _number_of_sentences_to_keep(sentences: List[str], split_length: int, split_overlap: int, language: str, particle_size: str) -> int: + def _number_of_sentences_to_keep( + sentences: List[str], split_length: int, split_overlap: int, language: str, particle_size: str + ) -> int: """ Returns the number of sentences to keep in the next chunk based on the `split_overlap` and `split_length`. @@ -336,10 +326,10 @@ def _number_of_sentences_to_keep(sentences: List[str], split_length: int, split_ # chinese_tokenizer_fine = hanlp.load(hanlp.pretrained.tok.FINE_ELECTRA_SMALL_ZH) # Next overlapping Document should not start exactly the same as the previous one, so we skip the first sentence for sent in reversed(sentences[1:]): - if language == 'zh' and particle_size == "coarse": + if language == "zh" and particle_size == "coarse": num_words += len(chinese_tokenizer_coarse(sent)) # num_words += len(sent.split()) - if language == 'zh' and particle_size == "fine": + if language == "zh" and particle_size == "fine": num_words += len(chinese_tokenizer_fine(sent)) # If the number of words is larger than the split_length then don't add any more sentences if num_words > split_length: @@ -351,9 +341,10 @@ def _number_of_sentences_to_keep(sentences: List[str], split_length: int, split_ if __name__ == "__main__": - from pprint import pprint - doc = Document(content="""月光轻轻洒落,林中传来阵阵狼嚎,夜色悄然笼罩一切。 + + doc = Document( + content="""月光轻轻洒落,林中传来阵阵狼嚎,夜色悄然笼罩一切。 树叶在微风中沙沙作响,影子在地面上摇曳不定。 一只猫头鹰静静地眨了眨眼,从枝头注视着四周…… 远处的小溪哗啦啦地流淌,仿佛在向石头倾诉着什么。 @@ -362,10 +353,13 @@ def _number_of_sentences_to_keep(sentences: List[str], split_length: int, split_ 一只狐狸悄然出现,又迅速消失在灌木丛中。 天上的星星闪烁着,仿佛在诉说古老的故事。 时间仿佛停滞了…… - 万物静候,聆听着夜的呼吸!""") + 万物静候,聆听着夜的呼吸!""" + ) # splitter = chinese_DocumentSpliter(split_by="sentence", split_length=3, split_overlap=1, language='zh') - splitter = chinese_DocumentSpliter(split_by="word", split_length=30, split_overlap=3,language='zh',respect_sentence_boundary=False) + splitter = chinese_DocumentSpliter( + split_by="word", split_length=30, split_overlap=3, language="zh", respect_sentence_boundary=False + ) splitter.warm_up() result = splitter.run(documents=[doc]) From e9ccf11259f09ea286cfc52b40f6e803a299d387 Mon Sep 17 00:00:00 2001 From: mc112611 <307267954@qq.com> Date: Tue, 3 Jun 2025 19:28:29 +0800 Subject: [PATCH 03/34] Fix according to review: - Removed notebook and original_pipeline.png - Added release note YAML file in notes/ - Reverted config.yaml - Implemented lazy import for hanlp - Removed main guard block from module --- ...spliter.py => chinese_document_spliter.py} | 134 ++++++++---------- 1 file changed, 61 insertions(+), 73 deletions(-) rename haystack/components/preprocessors/{test_chinese_document_spliter.py => chinese_document_spliter.py} (76%) diff --git a/haystack/components/preprocessors/test_chinese_document_spliter.py b/haystack/components/preprocessors/chinese_document_spliter.py similarity index 76% rename from haystack/components/preprocessors/test_chinese_document_spliter.py rename to haystack/components/preprocessors/chinese_document_spliter.py index 625d5dc0e..321664195 100644 --- a/haystack/components/preprocessors/test_chinese_document_spliter.py +++ b/haystack/components/preprocessors/chinese_document_spliter.py @@ -1,24 +1,30 @@ -""" -haystack-ai == 2.12.1 +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 -""" from haystack.components.preprocessors import DocumentSplitter from copy import deepcopy from typing import Any, Callable, Dict, List, Literal, Optional, Tuple +from haystack.lazy_imports import LazyImport from more_itertools import windowed -import hanlp from haystack import Document, component, logging from haystack.components.preprocessors.sentence_tokenizer import Language, SentenceSplitter, nltk_imports from haystack.core.serialization import default_from_dict, default_to_dict from haystack.utils import deserialize_callable, serialize_callable +with LazyImport("Run 'pip install hanlp'") as hanlp: + 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"} -chinese_tokenizer_coarse = hanlp.load(hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH) +_CHARACTER_SPLIT_BY_MAPPING = { + "page": "\f", "passage": "\n\n", "period": ".", "word": " ", "line": "\n"} +chinese_tokenizer_coarse = hanlp.load( + hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH) chinese_tokenizer_fine = hanlp.load(hanlp.pretrained.tok.FINE_ELECTRA_SMALL_ZH) # 加载中文的句子切分器 split_sent = hanlp.load(hanlp.pretrained.eos.UD_CTB_EOS_MUL) @@ -26,6 +32,7 @@ @component class chinese_DocumentSpliter(DocumentSplitter): + def __init__(self, *args, particle_size: Literal["coarse", "fine"] = "coarse", **kwargs): super(chinese_DocumentSpliter, self).__init__(*args, **kwargs) @@ -40,12 +47,12 @@ def __init__(self, *args, particle_size: Literal["coarse", "fine"] = "coarse", * def _split_by_character(self, doc) -> List[Document]: split_at = _CHARACTER_SPLIT_BY_MAPPING[self.split_by] - if self.language == "zh" and self.particle_size == "coarse": + if self.language == 'zh' and self.particle_size == "coarse": units = chinese_tokenizer_coarse(doc.content) - if self.language == "zh" and self.particle_size == "fine": + if self.language == 'zh' and self.particle_size == "fine": units = chinese_tokenizer_fine(doc.content) - if self.language == "en": + if self.language == 'en': units = doc.content.split(split_at) # Add the delimiter back to all units except the last one for i in range(len(units) - 1): @@ -70,7 +77,11 @@ def chinese_sentence_split(self, text: str) -> list: for sentence in sentences: start = text.find(sentence, start) end = start + len(sentence) - results.append({"sentence": sentence + "\n", "start": start, "end": end}) + results.append({ + 'sentence': sentence + '\n', + 'start': start, + 'end': end + }) start = end return results @@ -112,17 +123,17 @@ def _concatenate_sentences_based_on_word_amount( # chinese_tokenizer_fine = hanlp.load(hanlp.pretrained.tok.FINE_ELECTRA_SMALL_ZH) for sentence_idx, sentence in enumerate(sentences): current_chunk.append(sentence) - if language == "zh" and particle_size == "coarse": + if language == 'zh' and particle_size == "coarse": chunk_word_count += len(chinese_tokenizer_coarse(sentence)) next_sentence_word_count = ( - len(chinese_tokenizer_coarse(sentences[sentence_idx + 1])) - if sentence_idx < len(sentences) - 1 - else 0 + len(chinese_tokenizer_coarse( + sentences[sentence_idx + 1])) if sentence_idx < len(sentences) - 1 else 0 ) - if language == "zh" and particle_size == "fine": + if language == 'zh' and particle_size == "fine": chunk_word_count += len(chinese_tokenizer_fine(sentence)) next_sentence_word_count = ( - len(chinese_tokenizer_fine(sentences[sentence_idx + 1])) if sentence_idx < len(sentences) - 1 else 0 + len(chinese_tokenizer_fine( + 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, @@ -135,24 +146,24 @@ def _concatenate_sentences_based_on_word_amount( # Get the number of sentences that overlap with the next chunk num_sentences_to_keep = chinese_DocumentSpliter._number_of_sentences_to_keep( - sentences=current_chunk, - split_length=split_length, - split_overlap=split_overlap, - language=language, - particle_size=particle_size, + sentences=current_chunk, split_length=split_length, split_overlap=split_overlap, language=language, particle_size=particle_size ) # 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) + 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) + 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_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 @@ -170,21 +181,18 @@ def _concatenate_sentences_based_on_word_amount( def _split_by_nltk_sentence(self, doc: Document) -> List[Document]: split_docs = [] - if self.language == "zh": + if self.language == 'zh': result = self.chinese_sentence_split(doc.content) - if self.language == "en": - result = self.sentence_splitter.split_sentences(doc.content) # type: ignore # None check is done in run() + if self.language == 'en': + result = self.sentence_splitter.split_sentences( + doc.content) # type: ignore # None check is done in run() 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, - language=self.language, - particle_size=self.particle_size, - ) + sentences=units, split_length=self.split_length, split_overlap=self.split_overlap, language=self.language, + particle_size=self.particle_size) else: text_splits, splits_pages, splits_start_idxs = self._concatenate_units( elements=units, @@ -216,7 +224,8 @@ def _concatenate_units( splits_start_idxs: List[int] = [] cur_start_idx = 0 cur_page = 1 - segments = windowed(elements, n=split_length, step=split_length - split_overlap) + segments = windowed(elements, n=split_length, + step=split_length - split_overlap) for seg in segments: current_units = [unit for unit in seg if unit is not None] @@ -239,7 +248,8 @@ def _concatenate_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) + num_page_breaks = sum(processed_unit.count("\f") + for processed_unit in processed_units) cur_page += num_page_breaks @@ -272,10 +282,11 @@ def _create_docs_from_splits( 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) + self._add_split_overlap_information( + doc, doc_start_idx, previous_doc, previous_doc_start_idx) for d in documents: - d.content = d.content.replace(" ", "") + d.content=d.content.replace(" ","") return documents @staticmethod @@ -290,24 +301,26 @@ def _add_split_overlap_information( :param previous_doc: The Document that was split before the current Document. :param previous_doc_start_idx: The starting index of the previous Document. """ - overlapping_range = (current_doc_start_idx - previous_doc_start_idx, len(previous_doc.content)) # type: ignore + overlapping_range = (current_doc_start_idx - previous_doc_start_idx, + len(previous_doc.content)) # type: ignore if overlapping_range[0] < overlapping_range[1]: # type: ignore - overlapping_str = previous_doc.content[overlapping_range[0] : overlapping_range[1]] + overlapping_str = previous_doc.content[overlapping_range[0]: overlapping_range[1]] if current_doc.content.startswith(overlapping_str): # type: ignore # 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}) + 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}) + overlapping_range = ( + 0, overlapping_range[1] - overlapping_range[0]) + previous_doc.meta["_split_overlap"].append( + {"doc_id": current_doc.id, "range": overlapping_range}) @staticmethod - def _number_of_sentences_to_keep( - sentences: List[str], split_length: int, split_overlap: int, language: str, particle_size: str - ) -> int: + def _number_of_sentences_to_keep(sentences: List[str], split_length: int, split_overlap: int, language: str, particle_size: str) -> int: """ Returns the number of sentences to keep in the next chunk based on the `split_overlap` and `split_length`. @@ -326,10 +339,10 @@ def _number_of_sentences_to_keep( # chinese_tokenizer_fine = hanlp.load(hanlp.pretrained.tok.FINE_ELECTRA_SMALL_ZH) # Next overlapping Document should not start exactly the same as the previous one, so we skip the first sentence for sent in reversed(sentences[1:]): - if language == "zh" and particle_size == "coarse": + if language == 'zh' and particle_size == "coarse": num_words += len(chinese_tokenizer_coarse(sent)) # num_words += len(sent.split()) - if language == "zh" and particle_size == "fine": + if language == 'zh' and particle_size == "fine": num_words += len(chinese_tokenizer_fine(sent)) # If the number of words is larger than the split_length then don't add any more sentences if num_words > split_length: @@ -339,28 +352,3 @@ def _number_of_sentences_to_keep( break return num_sentences_to_keep - -if __name__ == "__main__": - from pprint import pprint - - doc = Document( - content="""月光轻轻洒落,林中传来阵阵狼嚎,夜色悄然笼罩一切。 - 树叶在微风中沙沙作响,影子在地面上摇曳不定。 - 一只猫头鹰静静地眨了眨眼,从枝头注视着四周…… - 远处的小溪哗啦啦地流淌,仿佛在向石头倾诉着什么。 - “咔嚓”一声,某处的树枝突然断裂,然后恢复了寂静。 - 空气中弥漫着松树与湿土的气息,令人心安。 - 一只狐狸悄然出现,又迅速消失在灌木丛中。 - 天上的星星闪烁着,仿佛在诉说古老的故事。 - 时间仿佛停滞了…… - 万物静候,聆听着夜的呼吸!""" - ) - - # splitter = chinese_DocumentSpliter(split_by="sentence", split_length=3, split_overlap=1, language='zh') - splitter = chinese_DocumentSpliter( - split_by="word", split_length=30, split_overlap=3, language="zh", respect_sentence_boundary=False - ) - splitter.warm_up() - result = splitter.run(documents=[doc]) - - pprint(result) From 99eb3350b709e8732725dbc9cb36b523dedf4dea Mon Sep 17 00:00:00 2001 From: "David S. Batista" Date: Wed, 4 Jun 2025 17:36:55 +0200 Subject: [PATCH 04/34] cleaning up --- .../preprocessors/chinese_document_spliter.py | 140 +++++++++--------- 1 file changed, 69 insertions(+), 71 deletions(-) diff --git a/haystack/components/preprocessors/chinese_document_spliter.py b/haystack/components/preprocessors/chinese_document_spliter.py index 321664195..0fba3a7e9 100644 --- a/haystack/components/preprocessors/chinese_document_spliter.py +++ b/haystack/components/preprocessors/chinese_document_spliter.py @@ -2,42 +2,39 @@ # # SPDX-License-Identifier: Apache-2.0 - -from haystack.components.preprocessors import DocumentSplitter from copy import deepcopy -from typing import Any, Callable, Dict, List, Literal, Optional, Tuple -from haystack.lazy_imports import LazyImport +from typing import Any, Dict, List, Literal, Tuple from more_itertools import windowed + from haystack import Document, component, logging -from haystack.components.preprocessors.sentence_tokenizer import Language, SentenceSplitter, nltk_imports -from haystack.core.serialization import default_from_dict, default_to_dict -from haystack.utils import deserialize_callable, serialize_callable -with LazyImport("Run 'pip install hanlp'") as hanlp: - import hanlp +from haystack.components.preprocessors import DocumentSplitter +from haystack.lazy_imports import LazyImport +with LazyImport("Run 'pip install hanlp'") as hanlp_import: + 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"} -chinese_tokenizer_coarse = hanlp.load( - hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH) +_CHARACTER_SPLIT_BY_MAPPING = {"page": "\f", "passage": "\n\n", "period": ".", "word": " ", "line": "\n"} + +hanlp_import.check() + +chinese_tokenizer_coarse = hanlp.load(hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH) chinese_tokenizer_fine = hanlp.load(hanlp.pretrained.tok.FINE_ELECTRA_SMALL_ZH) -# 加载中文的句子切分器 -split_sent = hanlp.load(hanlp.pretrained.eos.UD_CTB_EOS_MUL) +split_sent = hanlp.load(hanlp.pretrained.eos.UD_CTB_EOS_MUL) # 加载中文的句子切分器 @component -class chinese_DocumentSpliter(DocumentSplitter): - +class ChineseDocumentspliter(DocumentSplitter): def __init__(self, *args, particle_size: Literal["coarse", "fine"] = "coarse", **kwargs): - super(chinese_DocumentSpliter, self).__init__(*args, **kwargs) + super(ChineseDocumentspliter, self).__init__(*args, **kwargs) # coarse代表粗颗粒度中文分词,fine代表细颗粒度分词,默认为粗颗粒度分词 - # 'coarse' represents coarse granularity Chinese word segmentation, 'fine' represents fine granularity word segmentation, default is coarse granularity word segmentation + # 'coarse' represents coarse granularity Chinese word segmentation, 'fine' represents fine granularity word + # segmentation, default is coarse granularity word segmentation self.particle_size = particle_size # self.chinese_tokenizer_coarse = hanlp.load(hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH) # self.chinese_tokenizer_fine = hanlp.load(hanlp.pretrained.tok.FINE_ELECTRA_SMALL_ZH) @@ -47,12 +44,12 @@ def __init__(self, *args, particle_size: Literal["coarse", "fine"] = "coarse", * def _split_by_character(self, doc) -> List[Document]: split_at = _CHARACTER_SPLIT_BY_MAPPING[self.split_by] - if self.language == 'zh' and self.particle_size == "coarse": + if self.language == "zh" and self.particle_size == "coarse": units = chinese_tokenizer_coarse(doc.content) - if self.language == 'zh' and self.particle_size == "fine": + if self.language == "zh" and self.particle_size == "fine": units = chinese_tokenizer_fine(doc.content) - if self.language == 'en': + if self.language == "en": units = doc.content.split(split_at) # Add the delimiter back to all units except the last one for i in range(len(units) - 1): @@ -67,7 +64,14 @@ def _split_by_character(self, doc) -> List[Document]: ) # 定义一个函数用于处理中文分句 - def chinese_sentence_split(self, text: str) -> list: + @staticmethod + def chinese_sentence_split(text: str) -> list: + """ + Segmentation of Chinese text. + + :param text: The Chinese text to be segmented. + :returns: A list of dictionaries, each containing a sentence and its start and end indices. + """ # 分句 sentences = split_sent(text) @@ -77,11 +81,7 @@ def chinese_sentence_split(self, text: str) -> list: for sentence in sentences: start = text.find(sentence, start) end = start + len(sentence) - results.append({ - 'sentence': sentence + '\n', - 'start': start, - 'end': end - }) + results.append({"sentence": sentence + "\n", "start": start, "end": end}) start = end return results @@ -123,17 +123,17 @@ def _concatenate_sentences_based_on_word_amount( # chinese_tokenizer_fine = hanlp.load(hanlp.pretrained.tok.FINE_ELECTRA_SMALL_ZH) for sentence_idx, sentence in enumerate(sentences): current_chunk.append(sentence) - if language == 'zh' and particle_size == "coarse": + if language == "zh" and particle_size == "coarse": chunk_word_count += len(chinese_tokenizer_coarse(sentence)) next_sentence_word_count = ( - len(chinese_tokenizer_coarse( - sentences[sentence_idx + 1])) if sentence_idx < len(sentences) - 1 else 0 + len(chinese_tokenizer_coarse(sentences[sentence_idx + 1])) + if sentence_idx < len(sentences) - 1 + else 0 ) - if language == 'zh' and particle_size == "fine": + if language == "zh" and particle_size == "fine": chunk_word_count += len(chinese_tokenizer_fine(sentence)) next_sentence_word_count = ( - len(chinese_tokenizer_fine( - sentences[sentence_idx + 1])) if sentence_idx < len(sentences) - 1 else 0 + len(chinese_tokenizer_fine(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, @@ -145,25 +145,25 @@ def _concatenate_sentences_based_on_word_amount( split_start_indices.append(chunk_start_idx) # Get the number of sentences that overlap with the next chunk - num_sentences_to_keep = chinese_DocumentSpliter._number_of_sentences_to_keep( - sentences=current_chunk, split_length=split_length, split_overlap=split_overlap, language=language, particle_size=particle_size + num_sentences_to_keep = ChineseDocumentspliter._number_of_sentences_to_keep( + sentences=current_chunk, + split_length=split_length, + split_overlap=split_overlap, + language=language, + particle_size=particle_size, ) # 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) + 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) + 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_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 @@ -181,18 +181,21 @@ def _concatenate_sentences_based_on_word_amount( def _split_by_nltk_sentence(self, doc: Document) -> List[Document]: split_docs = [] - if self.language == 'zh': - result = self.chinese_sentence_split(doc.content) - if self.language == 'en': - result = self.sentence_splitter.split_sentences( - doc.content) # type: ignore # None check is done in run() + if self.language == "zh": + result = ChineseDocumentspliter.chinese_sentence_split(doc.content) + if self.language == "en": + result = self.sentence_splitter.split_sentences(doc.content) # type: ignore # None check is done in run() 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, language=self.language, - particle_size=self.particle_size) + sentences=units, + split_length=self.split_length, + split_overlap=self.split_overlap, + language=self.language, + particle_size=self.particle_size, + ) else: text_splits, splits_pages, splits_start_idxs = self._concatenate_units( elements=units, @@ -224,8 +227,7 @@ def _concatenate_units( splits_start_idxs: List[int] = [] cur_start_idx = 0 cur_page = 1 - segments = windowed(elements, n=split_length, - step=split_length - split_overlap) + segments = windowed(elements, n=split_length, step=split_length - split_overlap) for seg in segments: current_units = [unit for unit in seg if unit is not None] @@ -248,8 +250,7 @@ def _concatenate_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) + num_page_breaks = sum(processed_unit.count("\f") for processed_unit in processed_units) cur_page += num_page_breaks @@ -282,11 +283,10 @@ def _create_docs_from_splits( 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) + self._add_split_overlap_information(doc, doc_start_idx, previous_doc, previous_doc_start_idx) for d in documents: - d.content=d.content.replace(" ","") + d.content = d.content.replace(" ", "") return documents @staticmethod @@ -301,26 +301,24 @@ def _add_split_overlap_information( :param previous_doc: The Document that was split before the current Document. :param previous_doc_start_idx: The starting index of the previous Document. """ - overlapping_range = (current_doc_start_idx - previous_doc_start_idx, - len(previous_doc.content)) # type: ignore + overlapping_range = (current_doc_start_idx - previous_doc_start_idx, len(previous_doc.content)) # type: ignore if overlapping_range[0] < overlapping_range[1]: # type: ignore - overlapping_str = previous_doc.content[overlapping_range[0]: overlapping_range[1]] + overlapping_str = previous_doc.content[overlapping_range[0] : overlapping_range[1]] if current_doc.content.startswith(overlapping_str): # type: ignore # 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}) + 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}) + overlapping_range = (0, overlapping_range[1] - overlapping_range[0]) + previous_doc.meta["_split_overlap"].append({"doc_id": current_doc.id, "range": overlapping_range}) @staticmethod - def _number_of_sentences_to_keep(sentences: List[str], split_length: int, split_overlap: int, language: str, particle_size: str) -> int: + def _number_of_sentences_to_keep( + sentences: List[str], split_length: int, split_overlap: int, language: str, particle_size: str + ) -> int: """ Returns the number of sentences to keep in the next chunk based on the `split_overlap` and `split_length`. @@ -339,10 +337,10 @@ def _number_of_sentences_to_keep(sentences: List[str], split_length: int, split_ # chinese_tokenizer_fine = hanlp.load(hanlp.pretrained.tok.FINE_ELECTRA_SMALL_ZH) # Next overlapping Document should not start exactly the same as the previous one, so we skip the first sentence for sent in reversed(sentences[1:]): - if language == 'zh' and particle_size == "coarse": + if language == "zh" and particle_size == "coarse": num_words += len(chinese_tokenizer_coarse(sent)) # num_words += len(sent.split()) - if language == 'zh' and particle_size == "fine": + if language == "zh" and particle_size == "fine": num_words += len(chinese_tokenizer_fine(sent)) # If the number of words is larger than the split_length then don't add any more sentences if num_words > split_length: @@ -350,5 +348,5 @@ def _number_of_sentences_to_keep(sentences: List[str], split_length: int, split_ num_sentences_to_keep += 1 if num_words > split_overlap: break - return num_sentences_to_keep + return num_sentences_to_keep From 671ca133a6318b4bf4089ec78d98a4ee1633bfe7 Mon Sep 17 00:00:00 2001 From: "David S. Batista" Date: Wed, 4 Jun 2025 18:00:57 +0200 Subject: [PATCH 05/34] fixing lazy import --- .../preprocessors/chinese_document_spliter.py | 50 +++++++++---------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/haystack/components/preprocessors/chinese_document_spliter.py b/haystack/components/preprocessors/chinese_document_spliter.py index 0fba3a7e9..7306e65d7 100644 --- a/haystack/components/preprocessors/chinese_document_spliter.py +++ b/haystack/components/preprocessors/chinese_document_spliter.py @@ -20,17 +20,11 @@ # 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"} -hanlp_import.check() - -chinese_tokenizer_coarse = hanlp.load(hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH) -chinese_tokenizer_fine = hanlp.load(hanlp.pretrained.tok.FINE_ELECTRA_SMALL_ZH) -split_sent = hanlp.load(hanlp.pretrained.eos.UD_CTB_EOS_MUL) # 加载中文的句子切分器 - @component -class ChineseDocumentspliter(DocumentSplitter): +class ChineseDocumentSplitter(DocumentSplitter): def __init__(self, *args, particle_size: Literal["coarse", "fine"] = "coarse", **kwargs): - super(ChineseDocumentspliter, self).__init__(*args, **kwargs) + super(ChineseDocumentSplitter, self).__init__(*args, **kwargs) # coarse代表粗颗粒度中文分词,fine代表细颗粒度分词,默认为粗颗粒度分词 # 'coarse' represents coarse granularity Chinese word segmentation, 'fine' represents fine granularity word @@ -42,13 +36,19 @@ def __init__(self, *args, particle_size: Literal["coarse", "fine"] = "coarse", * # # 加载中文的句子切分器 # self.split_sent = hanlp.load(hanlp.pretrained.eos.UD_CTB_EOS_MUL) + hanlp_import.check() + + self.chinese_tokenizer_coarse = hanlp.load(hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH) + self.chinese_tokenizer_fine = 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) -> List[Document]: split_at = _CHARACTER_SPLIT_BY_MAPPING[self.split_by] if self.language == "zh" and self.particle_size == "coarse": - units = chinese_tokenizer_coarse(doc.content) + units = self.chinese_tokenizer_coarse(doc.content) if self.language == "zh" and self.particle_size == "fine": - units = chinese_tokenizer_fine(doc.content) + units = self.chinese_tokenizer_fine(doc.content) if self.language == "en": units = doc.content.split(split_at) # Add the delimiter back to all units except the last one @@ -64,8 +64,7 @@ def _split_by_character(self, doc) -> List[Document]: ) # 定义一个函数用于处理中文分句 - @staticmethod - def chinese_sentence_split(text: str) -> list: + def chinese_sentence_split(self, text: str) -> list: """ Segmentation of Chinese text. @@ -73,7 +72,7 @@ def chinese_sentence_split(text: str) -> list: :returns: A list of dictionaries, each containing a sentence and its start and end indices. """ # 分句 - sentences = split_sent(text) + sentences = self.split_sent(text) # 整理格式 results = [] @@ -95,9 +94,8 @@ def _split_document(self, doc: Document) -> List[Document]: return self._split_by_character(doc) - @staticmethod def _concatenate_sentences_based_on_word_amount( - sentences: List[str], split_length: int, split_overlap: int, language: str, particle_size: str + self, sentences: List[str], split_length: int, split_overlap: int, language: str, particle_size: str ) -> Tuple[List[str], List[int], List[int]]: """ Groups the sentences into chunks of `split_length` words while respecting sentence boundaries. @@ -124,16 +122,18 @@ def _concatenate_sentences_based_on_word_amount( for sentence_idx, sentence in enumerate(sentences): current_chunk.append(sentence) if language == "zh" and particle_size == "coarse": - chunk_word_count += len(chinese_tokenizer_coarse(sentence)) + chunk_word_count += len(self.chinese_tokenizer_coarse(sentence)) next_sentence_word_count = ( - len(chinese_tokenizer_coarse(sentences[sentence_idx + 1])) + len(self.chinese_tokenizer_coarse(sentences[sentence_idx + 1])) if sentence_idx < len(sentences) - 1 else 0 ) if language == "zh" and particle_size == "fine": - chunk_word_count += len(chinese_tokenizer_fine(sentence)) + chunk_word_count += len(self.chinese_tokenizer_fine(sentence)) next_sentence_word_count = ( - len(chinese_tokenizer_fine(sentences[sentence_idx + 1])) if sentence_idx < len(sentences) - 1 else 0 + len(self.chinese_tokenizer_fine(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, @@ -145,7 +145,8 @@ def _concatenate_sentences_based_on_word_amount( split_start_indices.append(chunk_start_idx) # Get the number of sentences that overlap with the next chunk - num_sentences_to_keep = ChineseDocumentspliter._number_of_sentences_to_keep( + num_sentences_to_keep = ChineseDocumentSplitter._number_of_sentences_to_keep( + self, sentences=current_chunk, split_length=split_length, split_overlap=split_overlap, @@ -182,7 +183,7 @@ def _split_by_nltk_sentence(self, doc: Document) -> List[Document]: split_docs = [] if self.language == "zh": - result = ChineseDocumentspliter.chinese_sentence_split(doc.content) + result = ChineseDocumentSplitter.chinese_sentence_split(doc.content) if self.language == "en": result = self.sentence_splitter.split_sentences(doc.content) # type: ignore # None check is done in run() @@ -315,9 +316,8 @@ def _add_split_overlap_information( overlapping_range = (0, overlapping_range[1] - overlapping_range[0]) previous_doc.meta["_split_overlap"].append({"doc_id": current_doc.id, "range": overlapping_range}) - @staticmethod def _number_of_sentences_to_keep( - sentences: List[str], split_length: int, split_overlap: int, language: str, particle_size: str + self, sentences: List[str], split_length: int, split_overlap: int, language: str, particle_size: str ) -> int: """ Returns the number of sentences to keep in the next chunk based on the `split_overlap` and `split_length`. @@ -338,10 +338,10 @@ def _number_of_sentences_to_keep( # Next overlapping Document should not start exactly the same as the previous one, so we skip the first sentence for sent in reversed(sentences[1:]): if language == "zh" and particle_size == "coarse": - num_words += len(chinese_tokenizer_coarse(sent)) + num_words += len(self.chinese_tokenizer_coarse(sent)) # num_words += len(sent.split()) if language == "zh" and particle_size == "fine": - num_words += len(chinese_tokenizer_fine(sent)) + num_words += len(self.chinese_tokenizer_fine(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 From 830a525d2e2eb20c7f423a8e087d744fd7ede593 Mon Sep 17 00:00:00 2001 From: mc112611 <307267954@qq.com> Date: Thu, 5 Jun 2025 15:54:58 +0800 Subject: [PATCH 06/34] Add test script for ChineseDocumentSplitter, remove Chinese comments, and fix lint issues --- .../preprocessors/chinese_document_spliter.py | 93 +++++-------- .../test_chinese_document_splitter.py | 129 ++++++++++++++++++ 2 files changed, 164 insertions(+), 58 deletions(-) create mode 100644 test/components/preprocessors/test_chinese_document_splitter.py diff --git a/haystack/components/preprocessors/chinese_document_spliter.py b/haystack/components/preprocessors/chinese_document_spliter.py index 7306e65d7..134e48f29 100644 --- a/haystack/components/preprocessors/chinese_document_spliter.py +++ b/haystack/components/preprocessors/chinese_document_spliter.py @@ -1,54 +1,41 @@ -# SPDX-FileCopyrightText: 2022-present deepset GmbH -# -# SPDX-License-Identifier: Apache-2.0 - from copy import deepcopy -from typing import Any, Dict, List, Literal, Tuple +from typing import Any, Callable, Dict, List, Literal, Optional, Tuple +import hanlp from more_itertools import windowed from haystack import Document, component, logging from haystack.components.preprocessors import DocumentSplitter -from haystack.lazy_imports import LazyImport - -with LazyImport("Run 'pip install hanlp'") as hanlp_import: - import hanlp - +from haystack.components.preprocessors.sentence_tokenizer import Language, SentenceSplitter, nltk_imports +from haystack.core.serialization import default_from_dict, default_to_dict +from haystack.utils import deserialize_callable, serialize_callable 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"} +chinese_tokenizer_coarse = hanlp.load(hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH) +chinese_tokenizer_fine = hanlp.load(hanlp.pretrained.tok.FINE_ELECTRA_SMALL_ZH) +# Load Chinese sentence slicer +split_sent = hanlp.load(hanlp.pretrained.eos.UD_CTB_EOS_MUL) @component -class ChineseDocumentSplitter(DocumentSplitter): +class chinese_DocumentSplitter(DocumentSplitter): def __init__(self, *args, particle_size: Literal["coarse", "fine"] = "coarse", **kwargs): - super(ChineseDocumentSplitter, self).__init__(*args, **kwargs) - - # coarse代表粗颗粒度中文分词,fine代表细颗粒度分词,默认为粗颗粒度分词 - # 'coarse' represents coarse granularity Chinese word segmentation, 'fine' represents fine granularity word - # segmentation, default is coarse granularity word segmentation + super(chinese_DocumentSplitter, self).__init__(*args, **kwargs) self.particle_size = particle_size - # self.chinese_tokenizer_coarse = hanlp.load(hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH) - # self.chinese_tokenizer_fine = hanlp.load(hanlp.pretrained.tok.FINE_ELECTRA_SMALL_ZH) - - # # 加载中文的句子切分器 - # self.split_sent = hanlp.load(hanlp.pretrained.eos.UD_CTB_EOS_MUL) - - hanlp_import.check() - - self.chinese_tokenizer_coarse = hanlp.load(hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH) - self.chinese_tokenizer_fine = 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) -> List[Document]: split_at = _CHARACTER_SPLIT_BY_MAPPING[self.split_by] + # 'coarse' represents coarse granularity Chinese word segmentation, + # 'fine' represents fine granularity word segmentation, + # default is coarse granularity word segmentation if self.language == "zh" and self.particle_size == "coarse": - units = self.chinese_tokenizer_coarse(doc.content) + units = chinese_tokenizer_coarse(doc.content) if self.language == "zh" and self.particle_size == "fine": - units = self.chinese_tokenizer_fine(doc.content) + units = chinese_tokenizer_fine(doc.content) if self.language == "en": units = doc.content.split(split_at) # Add the delimiter back to all units except the last one @@ -63,18 +50,13 @@ def _split_by_character(self, doc) -> List[Document]: 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: - """ - Segmentation of Chinese text. - - :param text: The Chinese text to be segmented. - :returns: A list of dictionaries, each containing a sentence and its start and end indices. - """ - # 分句 - sentences = self.split_sent(text) + """Split Chinese text into sentences.""" + # Split sentences + sentences = split_sent(text) - # 整理格式 + # Organize the format of segmented sentences results = [] start = 0 for sentence in sentences: @@ -94,8 +76,9 @@ def _split_document(self, doc: Document) -> List[Document]: return self._split_by_character(doc) + @staticmethod def _concatenate_sentences_based_on_word_amount( - self, sentences: List[str], split_length: int, split_overlap: int, language: str, particle_size: str + sentences: List[str], split_length: int, split_overlap: int, language: str, particle_size: str ) -> Tuple[List[str], List[int], List[int]]: """ Groups the sentences into chunks of `split_length` words while respecting sentence boundaries. @@ -122,18 +105,16 @@ def _concatenate_sentences_based_on_word_amount( for sentence_idx, sentence in enumerate(sentences): current_chunk.append(sentence) if language == "zh" and particle_size == "coarse": - chunk_word_count += len(self.chinese_tokenizer_coarse(sentence)) + chunk_word_count += len(chinese_tokenizer_coarse(sentence)) next_sentence_word_count = ( - len(self.chinese_tokenizer_coarse(sentences[sentence_idx + 1])) + len(chinese_tokenizer_coarse(sentences[sentence_idx + 1])) if sentence_idx < len(sentences) - 1 else 0 ) if language == "zh" and particle_size == "fine": - chunk_word_count += len(self.chinese_tokenizer_fine(sentence)) + chunk_word_count += len(chinese_tokenizer_fine(sentence)) next_sentence_word_count = ( - len(self.chinese_tokenizer_fine(sentences[sentence_idx + 1])) - if sentence_idx < len(sentences) - 1 - else 0 + len(chinese_tokenizer_fine(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, @@ -145,8 +126,7 @@ def _concatenate_sentences_based_on_word_amount( split_start_indices.append(chunk_start_idx) # Get the number of sentences that overlap with the next chunk - num_sentences_to_keep = ChineseDocumentSplitter._number_of_sentences_to_keep( - self, + num_sentences_to_keep = chinese_DocumentSplitter._number_of_sentences_to_keep( sentences=current_chunk, split_length=split_length, split_overlap=split_overlap, @@ -178,12 +158,12 @@ def _concatenate_sentences_based_on_word_amount( return text_splits, split_start_page_numbers, split_start_indices - # 增加中文句子切分,通过languge == "zh",进行启用 + # Add Chinese sentence segmentation and enable it using language=="zh" def _split_by_nltk_sentence(self, doc: Document) -> List[Document]: split_docs = [] if self.language == "zh": - result = ChineseDocumentSplitter.chinese_sentence_split(doc.content) + result = self.chinese_sentence_split(doc.content) if self.language == "en": result = self.sentence_splitter.split_sentences(doc.content) # type: ignore # None check is done in run() @@ -316,8 +296,9 @@ def _add_split_overlap_information( overlapping_range = (0, overlapping_range[1] - overlapping_range[0]) previous_doc.meta["_split_overlap"].append({"doc_id": current_doc.id, "range": overlapping_range}) + @staticmethod def _number_of_sentences_to_keep( - self, sentences: List[str], split_length: int, split_overlap: int, language: str, particle_size: str + sentences: List[str], split_length: int, split_overlap: int, language: str, particle_size: str ) -> int: """ Returns the number of sentences to keep in the next chunk based on the `split_overlap` and `split_length`. @@ -333,20 +314,16 @@ def _number_of_sentences_to_keep( num_sentences_to_keep = 0 num_words = 0 - # chinese_tokenizer_coarse = hanlp.load(hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH) - # chinese_tokenizer_fine = hanlp.load(hanlp.pretrained.tok.FINE_ELECTRA_SMALL_ZH) - # Next overlapping Document should not start exactly the same as the previous one, so we skip the first sentence + for sent in reversed(sentences[1:]): if language == "zh" and particle_size == "coarse": - num_words += len(self.chinese_tokenizer_coarse(sent)) - # num_words += len(sent.split()) + num_words += len(chinese_tokenizer_coarse(sent)) if language == "zh" and particle_size == "fine": - num_words += len(self.chinese_tokenizer_fine(sent)) + num_words += len(chinese_tokenizer_fine(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 diff --git a/test/components/preprocessors/test_chinese_document_splitter.py b/test/components/preprocessors/test_chinese_document_splitter.py new file mode 100644 index 000000000..8837419e3 --- /dev/null +++ b/test/components/preprocessors/test_chinese_document_splitter.py @@ -0,0 +1,129 @@ +import pytest +from haystack import Document +from haystack.components.preprocessors.chinese_document_spliter import chinese_DocumentSplitter + + +class TestChineseDocumentSplitter: + @pytest.fixture + def sample_text(self) -> str: + return "这是第一句话,也是故事的开端,紧接着是第二句话,渐渐引出了背景;随后,翻开新/f的一页,我们读到了这一页的第一句话,继续延展出情节的发展,直到这页的第二句话将整段文字温柔地收束于平静之中。" + + def test_split_by_word(self, sample_text): + """ + Test splitting by word. + + Note on Chinese words: + 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. + """ + splitter = chinese_DocumentSplitter( + split_by="word", language="zh", particle_size="coarse", split_length=5, split_overlap=0 + ) + if hasattr(splitter, "warm_up"): + splitter.warm_up() + + result = splitter.run(documents=[Document(content=sample_text)]) + docs = result["documents"] + + assert all(isinstance(doc, Document) for doc in docs) + assert all(len(doc.content.strip()) <= 10 for doc in docs) + + def test_split_by_sentence(self, sample_text): + splitter = chinese_DocumentSplitter( + split_by="sentence", language="zh", particle_size="coarse", split_length=10, split_overlap=0 + ) + if hasattr(splitter, "warm_up"): + splitter.warm_up() + + result = splitter.run(documents=[Document(content=sample_text)]) + docs = result["documents"] + + assert all(isinstance(doc, Document) for doc in docs) + assert all(doc.content.strip() != "" for doc in docs) + assert any("。" in doc.content for doc in docs), "Expected at least one chunk containing a full stop." + + def test_respect_sentence_boundary(self): + """Test that respect_sentence_boundary=True avoids splitting sentences""" + text = "这是第一句话,这是第二句话,这是第三句话。这是第四句话,这是第五句话,这是第六句话!这是第七句话,这是第八句话,这是第九句话?" + doc = Document(content=text) + + splitter = chinese_DocumentSplitter( + split_by="word", split_length=10, split_overlap=3, language="zh", respect_sentence_boundary=True + ) + splitter.warm_up() + result = splitter.run(documents=[doc]) + docs = result["documents"] + + print(f"Total chunks created: {len(docs)}.") + for i, d in enumerate(docs): + print(f"\nChunk {i + 1}:\n{d.content}") + # Optional: check that sentences are not cut off + assert d.content.strip().endswith(("。", "!", "?")), "Sentence was cut off!" + + def test_overlap_chunks_with_long_text(self): + """Test split_overlap parameter to ensure there is clear overlap between chunks of long text""" + text = ( + "月光轻轻洒落,林中传来阵阵狼嚎,夜色悄然笼罩一切。" + "树叶在微风中沙沙作响,影子在地面上摇曳不定。" + "一只猫头鹰静静地眨了眨眼,从枝头注视着四周……" + "远处的小溪哗啦啦地流淌,仿佛在向石头倾诉着什么。" + "“咔嚓”一声,某处的树枝突然断裂,然后恢复了寂静。" + "空气中弥漫着松树与湿土的气息,令人心安。" + "一只狐狸悄然出现,又迅速消失在灌木丛中。" + "天上的星星闪烁着,仿佛在诉说古老的故事。" + "时间仿佛停滞了……" + "万物静候,聆听着夜的呼吸!" + ) + doc = Document(content=text) + + splitter = chinese_DocumentSplitter( + split_by="word", language="zh", split_length=30, split_overlap=10, particle_size="coarse" + ) + if hasattr(splitter, "warm_up"): + splitter.warm_up() + + result = splitter.run(documents=[doc]) + docs = result["documents"] + + print(f"Total chunks generated: {len(docs)}.") + for i, d in enumerate(docs): + print(f"\nChunk {i + 1}:\n{d.content}") + + assert len(docs) > 1, "Expected multiple chunks to be generated" + + max_len_allowed = 80 # Allow a somewhat relaxed max chunk length + assert all(len(doc.content) <= max_len_allowed for doc in docs), ( + f"Some chunks exceed {max_len_allowed} characters" + ) + + def has_any_overlap(suffix: str, prefix: str) -> bool: + """ + Check if suffix and prefix have at least one continuous overlapping character sequence. + Tries from 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}'" + ) From 75413e42e1012f022e423604d49f023c1703f7c5 Mon Sep 17 00:00:00 2001 From: "David S. Batista" Date: Thu, 5 Jun 2025 10:59:31 +0200 Subject: [PATCH 07/34] wip --- ...pliter.py => chinese_document_splitter.py} | 46 +++++++++++++++---- 1 file changed, 37 insertions(+), 9 deletions(-) rename haystack/components/preprocessors/{chinese_document_spliter.py => chinese_document_splitter.py} (91%) diff --git a/haystack/components/preprocessors/chinese_document_spliter.py b/haystack/components/preprocessors/chinese_document_splitter.py similarity index 91% rename from haystack/components/preprocessors/chinese_document_spliter.py rename to haystack/components/preprocessors/chinese_document_splitter.py index 134e48f29..1254606b6 100644 --- a/haystack/components/preprocessors/chinese_document_spliter.py +++ b/haystack/components/preprocessors/chinese_document_splitter.py @@ -1,14 +1,15 @@ from copy import deepcopy from typing import Any, Callable, Dict, List, Literal, Optional, Tuple -import hanlp from more_itertools import windowed from haystack import Document, component, logging from haystack.components.preprocessors import DocumentSplitter -from haystack.components.preprocessors.sentence_tokenizer import Language, SentenceSplitter, nltk_imports -from haystack.core.serialization import default_from_dict, default_to_dict -from haystack.utils import deserialize_callable, serialize_callable +from haystack.lazy_imports import LazyImport + +with LazyImport("Run 'pip install hanlp'") as hanlp_import: + import hanlp + logger = logging.getLogger(__name__) @@ -21,24 +22,50 @@ @component -class chinese_DocumentSplitter(DocumentSplitter): +class ChineseDocumentSplitter(DocumentSplitter): def __init__(self, *args, particle_size: Literal["coarse", "fine"] = "coarse", **kwargs): - super(chinese_DocumentSplitter, self).__init__(*args, **kwargs) + """ + A DocumentSplitter for Chinese text. + + # coarse代表粗颗粒度中文分词,fine代表细颗粒度分词,默认为粗颗粒度分词 + # 'coarse' represents coarse granularity Chinese word segmentation, 'fine' represents fine granularity word + # segmentation, default is coarse granularity word segmentation + + :param particle_size: The granularity of Chinese word segmentation, either 'coarse' or 'fine'. + + """ + super(ChineseDocumentSplitter, self).__init__(*args, **kwargs) self.particle_size = particle_size + hanlp_import.check() + + self.chinese_tokenizer_coarse = hanlp.load(hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH) + self.chinese_tokenizer_fine = 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) -> List[Document]: + """ + Define a function to handle Chinese clauses + + :param doc: + :return: + """ split_at = _CHARACTER_SPLIT_BY_MAPPING[self.split_by] + # 'coarse' represents coarse granularity Chinese word segmentation, # 'fine' represents fine granularity word segmentation, # default is coarse granularity word segmentation + if self.language == "zh" and self.particle_size == "coarse": - units = chinese_tokenizer_coarse(doc.content) + units = self.chinese_tokenizer_coarse(doc.content) if self.language == "zh" and self.particle_size == "fine": - units = chinese_tokenizer_fine(doc.content) + units = self.chinese_tokenizer_fine(doc.content) + if self.language == "en": units = doc.content.split(split_at) # Add the delimiter back to all units except the last one + for i in range(len(units) - 1): units[i] += split_at text_splits, splits_pages, splits_start_idxs = self._concatenate_units( @@ -46,6 +73,7 @@ def _split_by_character(self, doc) -> List[Document]: ) 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 ) @@ -126,7 +154,7 @@ def _concatenate_sentences_based_on_word_amount( split_start_indices.append(chunk_start_idx) # Get the number of sentences that overlap with the next chunk - num_sentences_to_keep = chinese_DocumentSplitter._number_of_sentences_to_keep( + num_sentences_to_keep = ChineseDocumentSplitter._number_of_sentences_to_keep( sentences=current_chunk, split_length=split_length, split_overlap=split_overlap, From bd5ffd5cb9ba03422acbba6a161fa80370059db1 Mon Sep 17 00:00:00 2001 From: "David S. Batista" Date: Thu, 5 Jun 2025 11:04:50 +0200 Subject: [PATCH 08/34] adding LICENSE header to tests --- .../preprocessors/test_chinese_document_splitter.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/test/components/preprocessors/test_chinese_document_splitter.py b/test/components/preprocessors/test_chinese_document_splitter.py index 8837419e3..87f874ea8 100644 --- a/test/components/preprocessors/test_chinese_document_splitter.py +++ b/test/components/preprocessors/test_chinese_document_splitter.py @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + import pytest from haystack import Document from haystack.components.preprocessors.chinese_document_spliter import chinese_DocumentSplitter From b908ee5d9802378b78eb00f6ab2dabbd9d37e31f Mon Sep 17 00:00:00 2001 From: "David S. Batista" Date: Thu, 5 Jun 2025 11:07:28 +0200 Subject: [PATCH 09/34] wip --- .../components/preprocessors/chinese_document_splitter.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/haystack/components/preprocessors/chinese_document_splitter.py b/haystack/components/preprocessors/chinese_document_splitter.py index 1254606b6..66bece83f 100644 --- a/haystack/components/preprocessors/chinese_document_splitter.py +++ b/haystack/components/preprocessors/chinese_document_splitter.py @@ -1,5 +1,5 @@ from copy import deepcopy -from typing import Any, Callable, Dict, List, Literal, Optional, Tuple +from typing import Any, Dict, List, Literal, Tuple from more_itertools import windowed @@ -27,9 +27,8 @@ def __init__(self, *args, particle_size: Literal["coarse", "fine"] = "coarse", * """ A DocumentSplitter for Chinese text. - # coarse代表粗颗粒度中文分词,fine代表细颗粒度分词,默认为粗颗粒度分词 - # 'coarse' represents coarse granularity Chinese word segmentation, 'fine' represents fine granularity word - # segmentation, default is coarse granularity word segmentation + 'coarse' represents coarse granularity Chinese word segmentation, 'fine' represents fine granularity word + segmentation, default is coarse granularity word segmentation. :param particle_size: The granularity of Chinese word segmentation, either 'coarse' or 'fine'. From 29de3308dfee7f9b92c6602ad3e484242abe8b7a Mon Sep 17 00:00:00 2001 From: "David S. Batista" Date: Thu, 5 Jun 2025 11:09:21 +0200 Subject: [PATCH 10/34] adding LICENSE header --- .../components/preprocessors/chinese_document_splitter.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/haystack/components/preprocessors/chinese_document_splitter.py b/haystack/components/preprocessors/chinese_document_splitter.py index 66bece83f..57b9aee86 100644 --- a/haystack/components/preprocessors/chinese_document_splitter.py +++ b/haystack/components/preprocessors/chinese_document_splitter.py @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 + from copy import deepcopy from typing import Any, Dict, List, Literal, Tuple From 86e5c8f68e4c54510392d58deafa63641716f4f0 Mon Sep 17 00:00:00 2001 From: "David S. Batista" Date: Thu, 5 Jun 2025 11:14:17 +0200 Subject: [PATCH 11/34] fixing linting issues --- .../chinese_document_splitter.py | 33 ++++++++++--------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/haystack/components/preprocessors/chinese_document_splitter.py b/haystack/components/preprocessors/chinese_document_splitter.py index 57b9aee86..c2fbb11c7 100644 --- a/haystack/components/preprocessors/chinese_document_splitter.py +++ b/haystack/components/preprocessors/chinese_document_splitter.py @@ -19,10 +19,11 @@ # 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"} -chinese_tokenizer_coarse = hanlp.load(hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH) -chinese_tokenizer_fine = hanlp.load(hanlp.pretrained.tok.FINE_ELECTRA_SMALL_ZH) + +# chinese_tokenizer_coarse = hanlp.load(hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH) +# chinese_tokenizer_fine = hanlp.load(hanlp.pretrained.tok.FINE_ELECTRA_SMALL_ZH) # Load Chinese sentence slicer -split_sent = hanlp.load(hanlp.pretrained.eos.UD_CTB_EOS_MUL) +# split_sent = hanlp.load(hanlp.pretrained.eos.UD_CTB_EOS_MUL) @component @@ -85,7 +86,7 @@ def _split_by_character(self, doc) -> List[Document]: def chinese_sentence_split(self, text: str) -> list: """Split Chinese text into sentences.""" # Split sentences - sentences = split_sent(text) + sentences = self.split_sent(text) # Organize the format of segmented sentences results = [] @@ -107,9 +108,8 @@ def _split_document(self, doc: Document) -> List[Document]: return self._split_by_character(doc) - @staticmethod - def _concatenate_sentences_based_on_word_amount( - sentences: List[str], split_length: int, split_overlap: int, language: str, particle_size: str + def _concatenate_sentences_based_on_word_amount( # pylint: disable=too-many-positional-arguments + self, sentences: List[str], split_length: int, split_overlap: int, language: str, particle_size: str ) -> Tuple[List[str], List[int], List[int]]: """ Groups the sentences into chunks of `split_length` words while respecting sentence boundaries. @@ -136,16 +136,18 @@ def _concatenate_sentences_based_on_word_amount( for sentence_idx, sentence in enumerate(sentences): current_chunk.append(sentence) if language == "zh" and particle_size == "coarse": - chunk_word_count += len(chinese_tokenizer_coarse(sentence)) + chunk_word_count += len(self.chinese_tokenizer_coarse(sentence)) next_sentence_word_count = ( - len(chinese_tokenizer_coarse(sentences[sentence_idx + 1])) + len(self.chinese_tokenizer_coarse(sentences[sentence_idx + 1])) if sentence_idx < len(sentences) - 1 else 0 ) if language == "zh" and particle_size == "fine": - chunk_word_count += len(chinese_tokenizer_fine(sentence)) + chunk_word_count += len(self.chinese_tokenizer_fine(sentence)) next_sentence_word_count = ( - len(chinese_tokenizer_fine(sentences[sentence_idx + 1])) if sentence_idx < len(sentences) - 1 else 0 + len(self.chinese_tokenizer_fine(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, @@ -327,9 +329,8 @@ def _add_split_overlap_information( overlapping_range = (0, overlapping_range[1] - overlapping_range[0]) previous_doc.meta["_split_overlap"].append({"doc_id": current_doc.id, "range": overlapping_range}) - @staticmethod - def _number_of_sentences_to_keep( - sentences: List[str], split_length: int, split_overlap: int, language: str, particle_size: str + def _number_of_sentences_to_keep( # pylint: disable=too-many-positional-arguments + self, sentences: List[str], split_length: int, split_overlap: int, language: str, particle_size: str ) -> int: """ Returns the number of sentences to keep in the next chunk based on the `split_overlap` and `split_length`. @@ -348,9 +349,9 @@ def _number_of_sentences_to_keep( for sent in reversed(sentences[1:]): if language == "zh" and particle_size == "coarse": - num_words += len(chinese_tokenizer_coarse(sent)) + num_words += len(self.chinese_tokenizer_coarse(sent)) if language == "zh" and particle_size == "fine": - num_words += len(chinese_tokenizer_fine(sent)) + num_words += len(self.chinese_tokenizer_fine(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 From 14bcf08983d7199fe7af4b77cb303d4202aae4c1 Mon Sep 17 00:00:00 2001 From: "David S. Batista" Date: Thu, 5 Jun 2025 11:42:08 +0200 Subject: [PATCH 12/34] fixing tests --- .../preprocessors/chinese_document_splitter.py | 4 ++-- .../preprocessors/test_chinese_document_splitter.py | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/haystack/components/preprocessors/chinese_document_splitter.py b/haystack/components/preprocessors/chinese_document_splitter.py index c2fbb11c7..cc448604d 100644 --- a/haystack/components/preprocessors/chinese_document_splitter.py +++ b/haystack/components/preprocessors/chinese_document_splitter.py @@ -70,7 +70,7 @@ def _split_by_character(self, doc) -> List[Document]: units = doc.content.split(split_at) # Add the delimiter back to all units except the last one - for i in range(len(units) - 1): + for i in range(len(units) - 1): # pylint: disable=possibly-used-before-assignment units[i] += split_at text_splits, splits_pages, splits_start_idxs = self._concatenate_units( units, self.split_length, self.split_overlap, self.split_threshold @@ -152,7 +152,7 @@ def _concatenate_sentences_based_on_word_amount( # pylint: disable=too-many-pos # 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: + if (chunk_word_count + next_sentence_word_count) > split_length or sentence_idx == len(sentences) - 1: # pylint: disable=possibly-used-before-assignment # Save current chunk and start a new one list_of_splits.append(current_chunk) split_start_page_numbers.append(chunk_starting_page_number) diff --git a/test/components/preprocessors/test_chinese_document_splitter.py b/test/components/preprocessors/test_chinese_document_splitter.py index 87f874ea8..4d4bfb843 100644 --- a/test/components/preprocessors/test_chinese_document_splitter.py +++ b/test/components/preprocessors/test_chinese_document_splitter.py @@ -4,7 +4,7 @@ import pytest from haystack import Document -from haystack.components.preprocessors.chinese_document_spliter import chinese_DocumentSplitter +from haystack.components.preprocessors.chinese_document_splitter import ChineseDocumentSplitter class TestChineseDocumentSplitter: @@ -27,7 +27,7 @@ def test_split_by_word(self, sample_text): Therefore, splitting by word means splitting by these multi-character tokens, not simply by single characters or spaces. """ - splitter = chinese_DocumentSplitter( + splitter = ChineseDocumentSplitter( split_by="word", language="zh", particle_size="coarse", split_length=5, split_overlap=0 ) if hasattr(splitter, "warm_up"): @@ -40,7 +40,7 @@ def test_split_by_word(self, sample_text): assert all(len(doc.content.strip()) <= 10 for doc in docs) def test_split_by_sentence(self, sample_text): - splitter = chinese_DocumentSplitter( + splitter = ChineseDocumentSplitter( split_by="sentence", language="zh", particle_size="coarse", split_length=10, split_overlap=0 ) if hasattr(splitter, "warm_up"): @@ -58,7 +58,7 @@ def test_respect_sentence_boundary(self): text = "这是第一句话,这是第二句话,这是第三句话。这是第四句话,这是第五句话,这是第六句话!这是第七句话,这是第八句话,这是第九句话?" doc = Document(content=text) - splitter = chinese_DocumentSplitter( + splitter = ChineseDocumentSplitter( split_by="word", split_length=10, split_overlap=3, language="zh", respect_sentence_boundary=True ) splitter.warm_up() @@ -87,7 +87,7 @@ def test_overlap_chunks_with_long_text(self): ) doc = Document(content=text) - splitter = chinese_DocumentSplitter( + splitter = ChineseDocumentSplitter( split_by="word", language="zh", split_length=30, split_overlap=10, particle_size="coarse" ) if hasattr(splitter, "warm_up"): @@ -110,7 +110,7 @@ def test_overlap_chunks_with_long_text(self): def has_any_overlap(suffix: str, prefix: str) -> bool: """ Check if suffix and prefix have at least one continuous overlapping character sequence. - Tries from longest possible overlap down to 1 character. + Tries from the longest possible overlap down to 1 character. Returns True if any overlap found. """ max_check_len = min(len(suffix), len(prefix)) From fbfe639ef1c77681272e04d291d9712bd4beeb50 Mon Sep 17 00:00:00 2001 From: "David S. Batista" Date: Thu, 5 Jun 2025 11:54:11 +0200 Subject: [PATCH 13/34] fixing tests --- haystack/components/preprocessors/chinese_document_splitter.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/haystack/components/preprocessors/chinese_document_splitter.py b/haystack/components/preprocessors/chinese_document_splitter.py index cc448604d..552b53b7f 100644 --- a/haystack/components/preprocessors/chinese_document_splitter.py +++ b/haystack/components/preprocessors/chinese_document_splitter.py @@ -159,7 +159,7 @@ def _concatenate_sentences_based_on_word_amount( # pylint: disable=too-many-pos split_start_indices.append(chunk_start_idx) # Get the number of sentences that overlap with the next chunk - num_sentences_to_keep = ChineseDocumentSplitter._number_of_sentences_to_keep( + num_sentences_to_keep = self._number_of_sentences_to_keep( sentences=current_chunk, split_length=split_length, split_overlap=split_overlap, From 7609675f9939f13a2b722ad283e679278e00820b Mon Sep 17 00:00:00 2001 From: "David S. Batista" Date: Thu, 5 Jun 2025 15:45:50 +0200 Subject: [PATCH 14/34] wip: trying to make tests work with downloaded data --- .../chinese_document_splitter.py | 25 ++++++++++++------- .../test_chinese_document_splitter.py | 2 ++ 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/haystack/components/preprocessors/chinese_document_splitter.py b/haystack/components/preprocessors/chinese_document_splitter.py index 552b53b7f..0a76e03b2 100644 --- a/haystack/components/preprocessors/chinese_document_splitter.py +++ b/haystack/components/preprocessors/chinese_document_splitter.py @@ -20,11 +20,6 @@ # 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"} -# chinese_tokenizer_coarse = hanlp.load(hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH) -# chinese_tokenizer_fine = hanlp.load(hanlp.pretrained.tok.FINE_ELECTRA_SMALL_ZH) -# Load Chinese sentence slicer -# split_sent = hanlp.load(hanlp.pretrained.eos.UD_CTB_EOS_MUL) - @component class ChineseDocumentSplitter(DocumentSplitter): @@ -43,8 +38,18 @@ def __init__(self, *args, particle_size: Literal["coarse", "fine"] = "coarse", * hanlp_import.check() - self.chinese_tokenizer_coarse = hanlp.load(hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH) - self.chinese_tokenizer_fine = hanlp.load(hanlp.pretrained.tok.FINE_ELECTRA_SMALL_ZH) + if particle_size not in ["coarse", "fine"]: + raise ValueError(f"Invalid particle_size '{particle_size}'. Choose either 'coarse' or 'fine'.") + + if particle_size == "coarse": + logger.info("Using 'coarse' granularity Chinese word segmentation.") + self.chinese_tokenizer_coarse = hanlp.load(hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH) + + if particle_size == "fine": + logger.info("Using 'fine' granularity Chinese word segmentation.") + self.chinese_tokenizer_fine = hanlp.load(hanlp.pretrained.tok.FINE_ELECTRA_SMALL_ZH) + + # Load Chinese sentence slicer self.split_sent = hanlp.load(hanlp.pretrained.eos.UD_CTB_EOS_MUL) # 加载中文的句子切分器 def _split_by_character(self, doc) -> List[Document]: @@ -122,17 +127,18 @@ def _concatenate_sentences_based_on_word_amount( # pylint: disable=too-many-pos :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 = [] - # chinese_tokenizer_coarse = hanlp.load(hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH) - # chinese_tokenizer_fine = hanlp.load(hanlp.pretrained.tok.FINE_ELECTRA_SMALL_ZH) + for sentence_idx, sentence in enumerate(sentences): current_chunk.append(sentence) if language == "zh" and particle_size == "coarse": @@ -172,6 +178,7 @@ def _concatenate_sentences_based_on_word_amount( # pylint: disable=too-many-pos 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) diff --git a/test/components/preprocessors/test_chinese_document_splitter.py b/test/components/preprocessors/test_chinese_document_splitter.py index 4d4bfb843..c94fefa99 100644 --- a/test/components/preprocessors/test_chinese_document_splitter.py +++ b/test/components/preprocessors/test_chinese_document_splitter.py @@ -12,6 +12,7 @@ class TestChineseDocumentSplitter: def sample_text(self) -> str: return "这是第一句话,也是故事的开端,紧接着是第二句话,渐渐引出了背景;随后,翻开新/f的一页,我们读到了这一页的第一句话,继续延展出情节的发展,直到这页的第二句话将整段文字温柔地收束于平静之中。" + @pytest.mark.integration def test_split_by_word(self, sample_text): """ Test splitting by word. @@ -39,6 +40,7 @@ def test_split_by_word(self, sample_text): assert all(isinstance(doc, Document) for doc in docs) assert all(len(doc.content.strip()) <= 10 for doc in docs) + @pytest.mark.integration def test_split_by_sentence(self, sample_text): splitter = ChineseDocumentSplitter( split_by="sentence", language="zh", particle_size="coarse", split_length=10, split_overlap=0 From ca18eb2f3b47ac5ef84c5bdba1d98acd512b2e61 Mon Sep 17 00:00:00 2001 From: "David S. Batista" Date: Thu, 5 Jun 2025 15:51:08 +0200 Subject: [PATCH 15/34] wip: trying to make tests work with downloaded data --- test/components/preprocessors/test_chinese_document_splitter.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/components/preprocessors/test_chinese_document_splitter.py b/test/components/preprocessors/test_chinese_document_splitter.py index c94fefa99..10933dd7c 100644 --- a/test/components/preprocessors/test_chinese_document_splitter.py +++ b/test/components/preprocessors/test_chinese_document_splitter.py @@ -55,6 +55,7 @@ def test_split_by_sentence(self, sample_text): assert all(doc.content.strip() != "" for doc in docs) assert any("。" in doc.content for doc in docs), "Expected at least one chunk containing a full stop." + @pytest.mark.integration def test_respect_sentence_boundary(self): """Test that respect_sentence_boundary=True avoids splitting sentences""" text = "这是第一句话,这是第二句话,这是第三句话。这是第四句话,这是第五句话,这是第六句话!这是第七句话,这是第八句话,这是第九句话?" @@ -73,6 +74,7 @@ def test_respect_sentence_boundary(self): # Optional: check that sentences are not cut off assert d.content.strip().endswith(("。", "!", "?")), "Sentence was cut off!" + @pytest.mark.integration def test_overlap_chunks_with_long_text(self): """Test split_overlap parameter to ensure there is clear overlap between chunks of long text""" text = ( From 8b8ea1f652417c7e16b6baa9ecb16d6ba9e5275e Mon Sep 17 00:00:00 2001 From: Julian Risch Date: Fri, 13 Jun 2025 10:36:09 +0200 Subject: [PATCH 16/34] move ChineseDocumentSplitter to integration folder --- .../components/preprocessors/__init__.py | 8 ++++++++ .../components/preprocessors/chinese_document_splitter.py | 2 +- integrations/hanlp/tests/__init__.py | 3 +++ .../hanlp/tests}/test_chinese_document_splitter.py | 2 +- 4 files changed, 13 insertions(+), 2 deletions(-) create mode 100644 integrations/hanlp/src/haystack_integrations/components/preprocessors/__init__.py rename {haystack => integrations/hanlp/src/haystack_integrations}/components/preprocessors/chinese_document_splitter.py (99%) create mode 100644 integrations/hanlp/tests/__init__.py rename {test/components/preprocessors => integrations/hanlp/tests}/test_chinese_document_splitter.py (98%) diff --git a/integrations/hanlp/src/haystack_integrations/components/preprocessors/__init__.py b/integrations/hanlp/src/haystack_integrations/components/preprocessors/__init__.py new file mode 100644 index 000000000..c6cb8827d --- /dev/null +++ b/integrations/hanlp/src/haystack_integrations/components/preprocessors/__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/haystack/components/preprocessors/chinese_document_splitter.py b/integrations/hanlp/src/haystack_integrations/components/preprocessors/chinese_document_splitter.py similarity index 99% rename from haystack/components/preprocessors/chinese_document_splitter.py rename to integrations/hanlp/src/haystack_integrations/components/preprocessors/chinese_document_splitter.py index 0a76e03b2..d06890053 100644 --- a/haystack/components/preprocessors/chinese_document_splitter.py +++ b/integrations/hanlp/src/haystack_integrations/components/preprocessors/chinese_document_splitter.py @@ -1,4 +1,4 @@ -# SPDX-FileCopyrightText: 2022-present deepset GmbH +# SPDX-FileCopyrightText: 2025-present deepset GmbH # # SPDX-License-Identifier: Apache-2.0 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/test/components/preprocessors/test_chinese_document_splitter.py b/integrations/hanlp/tests/test_chinese_document_splitter.py similarity index 98% rename from test/components/preprocessors/test_chinese_document_splitter.py rename to integrations/hanlp/tests/test_chinese_document_splitter.py index 10933dd7c..f6f1ddb4a 100644 --- a/test/components/preprocessors/test_chinese_document_splitter.py +++ b/integrations/hanlp/tests/test_chinese_document_splitter.py @@ -1,4 +1,4 @@ -# SPDX-FileCopyrightText: 2022-present deepset GmbH +# SPDX-FileCopyrightText: 2025-present deepset GmbH # # SPDX-License-Identifier: Apache-2.0 From fe4784bbf1fb7e7cd681c26186f68bbe8a294f6d Mon Sep 17 00:00:00 2001 From: Julian Risch Date: Fri, 13 Jun 2025 10:59:28 +0200 Subject: [PATCH 17/34] create scaffold of the new integration --- integrations/hanlp/LICENSE.txt | 73 ++++++++++++ integrations/hanlp/README.md | 21 ++++ integrations/hanlp/pydoc/config.yml | 29 +++++ integrations/hanlp/pyproject.toml | 168 ++++++++++++++++++++++++++++ 4 files changed, 291 insertions(+) create mode 100644 integrations/hanlp/LICENSE.txt create mode 100644 integrations/hanlp/README.md create mode 100644 integrations/hanlp/pydoc/config.yml create mode 100644 integrations/hanlp/pyproject.toml 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..b45ef1880 --- /dev/null +++ b/integrations/hanlp/pyproject.toml @@ -0,0 +1,168 @@ +[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", +] +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 = true + +[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 = [ + "unit: unit tests", + "integration: integration tests", +] +log_cli = true From 1747d6a1cb6e5177579666628ccd2b25b7280ca6 Mon Sep 17 00:00:00 2001 From: Julian Risch Date: Fri, 13 Jun 2025 11:11:08 +0200 Subject: [PATCH 18/34] add test workflow --- .github/workflows/hanlp.yml | 84 +++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 .github/workflows/hanlp.yml diff --git a/.github/workflows/hanlp.yml b/.github/workflows/hanlp.yml new file mode 100644 index 000000000..b05814c1d --- /dev/null +++ b/.github/workflows/hanlp.yml @@ -0,0 +1,84 @@ +# 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"] + + 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 + + # TODO: Once this integration is properly typed, use hatch run test:types + # https://github.com/deepset-ai/haystack-core-integrations/issues/1771 + - name: Lint + if: matrix.python-version == '3.9' && runner.os == 'Linux' + run: hatch run fmt-check && hatch run lint:typing + + - 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 }} From b1f802cbfbe295b888fa837e061089194ecae511 Mon Sep 17 00:00:00 2001 From: Julian Risch Date: Fri, 13 Jun 2025 11:13:59 +0200 Subject: [PATCH 19/34] add new integration to labeler.yml --- .github/labeler.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/labeler.yml b/.github/labeler.yml index 397bf1235..d7943050f 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:instructor-embedders: - changed-files: - any-glob-to-any-file: "integrations/instructor_embedders/**/*" From d4165f06ac3ece9236b5d24442abfd26782d86db Mon Sep 17 00:00:00 2001 From: Julian Risch Date: Fri, 13 Jun 2025 11:17:27 +0200 Subject: [PATCH 20/34] add to overview table in README --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index db505a15a..c1e905ad2 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/) | 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/) | 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) | | [instructor-embedders-haystack](integrations/instructor_embedders/) | Embedder | [![PyPI - Version](https://img.shields.io/pypi/v/instructor-embedders-haystack.svg)](https://pypi.org/project/instructor-embedders-haystack) | [![Test / instructor-embedders](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/instructor_embedders.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/instructor_embedders.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) | From 7415b8344af345cf61b28b37a17a662829b92968 Mon Sep 17 00:00:00 2001 From: Julian Risch Date: Wed, 18 Jun 2025 23:16:00 +0200 Subject: [PATCH 21/34] add warmup, do not inherit from DocumentSplitter, remove english support --- .../chinese_document_splitter.py | 146 ++++++++++++------ .../tests/test_chinese_document_splitter.py | 30 ++-- 2 files changed, 113 insertions(+), 63 deletions(-) diff --git a/integrations/hanlp/src/haystack_integrations/components/preprocessors/chinese_document_splitter.py b/integrations/hanlp/src/haystack_integrations/components/preprocessors/chinese_document_splitter.py index d06890053..c53401bb7 100644 --- a/integrations/hanlp/src/haystack_integrations/components/preprocessors/chinese_document_splitter.py +++ b/integrations/hanlp/src/haystack_integrations/components/preprocessors/chinese_document_splitter.py @@ -1,19 +1,13 @@ # SPDX-FileCopyrightText: 2025-present deepset GmbH # # SPDX-License-Identifier: Apache-2.0 - +import hanlp from copy import deepcopy -from typing import Any, Dict, List, Literal, Tuple +from typing import Any, Dict, List, Literal, Tuple, Optional, Callable from more_itertools import windowed from haystack import Document, component, logging -from haystack.components.preprocessors import DocumentSplitter -from haystack.lazy_imports import LazyImport - -with LazyImport("Run 'pip install hanlp'") as hanlp_import: - import hanlp - logger = logging.getLogger(__name__) @@ -22,42 +16,77 @@ @component -class ChineseDocumentSplitter(DocumentSplitter): - def __init__(self, *args, particle_size: Literal["coarse", "fine"] = "coarse", **kwargs): +class ChineseDocumentSplitter: + 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, + particle_size: Literal["coarse", "fine"] = "coarse", + ): """ A DocumentSplitter for Chinese text. 'coarse' represents coarse granularity Chinese word segmentation, 'fine' represents fine granularity word segmentation, default is coarse granularity word segmentation. + :param split_by: The unit by which the text is split. Can be one of: "word", "sentence", "passage", "page", "line", "period", "function". + :param split_length: The maximum number of words in each split. + :param split_overlap: The number of overlapping words in each split. + :param split_threshold: The minimum number of words in each split. + :param respect_sentence_boundary: Whether to respect sentence boundaries when splitting. + :param splitting_function: A custom function to split the text. :param particle_size: The granularity of Chinese word segmentation, either 'coarse' or 'fine'. + :raises ValueError: If the particle_size is not 'coarse' or 'fine'. """ - super(ChineseDocumentSplitter, self).__init__(*args, **kwargs) + 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.particle_size = particle_size - hanlp_import.check() - if particle_size not in ["coarse", "fine"]: raise ValueError(f"Invalid particle_size '{particle_size}'. Choose either 'coarse' or 'fine'.") - if particle_size == "coarse": - logger.info("Using 'coarse' granularity Chinese word segmentation.") - self.chinese_tokenizer_coarse = hanlp.load(hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH) - if particle_size == "fine": - logger.info("Using 'fine' granularity Chinese word segmentation.") + 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: + raise RuntimeError("The Chinese word segmentation model is not loaded. Please run 'warm_up()' before calling 'run()'.") + + 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.particle_size == "coarse": + self.chinese_tokenizer_coarse = hanlp.load(hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH) + if self.particle_size == "fine": self.chinese_tokenizer_fine = hanlp.load(hanlp.pretrained.tok.FINE_ELECTRA_SMALL_ZH) + self.split_sent = hanlp.load(hanlp.pretrained.eos.UD_CTB_EOS_MUL) - # Load Chinese sentence slicer - self.split_sent = hanlp.load(hanlp.pretrained.eos.UD_CTB_EOS_MUL) # 加载中文的句子切分器 - def _split_by_character(self, doc) -> List[Document]: + def _split_by_character(self, doc: Document) -> List[Document]: """ Define a function to handle Chinese clauses - :param doc: - :return: + :param doc: The document to split. + :return: A list of split documents. """ split_at = _CHARACTER_SPLIT_BY_MAPPING[self.split_by] @@ -65,16 +94,12 @@ def _split_by_character(self, doc) -> List[Document]: # 'fine' represents fine granularity word segmentation, # default is coarse granularity word segmentation - if self.language == "zh" and self.particle_size == "coarse": + if self.particle_size == "coarse": units = self.chinese_tokenizer_coarse(doc.content) - if self.language == "zh" and self.particle_size == "fine": + if self.particle_size == "fine": units = self.chinese_tokenizer_fine(doc.content) - if self.language == "en": - units = doc.content.split(split_at) - # Add the delimiter back to all units except the last one - for i in range(len(units) - 1): # pylint: disable=possibly-used-before-assignment units[i] += split_at text_splits, splits_pages, splits_start_idxs = self._concatenate_units( @@ -88,8 +113,13 @@ def _split_by_character(self, doc) -> List[Document]: ) # Define a function to handle Chinese clauses - def chinese_sentence_split(self, text: str) -> list: - """Split Chinese text into sentences.""" + 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) @@ -114,7 +144,7 @@ def _split_document(self, doc: Document) -> List[Document]: return self._split_by_character(doc) def _concatenate_sentences_based_on_word_amount( # pylint: disable=too-many-positional-arguments - self, sentences: List[str], split_length: int, split_overlap: int, language: str, particle_size: str + self, sentences: List[str], split_length: int, split_overlap: int, particle_size: str ) -> Tuple[List[str], List[int], List[int]]: """ Groups the sentences into chunks of `split_length` words while respecting sentence boundaries. @@ -141,14 +171,14 @@ def _concatenate_sentences_based_on_word_amount( # pylint: disable=too-many-pos for sentence_idx, sentence in enumerate(sentences): current_chunk.append(sentence) - if language == "zh" and particle_size == "coarse": + if particle_size == "coarse": chunk_word_count += len(self.chinese_tokenizer_coarse(sentence)) next_sentence_word_count = ( len(self.chinese_tokenizer_coarse(sentences[sentence_idx + 1])) if sentence_idx < len(sentences) - 1 else 0 ) - if language == "zh" and particle_size == "fine": + if particle_size == "fine": chunk_word_count += len(self.chinese_tokenizer_fine(sentence)) next_sentence_word_count = ( len(self.chinese_tokenizer_fine(sentences[sentence_idx + 1])) @@ -169,7 +199,6 @@ def _concatenate_sentences_based_on_word_amount( # pylint: disable=too-many-pos sentences=current_chunk, split_length=split_length, split_overlap=split_overlap, - language=language, particle_size=particle_size, ) # Set up information for the new chunk @@ -198,15 +227,15 @@ def _concatenate_sentences_based_on_word_amount( # pylint: disable=too-many-pos return text_splits, split_start_page_numbers, split_start_indices - # Add Chinese sentence segmentation and enable it using language=="zh" def _split_by_nltk_sentence(self, doc: Document) -> List[Document]: - split_docs = [] - - if self.language == "zh": - result = self.chinese_sentence_split(doc.content) - if self.language == "en": - result = self.sentence_splitter.split_sentences(doc.content) # type: ignore # None check is done in run() + """ + Split Chinese text into sentences. + :param doc: The document to split. + :return: A list of split documents. + """ + split_docs = [] + result = self.chinese_sentence_split(doc.content) units = [sentence["sentence"] for sentence in result] if self.respect_sentence_boundary: @@ -214,7 +243,6 @@ def _split_by_nltk_sentence(self, doc: Document) -> List[Document]: sentences=units, split_length=self.split_length, split_overlap=self.split_overlap, - language=self.language, particle_size=self.particle_size, ) else: @@ -313,7 +341,7 @@ def _create_docs_from_splits( @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. @@ -337,7 +365,7 @@ def _add_split_overlap_information( previous_doc.meta["_split_overlap"].append({"doc_id": current_doc.id, "range": overlapping_range}) def _number_of_sentences_to_keep( # pylint: disable=too-many-positional-arguments - self, sentences: List[str], split_length: int, split_overlap: int, language: str, particle_size: str + self, sentences: List[str], split_length: int, split_overlap: int, particle_size: str ) -> int: """ Returns the number of sentences to keep in the next chunk based on the `split_overlap` and `split_length`. @@ -355,9 +383,9 @@ def _number_of_sentences_to_keep( # pylint: disable=too-many-positional-argumen num_words = 0 for sent in reversed(sentences[1:]): - if language == "zh" and particle_size == "coarse": + if particle_size == "coarse": num_words += len(self.chinese_tokenizer_coarse(sent)) - if language == "zh" and particle_size == "fine": + if particle_size == "fine": num_words += len(self.chinese_tokenizer_fine(sent)) # If the number of words is larger than the split_length then don't add any more sentences if num_words > split_length: @@ -366,3 +394,27 @@ def _number_of_sentences_to_keep( # pylint: disable=too-many-positional-argumen 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 self.splitting_function is None: + raise ValueError("No splitting function provided.") + + splits = self.splitting_function(doc.content) + if not isinstance(splits, list): + raise ValueError("The splitting function must return a list of strings.") + + 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, + ) diff --git a/integrations/hanlp/tests/test_chinese_document_splitter.py b/integrations/hanlp/tests/test_chinese_document_splitter.py index f6f1ddb4a..92092dcc9 100644 --- a/integrations/hanlp/tests/test_chinese_document_splitter.py +++ b/integrations/hanlp/tests/test_chinese_document_splitter.py @@ -4,7 +4,7 @@ import pytest from haystack import Document -from haystack.components.preprocessors.chinese_document_splitter import ChineseDocumentSplitter +from haystack_integrations.components.preprocessors.chinese_document_splitter import ChineseDocumentSplitter class TestChineseDocumentSplitter: @@ -29,10 +29,10 @@ def test_split_by_word(self, sample_text): not simply by single characters or spaces. """ splitter = ChineseDocumentSplitter( - split_by="word", language="zh", particle_size="coarse", split_length=5, split_overlap=0 + split_by="word", particle_size="coarse", split_length=5, split_overlap=0 ) - if hasattr(splitter, "warm_up"): - splitter.warm_up() + + splitter.warm_up() result = splitter.run(documents=[Document(content=sample_text)]) docs = result["documents"] @@ -43,10 +43,9 @@ def test_split_by_word(self, sample_text): @pytest.mark.integration def test_split_by_sentence(self, sample_text): splitter = ChineseDocumentSplitter( - split_by="sentence", language="zh", particle_size="coarse", split_length=10, split_overlap=0 + split_by="sentence", particle_size="coarse", split_length=10, split_overlap=0 ) - if hasattr(splitter, "warm_up"): - splitter.warm_up() + splitter.warm_up() result = splitter.run(documents=[Document(content=sample_text)]) docs = result["documents"] @@ -62,15 +61,15 @@ def test_respect_sentence_boundary(self): doc = Document(content=text) splitter = ChineseDocumentSplitter( - split_by="word", split_length=10, split_overlap=3, language="zh", respect_sentence_boundary=True + split_by="word", split_length=10, split_overlap=3, respect_sentence_boundary=True ) splitter.warm_up() result = splitter.run(documents=[doc]) docs = result["documents"] - print(f"Total chunks created: {len(docs)}.") + # print(f"Total chunks created: {len(docs)}.") for i, d in enumerate(docs): - print(f"\nChunk {i + 1}:\n{d.content}") + # print(f"\nChunk {i + 1}:\n{d.content}") # Optional: check that sentences are not cut off assert d.content.strip().endswith(("。", "!", "?")), "Sentence was cut off!" @@ -92,17 +91,16 @@ def test_overlap_chunks_with_long_text(self): doc = Document(content=text) splitter = ChineseDocumentSplitter( - split_by="word", language="zh", split_length=30, split_overlap=10, particle_size="coarse" + split_by="word", split_length=30, split_overlap=10, particle_size="coarse" ) - if hasattr(splitter, "warm_up"): - splitter.warm_up() + splitter.warm_up() result = splitter.run(documents=[doc]) docs = result["documents"] - print(f"Total chunks generated: {len(docs)}.") - for i, d in enumerate(docs): - print(f"\nChunk {i + 1}:\n{d.content}") + # print(f"Total chunks generated: {len(docs)}.") + # for i, d in enumerate(docs): + # print(f"\nChunk {i + 1}:\n{d.content}") assert len(docs) > 1, "Expected multiple chunks to be generated" From b803e7cc99a78d2c635e15444d48446d6438a27a Mon Sep 17 00:00:00 2001 From: Julian Risch Date: Wed, 18 Jun 2025 23:20:13 +0200 Subject: [PATCH 22/34] fmt --- .../chinese_document_splitter.py | 27 ++++++++++++------- .../tests/test_chinese_document_splitter.py | 3 ++- 2 files changed, 20 insertions(+), 10 deletions(-) diff --git a/integrations/hanlp/src/haystack_integrations/components/preprocessors/chinese_document_splitter.py b/integrations/hanlp/src/haystack_integrations/components/preprocessors/chinese_document_splitter.py index c53401bb7..3edc6b342 100644 --- a/integrations/hanlp/src/haystack_integrations/components/preprocessors/chinese_document_splitter.py +++ b/integrations/hanlp/src/haystack_integrations/components/preprocessors/chinese_document_splitter.py @@ -1,13 +1,12 @@ # SPDX-FileCopyrightText: 2025-present deepset GmbH # # SPDX-License-Identifier: Apache-2.0 -import hanlp from copy import deepcopy -from typing import Any, Dict, List, Literal, Tuple, Optional, Callable - -from more_itertools import windowed +from typing import Any, Callable, Dict, List, Literal, Optional, Tuple +import hanlp from haystack import Document, component, logging +from more_itertools import windowed logger = logging.getLogger(__name__) @@ -52,7 +51,11 @@ def __init__( self.particle_size = particle_size if particle_size not in ["coarse", "fine"]: - raise ValueError(f"Invalid particle_size '{particle_size}'. Choose either 'coarse' or 'fine'.") + msg = ( + f"Invalid particle_size '{particle_size}'. " + "Choose either 'coarse' or 'fine'." + ) + raise ValueError(msg) def run(self, documents: List[Document]) -> Dict[str, List[Document]]: @@ -65,8 +68,12 @@ def run(self, documents: List[Document]) -> Dict[str, List[Document]]: :raises RuntimeError: If the Chinese word segmentation model is not loaded. """ if self.split_sent is None: - raise RuntimeError("The Chinese word segmentation model is not loaded. Please run 'warm_up()' before calling 'run()'.") - + 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)) @@ -403,11 +410,13 @@ def _split_by_function(self, doc: Document) -> List[Document]: :return: A list of split documents. """ if self.splitting_function is None: - raise ValueError("No splitting function provided.") + msg = "No splitting function provided." + raise ValueError(msg) splits = self.splitting_function(doc.content) if not isinstance(splits, list): - raise ValueError("The splitting function must return a list of strings.") + msg = "The splitting function must return a list of strings." + raise ValueError(msg) metadata = deepcopy(doc.meta) metadata["source_id"] = doc.id diff --git a/integrations/hanlp/tests/test_chinese_document_splitter.py b/integrations/hanlp/tests/test_chinese_document_splitter.py index 92092dcc9..861d7c87e 100644 --- a/integrations/hanlp/tests/test_chinese_document_splitter.py +++ b/integrations/hanlp/tests/test_chinese_document_splitter.py @@ -4,6 +4,7 @@ import pytest from haystack import Document + from haystack_integrations.components.preprocessors.chinese_document_splitter import ChineseDocumentSplitter @@ -68,7 +69,7 @@ def test_respect_sentence_boundary(self): docs = result["documents"] # print(f"Total chunks created: {len(docs)}.") - for i, d in enumerate(docs): + for d in enumerate(docs): # print(f"\nChunk {i + 1}:\n{d.content}") # Optional: check that sentences are not cut off assert d.content.strip().endswith(("。", "!", "?")), "Sentence was cut off!" From 3a18f8d427622ab27fb0e430f21b9629b182c94a Mon Sep 17 00:00:00 2001 From: Julian Risch Date: Wed, 18 Jun 2025 23:27:43 +0200 Subject: [PATCH 23/34] fmt --- integrations/hanlp/pyproject.toml | 1 + .../chinese_document_splitter.py | 15 ++++----------- .../tests/test_chinese_document_splitter.py | 19 +++++++++++-------- 3 files changed, 16 insertions(+), 19 deletions(-) diff --git a/integrations/hanlp/pyproject.toml b/integrations/hanlp/pyproject.toml index b45ef1880..b0bd5290e 100644 --- a/integrations/hanlp/pyproject.toml +++ b/integrations/hanlp/pyproject.toml @@ -133,6 +133,7 @@ ignore = [ "ARG001", "ARG002", "ARG005", + "RUF001", ] unfixable = [ # Don't touch unused imports diff --git a/integrations/hanlp/src/haystack_integrations/components/preprocessors/chinese_document_splitter.py b/integrations/hanlp/src/haystack_integrations/components/preprocessors/chinese_document_splitter.py index 3edc6b342..7a8cd02c8 100644 --- a/integrations/hanlp/src/haystack_integrations/components/preprocessors/chinese_document_splitter.py +++ b/integrations/hanlp/src/haystack_integrations/components/preprocessors/chinese_document_splitter.py @@ -32,7 +32,8 @@ def __init__( 'coarse' represents coarse granularity Chinese word segmentation, 'fine' represents fine granularity word segmentation, default is coarse granularity word segmentation. - :param split_by: The unit by which the text is split. Can be one of: "word", "sentence", "passage", "page", "line", "period", "function". + :param split_by: The unit by which the text is split. Can be one of: \ + "word", "sentence", "passage", "page", "line", "period", "function". :param split_length: The maximum number of words in each split. :param split_overlap: The number of overlapping words in each split. :param split_threshold: The minimum number of words in each split. @@ -51,13 +52,9 @@ def __init__( self.particle_size = particle_size if particle_size not in ["coarse", "fine"]: - msg = ( - f"Invalid particle_size '{particle_size}'. " - "Choose either 'coarse' or 'fine'." - ) + msg = f"Invalid particle_size '{particle_size}'. Choose either 'coarse' or 'fine'." raise ValueError(msg) - def run(self, documents: List[Document]) -> Dict[str, List[Document]]: """ Split documents into smaller chunks. @@ -68,10 +65,7 @@ def run(self, documents: List[Document]) -> Dict[str, List[Document]]: :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()'." - ) + msg = "The Chinese word segmentation model is not loaded. Please run 'warm_up()' before calling 'run()'." raise RuntimeError(msg) split_docs = [] @@ -87,7 +81,6 @@ def warm_up(self) -> None: self.chinese_tokenizer_fine = 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 diff --git a/integrations/hanlp/tests/test_chinese_document_splitter.py b/integrations/hanlp/tests/test_chinese_document_splitter.py index 861d7c87e..fc0e3f6ea 100644 --- a/integrations/hanlp/tests/test_chinese_document_splitter.py +++ b/integrations/hanlp/tests/test_chinese_document_splitter.py @@ -11,7 +11,10 @@ class TestChineseDocumentSplitter: @pytest.fixture def sample_text(self) -> str: - return "这是第一句话,也是故事的开端,紧接着是第二句话,渐渐引出了背景;随后,翻开新/f的一页,我们读到了这一页的第一句话,继续延展出情节的发展,直到这页的第二句话将整段文字温柔地收束于平静之中。" + return ( + "这是第一句话,也是故事的开端,紧接着是第二句话,渐渐引出了背景;随后,翻开新/f的一页," + "我们读到了这一页的第一句话,继续延展出情节的发展,直到这页的第二句话将整段文字温柔地收束于平静之中。" + ) @pytest.mark.integration def test_split_by_word(self, sample_text): @@ -29,9 +32,7 @@ def test_split_by_word(self, sample_text): Therefore, splitting by word means splitting by these multi-character tokens, not simply by single characters or spaces. """ - splitter = ChineseDocumentSplitter( - split_by="word", particle_size="coarse", split_length=5, split_overlap=0 - ) + splitter = ChineseDocumentSplitter(split_by="word", particle_size="coarse", split_length=5, split_overlap=0) splitter.warm_up() @@ -58,7 +59,11 @@ def test_split_by_sentence(self, sample_text): @pytest.mark.integration def test_respect_sentence_boundary(self): """Test that respect_sentence_boundary=True avoids splitting sentences""" - text = "这是第一句话,这是第二句话,这是第三句话。这是第四句话,这是第五句话,这是第六句话!这是第七句话,这是第八句话,这是第九句话?" + text = ( + "这是第一句话,这是第二句话,这是第三句话。" + "这是第四句话,这是第五句话,这是第六句话!" + "这是第七句话,这是第八句话,这是第九句话?" + ) doc = Document(content=text) splitter = ChineseDocumentSplitter( @@ -91,9 +96,7 @@ def test_overlap_chunks_with_long_text(self): ) doc = Document(content=text) - splitter = ChineseDocumentSplitter( - split_by="word", split_length=30, split_overlap=10, particle_size="coarse" - ) + splitter = ChineseDocumentSplitter(split_by="word", split_length=30, split_overlap=10, particle_size="coarse") splitter.warm_up() result = splitter.run(documents=[doc]) From ec070b237bab45e093bb753f2c9911ece7632fa1 Mon Sep 17 00:00:00 2001 From: Julian Risch Date: Wed, 18 Jun 2025 23:46:10 +0200 Subject: [PATCH 24/34] align Hatch script of hanlp with other integrations --- integrations/hanlp/pyproject.toml | 33 ++++++++++++++++++------------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/integrations/hanlp/pyproject.toml b/integrations/hanlp/pyproject.toml index b0bd5290e..4fff04611 100644 --- a/integrations/hanlp/pyproject.toml +++ b/integrations/hanlp/pyproject.toml @@ -57,7 +57,7 @@ dependencies = [ "pytest-cov", "pytest-rerunfailures", "mypy", - "pip", + "pip" ] [tool.hatch.envs.test.scripts] @@ -66,19 +66,15 @@ 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}""" +types = "mypy --install-types --non-interactive --explicit-package-bases {args:src/ tests}" -[tool.mypy] -install_types = true -non_interactive = true -check_untyped_defs = true -disallow_incomplete_defs = true +[tool.hatch.envs.lint] +installer = "uv" +detached = true +dependencies = ["pip", "black>=23.1.0", "mypy>=1.0.0", "ruff>=0.0.243"] -[[tool.mypy.overrides]] -module = [ -"hanlp.*", -] -ignore_missing_imports = true +[tool.hatch.envs.lint.scripts] +typing = "mypy --install-types --non-interactive --explicit-package-bases {args:src/ tests}" [tool.black] target-version = ["py38"] @@ -153,17 +149,26 @@ ban-relative-imports = "parents" [tool.coverage.run] source = ["haystack_integrations"] branch = true -parallel = true +parallel = false [tool.coverage.report] omit = ["*/tests/*", "*/__init__.py"] show_missing = true exclude_lines = ["no cov", "if __name__ == .__main__.:", "if TYPE_CHECKING:"] +[[tool.mypy.overrides]] +module = [ + "hanlp.*", + "haystack.*", + "haystack_integrations.*", + "pytest.*", +] +ignore_missing_imports = true + [tool.pytest.ini_options] addopts = "--strict-markers" markers = [ - "unit: unit tests", "integration: integration tests", + "unit: unit tests", ] log_cli = true From bbfce8e40f092ed4128fe1899e768992d89db7b5 Mon Sep 17 00:00:00 2001 From: Julian Risch Date: Wed, 18 Jun 2025 23:51:37 +0200 Subject: [PATCH 25/34] lint:typing more_itertools --- integrations/hanlp/pyproject.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/integrations/hanlp/pyproject.toml b/integrations/hanlp/pyproject.toml index 4fff04611..c2fd494b7 100644 --- a/integrations/hanlp/pyproject.toml +++ b/integrations/hanlp/pyproject.toml @@ -162,6 +162,7 @@ module = [ "haystack.*", "haystack_integrations.*", "pytest.*", + "more_itertools.*", ] ignore_missing_imports = true From 0f90ce148dfde7b43b3ad6f252a742c782a35991 Mon Sep 17 00:00:00 2001 From: Julian Risch Date: Thu, 19 Jun 2025 00:16:55 +0200 Subject: [PATCH 26/34] move files to hanlp directory --- .../components/preprocessors/{ => hanlp}/__init__.py | 0 .../preprocessors/{ => hanlp}/chinese_document_splitter.py | 0 integrations/hanlp/tests/test_chinese_document_splitter.py | 2 +- 3 files changed, 1 insertion(+), 1 deletion(-) rename integrations/hanlp/src/haystack_integrations/components/preprocessors/{ => hanlp}/__init__.py (100%) rename integrations/hanlp/src/haystack_integrations/components/preprocessors/{ => hanlp}/chinese_document_splitter.py (100%) diff --git a/integrations/hanlp/src/haystack_integrations/components/preprocessors/__init__.py b/integrations/hanlp/src/haystack_integrations/components/preprocessors/hanlp/__init__.py similarity index 100% rename from integrations/hanlp/src/haystack_integrations/components/preprocessors/__init__.py rename to integrations/hanlp/src/haystack_integrations/components/preprocessors/hanlp/__init__.py diff --git a/integrations/hanlp/src/haystack_integrations/components/preprocessors/chinese_document_splitter.py b/integrations/hanlp/src/haystack_integrations/components/preprocessors/hanlp/chinese_document_splitter.py similarity index 100% rename from integrations/hanlp/src/haystack_integrations/components/preprocessors/chinese_document_splitter.py rename to integrations/hanlp/src/haystack_integrations/components/preprocessors/hanlp/chinese_document_splitter.py diff --git a/integrations/hanlp/tests/test_chinese_document_splitter.py b/integrations/hanlp/tests/test_chinese_document_splitter.py index fc0e3f6ea..25d95d064 100644 --- a/integrations/hanlp/tests/test_chinese_document_splitter.py +++ b/integrations/hanlp/tests/test_chinese_document_splitter.py @@ -5,7 +5,7 @@ import pytest from haystack import Document -from haystack_integrations.components.preprocessors.chinese_document_splitter import ChineseDocumentSplitter +from haystack_integrations.components.preprocessors.hanlp import ChineseDocumentSplitter class TestChineseDocumentSplitter: From 7ac831ad80030bdcf5ed45ec0e3d3c9307bf3aca Mon Sep 17 00:00:00 2001 From: Julian Risch Date: Thu, 19 Jun 2025 00:18:46 +0200 Subject: [PATCH 27/34] fix tests using enumerate only for prints --- integrations/hanlp/tests/test_chinese_document_splitter.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/integrations/hanlp/tests/test_chinese_document_splitter.py b/integrations/hanlp/tests/test_chinese_document_splitter.py index 25d95d064..2c4655fdf 100644 --- a/integrations/hanlp/tests/test_chinese_document_splitter.py +++ b/integrations/hanlp/tests/test_chinese_document_splitter.py @@ -74,10 +74,10 @@ def test_respect_sentence_boundary(self): docs = result["documents"] # print(f"Total chunks created: {len(docs)}.") - for d in enumerate(docs): - # print(f"\nChunk {i + 1}:\n{d.content}") + for doc in docs: + # print(f"\nChunk {i + 1}:\n{doc.content}") # Optional: check that sentences are not cut off - assert d.content.strip().endswith(("。", "!", "?")), "Sentence was cut off!" + assert doc.content.strip().endswith(("。", "!", "?")), "Sentence was cut off!" @pytest.mark.integration def test_overlap_chunks_with_long_text(self): From 928d949483ebecdc5796f9041ae96669018654cb Mon Sep 17 00:00:00 2001 From: Julian Risch Date: Thu, 19 Jun 2025 00:19:20 +0200 Subject: [PATCH 28/34] fmt --- .../preprocessors/hanlp/chinese_document_splitter.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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 index 7a8cd02c8..079a8d0cb 100644 --- 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 @@ -4,10 +4,11 @@ from copy import deepcopy from typing import Any, Callable, Dict, List, Literal, Optional, Tuple -import hanlp from haystack import Document, component, logging from more_itertools import windowed +import hanlp + logger = logging.getLogger(__name__) # mapping of split by character, 'function' and 'sentence' don't split by character From 5f779039aa0da9fbf409c55b91f770310cb66a6c Mon Sep 17 00:00:00 2001 From: Julian Risch Date: Thu, 19 Jun 2025 00:34:57 +0200 Subject: [PATCH 29/34] add unit tests, handle edge case when split_length < split_overlap --- .../hanlp/chinese_document_splitter.py | 14 ++++++- .../tests/test_chinese_document_splitter.py | 42 +++++++++++++++++++ 2 files changed, 55 insertions(+), 1 deletion(-) 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 index 079a8d0cb..6cc98ccab 100644 --- 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 @@ -272,12 +272,24 @@ def _concatenate_units( 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=split_length - split_overlap) + segments = windowed(elements, n=split_length, step=step) for seg in segments: current_units = [unit for unit in seg if unit is not None] diff --git a/integrations/hanlp/tests/test_chinese_document_splitter.py b/integrations/hanlp/tests/test_chinese_document_splitter.py index 2c4655fdf..9d84f087a 100644 --- a/integrations/hanlp/tests/test_chinese_document_splitter.py +++ b/integrations/hanlp/tests/test_chinese_document_splitter.py @@ -9,6 +9,48 @@ class TestChineseDocumentSplitter: + def test_empty_document(self): + """Test that an empty document returns an empty list""" + splitter = ChineseDocumentSplitter() + doc = Document(content="") + splitter.warm_up() + results = splitter.run([doc]) + assert results["documents"] == [] + + def test_whitespace_only_document(self): + """Test that a document containing only whitespaces is handled correctly""" + splitter = ChineseDocumentSplitter() + doc = Document(content=" ") + splitter.warm_up() + results = splitter.run([doc]) + assert len(results["documents"]) == 0 + + def test_copy_metadata(self): + """Test that metadata is properly copied to split documents""" + splitter = ChineseDocumentSplitter(split_by="word", split_length=5) + documents = [ + Document(content="这是测试文本。", meta={"name": "doc 0"}), + Document(content="这是另一个测试文本。", meta={"name": "doc 1"}), + ] + splitter.warm_up() + result = splitter.run(documents=documents) + assert len(result["documents"]) > 0 + for doc, split_doc in zip(documents, result["documents"]): + assert doc.meta.items() <= split_doc.meta.items() + + def test_source_id_stored_in_metadata(self): + """Test that source document ID is stored in metadata of split documents""" + splitter = ChineseDocumentSplitter(split_by="word", split_length=5) + doc1 = Document(content="这是第一个测试文本。") + doc2 = Document(content="这是第二个测试文本。") + splitter.warm_up() + result = splitter.run(documents=[doc1, doc2]) + assert len(result["documents"]) > 0 + # Check that each split document has a source_id + for doc in result["documents"]: + assert "source_id" in doc.meta + assert doc.meta["source_id"] in [doc1.id, doc2.id] + @pytest.fixture def sample_text(self) -> str: return ( From 797d2948b7d22729adae1454a2f0a6ab4b9f348b Mon Sep 17 00:00:00 2001 From: Julian Risch Date: Thu, 19 Jun 2025 01:02:02 +0200 Subject: [PATCH 30/34] stop testing on windows + python 3.13 --- .github/workflows/hanlp.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.github/workflows/hanlp.yml b/.github/workflows/hanlp.yml index b05814c1d..36de06fd7 100644 --- a/.github/workflows/hanlp.yml +++ b/.github/workflows/hanlp.yml @@ -33,6 +33,12 @@ jobs: 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' From af7015fe6908b1d0df813f1f4192ee222fa4c825 Mon Sep 17 00:00:00 2001 From: Julian Risch Date: Thu, 19 Jun 2025 18:58:10 +0200 Subject: [PATCH 31/34] refactor tests, add usage example, simplify tokenizers --- .../hanlp/chinese_document_splitter.py | 92 +++++++++----- .../tests/test_chinese_document_splitter.py | 116 +++++++----------- 2 files changed, 103 insertions(+), 105 deletions(-) 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 index 6cc98ccab..86697b0b2 100644 --- 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 @@ -17,6 +17,37 @@ @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", @@ -28,18 +59,25 @@ def __init__( particle_size: Literal["coarse", "fine"] = "coarse", ): """ - A DocumentSplitter for Chinese text. - - 'coarse' represents coarse granularity Chinese word segmentation, 'fine' represents fine granularity word - segmentation, default is coarse granularity word segmentation. - - :param split_by: The unit by which the text is split. Can be one of: \ - "word", "sentence", "passage", "page", "line", "period", "function". - :param split_length: The maximum number of words in each split. - :param split_overlap: The number of overlapping words in each split. - :param split_threshold: The minimum number of words in each split. - :param respect_sentence_boundary: Whether to respect sentence boundaries when splitting. - :param splitting_function: A custom function to split the text. + 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 particle_size: The granularity of Chinese word segmentation, either 'coarse' or 'fine'. :raises ValueError: If the particle_size is not 'coarse' or 'fine'. @@ -77,9 +115,9 @@ def run(self, documents: List[Document]) -> Dict[str, List[Document]]: def warm_up(self) -> None: """Warm up the component by loading the necessary models.""" if self.particle_size == "coarse": - self.chinese_tokenizer_coarse = hanlp.load(hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH) + self.chinese_tokenizer = hanlp.load(hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH) if self.particle_size == "fine": - self.chinese_tokenizer_fine = hanlp.load(hanlp.pretrained.tok.FINE_ELECTRA_SMALL_ZH) + 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]: @@ -95,11 +133,8 @@ def _split_by_character(self, doc: Document) -> List[Document]: # 'fine' represents fine granularity word segmentation, # default is coarse granularity word segmentation - if self.particle_size == "coarse": - units = self.chinese_tokenizer_coarse(doc.content) - - if self.particle_size == "fine": - units = self.chinese_tokenizer_fine(doc.content) + if self.particle_size in {"coarse", "fine"}: + units = self.chinese_tokenizer(doc.content) for i in range(len(units) - 1): # pylint: disable=possibly-used-before-assignment units[i] += split_at @@ -172,17 +207,10 @@ def _concatenate_sentences_based_on_word_amount( # pylint: disable=too-many-pos for sentence_idx, sentence in enumerate(sentences): current_chunk.append(sentence) - if particle_size == "coarse": - chunk_word_count += len(self.chinese_tokenizer_coarse(sentence)) - next_sentence_word_count = ( - len(self.chinese_tokenizer_coarse(sentences[sentence_idx + 1])) - if sentence_idx < len(sentences) - 1 - else 0 - ) - if particle_size == "fine": - chunk_word_count += len(self.chinese_tokenizer_fine(sentence)) + if particle_size in {"coarse", "fine"}: + chunk_word_count += len(self.chinese_tokenizer(sentence)) next_sentence_word_count = ( - len(self.chinese_tokenizer_fine(sentences[sentence_idx + 1])) + len(self.chinese_tokenizer(sentences[sentence_idx + 1])) if sentence_idx < len(sentences) - 1 else 0 ) @@ -396,10 +424,8 @@ def _number_of_sentences_to_keep( # pylint: disable=too-many-positional-argumen num_words = 0 for sent in reversed(sentences[1:]): - if particle_size == "coarse": - num_words += len(self.chinese_tokenizer_coarse(sent)) - if particle_size == "fine": - num_words += len(self.chinese_tokenizer_fine(sent)) + if particle_size in {"coarse", "fine"}: + 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 diff --git a/integrations/hanlp/tests/test_chinese_document_splitter.py b/integrations/hanlp/tests/test_chinese_document_splitter.py index 9d84f087a..9f17f284a 100644 --- a/integrations/hanlp/tests/test_chinese_document_splitter.py +++ b/integrations/hanlp/tests/test_chinese_document_splitter.py @@ -9,80 +9,72 @@ class TestChineseDocumentSplitter: + @pytest.fixture + def sample_text(self) -> str: + return ( + "这是第一句话,也是故事的开端,紧接着是第二句话,渐渐引出了背景;随后,翻开新/f的一页," + "我们读到了这一页的第一句话,继续延展出情节的发展,直到这页的第二句话将整段文字温柔地收束于平静之中。" + ) + + @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): - """Test that an empty document returns an empty list""" splitter = ChineseDocumentSplitter() - doc = Document(content="") + documents = [Document(content="")] splitter.warm_up() - results = splitter.run([doc]) - assert results["documents"] == [] + results = splitter.run(documents=documents) + assert results == {"documents": []} + @pytest.mark.integration def test_whitespace_only_document(self): - """Test that a document containing only whitespaces is handled correctly""" splitter = ChineseDocumentSplitter() - doc = Document(content=" ") + documents = [Document(content=" ")] splitter.warm_up() - results = splitter.run([doc]) + results = splitter.run(documents=documents) assert len(results["documents"]) == 0 - def test_copy_metadata(self): - """Test that metadata is properly copied to split documents""" - splitter = ChineseDocumentSplitter(split_by="word", split_length=5) + @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) splitter.warm_up() result = splitter.run(documents=documents) - assert len(result["documents"]) > 0 + 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): - """Test that source document ID is stored in metadata of split documents""" + documents = [ + Document(content="这是第一个测试文本。"), + Document(content="这是第二个测试文本。"), + ] splitter = ChineseDocumentSplitter(split_by="word", split_length=5) - doc1 = Document(content="这是第一个测试文本。") - doc2 = Document(content="这是第二个测试文本。") splitter.warm_up() - result = splitter.run(documents=[doc1, doc2]) - assert len(result["documents"]) > 0 - # Check that each split document has a source_id - for doc in result["documents"]: - assert "source_id" in doc.meta - assert doc.meta["source_id"] in [doc1.id, doc2.id] - - @pytest.fixture - def sample_text(self) -> str: - return ( - "这是第一句话,也是故事的开端,紧接着是第二句话,渐渐引出了背景;随后,翻开新/f的一页," - "我们读到了这一页的第一句话,继续延展出情节的发展,直到这页的第二句话将整段文字温柔地收束于平静之中。" - ) + 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): - """ - Test splitting by word. - - Note on Chinese words: - 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. - """ splitter = ChineseDocumentSplitter(split_by="word", particle_size="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) - assert all(len(doc.content.strip()) <= 10 for doc in docs) + expected_lengths = [9, 9, 8, 8, 6, 6, 6, 8, 8, 6, 7, 8, 5] + actual_lengths = [len(doc.content.strip()) for doc in docs] + assert actual_lengths == expected_lengths @pytest.mark.integration def test_split_by_sentence(self, sample_text): @@ -90,41 +82,30 @@ def test_split_by_sentence(self, sample_text): split_by="sentence", particle_size="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) assert all(doc.content.strip() != "" for doc in docs) assert any("。" in doc.content for doc in docs), "Expected at least one chunk containing a full stop." @pytest.mark.integration def test_respect_sentence_boundary(self): - """Test that respect_sentence_boundary=True avoids splitting sentences""" - text = ( + doc = Document(content= "这是第一句话,这是第二句话,这是第三句话。" "这是第四句话,这是第五句话,这是第六句话!" "这是第七句话,这是第八句话,这是第九句话?" ) - doc = Document(content=text) - 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"] - - # print(f"Total chunks created: {len(docs)}.") - for doc in docs: - # print(f"\nChunk {i + 1}:\n{doc.content}") - # Optional: check that sentences are not cut off - assert doc.content.strip().endswith(("。", "!", "?")), "Sentence was cut off!" + assert all(doc.content.strip().endswith(("。", "!", "?")) for doc in docs), "Sentence was cut off!" @pytest.mark.integration def test_overlap_chunks_with_long_text(self): - """Test split_overlap parameter to ensure there is clear overlap between chunks of long text""" - text = ( + doc = Document(content= "月光轻轻洒落,林中传来阵阵狼嚎,夜色悄然笼罩一切。" "树叶在微风中沙沙作响,影子在地面上摇曳不定。" "一只猫头鹰静静地眨了眨眼,从枝头注视着四周……" @@ -136,24 +117,15 @@ def test_overlap_chunks_with_long_text(self): "时间仿佛停滞了……" "万物静候,聆听着夜的呼吸!" ) - doc = Document(content=text) splitter = ChineseDocumentSplitter(split_by="word", split_length=30, split_overlap=10, particle_size="coarse") splitter.warm_up() - result = splitter.run(documents=[doc]) docs = result["documents"] - - # print(f"Total chunks generated: {len(docs)}.") - # for i, d in enumerate(docs): - # print(f"\nChunk {i + 1}:\n{d.content}") - - assert len(docs) > 1, "Expected multiple chunks to be generated" - - max_len_allowed = 80 # Allow a somewhat relaxed max chunk length - assert all(len(doc.content) <= max_len_allowed for doc in docs), ( - f"Some chunks exceed {max_len_allowed} characters" - ) + 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: """ From 3909a25fa0d39ef5dc51fd64cc9ebc2c93886ba4 Mon Sep 17 00:00:00 2001 From: Julian Risch Date: Thu, 19 Jun 2025 19:32:33 +0200 Subject: [PATCH 32/34] add py.typed --- .github/workflows/hanlp.yml | 4 +-- integrations/hanlp/pyproject.toml | 34 ++++++++----------- .../hanlp/chinese_document_splitter.py | 21 +++++++++--- .../components/preprocessors/py.typed | 0 4 files changed, 33 insertions(+), 26 deletions(-) create mode 100644 integrations/hanlp/src/haystack_integrations/components/preprocessors/py.typed diff --git a/.github/workflows/hanlp.yml b/.github/workflows/hanlp.yml index 36de06fd7..7734892f9 100644 --- a/.github/workflows/hanlp.yml +++ b/.github/workflows/hanlp.yml @@ -55,11 +55,9 @@ jobs: - name: Install Hatch run: pip install --upgrade hatch - # TODO: Once this integration is properly typed, use hatch run test:types - # https://github.com/deepset-ai/haystack-core-integrations/issues/1771 - name: Lint if: matrix.python-version == '3.9' && runner.os == 'Linux' - run: hatch run fmt-check && hatch run lint:typing + run: hatch run fmt-check && hatch run test:types - name: Generate docs if: matrix.python-version == '3.9' && runner.os == 'Linux' diff --git a/integrations/hanlp/pyproject.toml b/integrations/hanlp/pyproject.toml index c2fd494b7..6a87c2494 100644 --- a/integrations/hanlp/pyproject.toml +++ b/integrations/hanlp/pyproject.toml @@ -23,7 +23,10 @@ classifiers = [ "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", ] -dependencies = ["haystack-ai>=2.13.1", "hanlp>=2.1.1"] +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" @@ -66,15 +69,19 @@ integration = 'pytest -m "integration" {args:tests}' all = 'pytest {args:tests}' cov-retry = 'all --cov=haystack_integrations --reruns 3 --reruns-delay 30 -x' -types = "mypy --install-types --non-interactive --explicit-package-bases {args:src/ tests}" +types = """mypy -p haystack_integrations.components.preprocessors.hanlp {args}""" -[tool.hatch.envs.lint] -installer = "uv" -detached = true -dependencies = ["pip", "black>=23.1.0", "mypy>=1.0.0", "ruff>=0.0.243"] +[tool.mypy] +install_types = true +non_interactive = true +check_untyped_defs = true +disallow_incomplete_defs = true -[tool.hatch.envs.lint.scripts] -typing = "mypy --install-types --non-interactive --explicit-package-bases {args:src/ tests}" +[[tool.mypy.overrides]] +module = [ +"hanlp.*", +] +ignore_missing_imports = true [tool.black] target-version = ["py38"] @@ -156,20 +163,9 @@ omit = ["*/tests/*", "*/__init__.py"] show_missing = true exclude_lines = ["no cov", "if __name__ == .__main__.:", "if TYPE_CHECKING:"] -[[tool.mypy.overrides]] -module = [ - "hanlp.*", - "haystack.*", - "haystack_integrations.*", - "pytest.*", - "more_itertools.*", -] -ignore_missing_imports = true - [tool.pytest.ini_options] addopts = "--strict-markers" markers = [ "integration: integration tests", - "unit: unit tests", ] log_cli = true 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 index 86697b0b2..410731638 100644 --- 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 @@ -127,6 +127,9 @@ def _split_by_character(self, doc: Document) -> List[Document]: :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] # 'coarse' represents coarse granularity Chinese word segmentation, @@ -172,7 +175,7 @@ def chinese_sentence_split(self, text: str) -> List[Dict[str, Any]]: def _split_document(self, doc: Document) -> List[Document]: if self.split_by == "sentence" or self.respect_sentence_boundary: - return self._split_by_nltk_sentence(doc) + 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) @@ -186,7 +189,7 @@ def _concatenate_sentences_based_on_word_amount( # pylint: disable=too-many-pos 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 NLTK sentence tokenizer. + with HanLP sentence tokenizer. :param sentences: The list of sentences to split. :param split_length: The maximum number of words in each split. @@ -256,13 +259,16 @@ def _concatenate_sentences_based_on_word_amount( # pylint: disable=too-many-pos return text_splits, split_start_page_numbers, split_start_indices - def _split_by_nltk_sentence(self, doc: Document) -> List[Document]: + 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] @@ -376,7 +382,8 @@ def _create_docs_from_splits( self._add_split_overlap_information(doc, doc_start_idx, previous_doc, previous_doc_start_idx) for d in documents: - d.content = d.content.replace(" ", "") + if d.content is not None: + d.content = d.content.replace(" ", "") return documents @staticmethod @@ -391,6 +398,9 @@ def _add_split_overlap_information( :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)) # type: ignore if overlapping_range[0] < overlapping_range[1]: @@ -441,6 +451,9 @@ def _split_by_function(self, doc: Document) -> List[Document]: :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) 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 From 2460646231155a2bd9053a632f078c45cae8a237 Mon Sep 17 00:00:00 2001 From: Julian Risch Date: Thu, 19 Jun 2025 19:35:16 +0200 Subject: [PATCH 33/34] ignore RUF002, fmt --- integrations/hanlp/pyproject.toml | 1 + .../preprocessors/hanlp/chinese_document_splitter.py | 5 ++--- .../hanlp/tests/test_chinese_document_splitter.py | 8 ++++---- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/integrations/hanlp/pyproject.toml b/integrations/hanlp/pyproject.toml index 6a87c2494..271eca87a 100644 --- a/integrations/hanlp/pyproject.toml +++ b/integrations/hanlp/pyproject.toml @@ -137,6 +137,7 @@ ignore = [ "ARG002", "ARG005", "RUF001", + "RUF002", ] unfixable = [ # Don't touch unused imports 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 index 410731638..4a82043c4 100644 --- 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 @@ -48,6 +48,7 @@ class ChineseDocumentSplitter: print(result["documents"]) ``` """ + def __init__( self, split_by: Literal["word", "sentence", "passage", "page", "line", "period", "function"] = "word", @@ -213,9 +214,7 @@ def _concatenate_sentences_based_on_word_amount( # pylint: disable=too-many-pos if particle_size in {"coarse", "fine"}: 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 + 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, diff --git a/integrations/hanlp/tests/test_chinese_document_splitter.py b/integrations/hanlp/tests/test_chinese_document_splitter.py index 9f17f284a..6e50c86ac 100644 --- a/integrations/hanlp/tests/test_chinese_document_splitter.py +++ b/integrations/hanlp/tests/test_chinese_document_splitter.py @@ -90,8 +90,8 @@ def test_split_by_sentence(self, sample_text): @pytest.mark.integration def test_respect_sentence_boundary(self): - doc = Document(content= - "这是第一句话,这是第二句话,这是第三句话。" + doc = Document( + content="这是第一句话,这是第二句话,这是第三句话。" "这是第四句话,这是第五句话,这是第六句话!" "这是第七句话,这是第八句话,这是第九句话?" ) @@ -105,8 +105,8 @@ def test_respect_sentence_boundary(self): @pytest.mark.integration def test_overlap_chunks_with_long_text(self): - doc = Document(content= - "月光轻轻洒落,林中传来阵阵狼嚎,夜色悄然笼罩一切。" + doc = Document( + content="月光轻轻洒落,林中传来阵阵狼嚎,夜色悄然笼罩一切。" "树叶在微风中沙沙作响,影子在地面上摇曳不定。" "一只猫头鹰静静地眨了眨眼,从枝头注视着四周……" "远处的小溪哗啦啦地流淌,仿佛在向石头倾诉着什么。" From 5e8fc7ba983b8a7243d8a76ceb061b23a5071e78 Mon Sep 17 00:00:00 2001 From: Julian Risch Date: Thu, 19 Jun 2025 19:46:29 +0200 Subject: [PATCH 34/34] to_dict, from_dict --- .../hanlp/chinese_document_splitter.py | 34 ++++++++- .../tests/test_chinese_document_splitter.py | 74 +++++++++++++++++++ 2 files changed, 107 insertions(+), 1 deletion(-) 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 index 4a82043c4..1c6fec98b 100644 --- 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 @@ -5,6 +5,8 @@ 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 @@ -91,7 +93,7 @@ def __init__( self.splitting_function = splitting_function self.particle_size = particle_size - if particle_size not in ["coarse", "fine"]: + if particle_size not in {"coarse", "fine"}: msg = f"Invalid particle_size '{particle_size}'. Choose either 'coarse' or 'fine'." raise ValueError(msg) @@ -471,3 +473,33 @@ def _split_by_function(self, doc: Document) -> List[Document]: 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, + particle_size=self.particle_size, + ) + 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/tests/test_chinese_document_splitter.py b/integrations/hanlp/tests/test_chinese_document_splitter.py index 6e50c86ac..eade9e9d8 100644 --- a/integrations/hanlp/tests/test_chinese_document_splitter.py +++ b/integrations/hanlp/tests/test_chinese_document_splitter.py @@ -4,10 +4,16 @@ 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: @@ -16,6 +22,74 @@ def sample_text(self) -> str: "我们读到了这一页的第一句话,继续延展出情节的发展,直到这页的第二句话将整段文字温柔地收束于平静之中。" ) + 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()