|
| 1 | +# Copyright 2021-2024 VMware, Inc. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +import json |
| 4 | +import logging |
| 5 | +import pathlib |
| 6 | +import re |
| 7 | +import string |
| 8 | + |
| 9 | +from config import CHUNK_OVERLAP |
| 10 | +from config import CHUNK_SIZE |
| 11 | +from config import CHUNKS_JSON_FILE |
| 12 | +from config import DOCUMENTS_JSON_FILE |
| 13 | +from nltk.tokenize import word_tokenize |
| 14 | +from vdk.api.job_input import IJobInput |
| 15 | + |
| 16 | +log = logging.getLogger(__name__) |
| 17 | + |
| 18 | + |
| 19 | +def custom_join(tokens): |
| 20 | + """ |
| 21 | + Joins a list of tokens into a string, adding a space between words |
| 22 | + but not between a word and following punctuation. |
| 23 | + """ |
| 24 | + result = "" |
| 25 | + for i, token in enumerate(tokens): |
| 26 | + if i == 0: |
| 27 | + result += token |
| 28 | + elif token in string.punctuation: |
| 29 | + result += token |
| 30 | + else: |
| 31 | + result += " " + token |
| 32 | + return result |
| 33 | + |
| 34 | + |
| 35 | +class ChunkerFactory: |
| 36 | + @staticmethod |
| 37 | + def get_chunker(strategy_name: str, **kwargs): |
| 38 | + chunkers = { |
| 39 | + "fixed": FixedSizeChunker, |
| 40 | + "wiki": WikiSectionChunker, |
| 41 | + } |
| 42 | + if strategy_name in chunkers: |
| 43 | + return ( |
| 44 | + chunkers[strategy_name](**kwargs) |
| 45 | + if strategy_name == "fixed" |
| 46 | + else chunkers[strategy_name]() |
| 47 | + ) |
| 48 | + else: |
| 49 | + raise ValueError( |
| 50 | + f"Unknown chunking strategy: {strategy_name}. " |
| 51 | + f"Supported strategies: {list(chunkers.keys())}" |
| 52 | + ) |
| 53 | + |
| 54 | + |
| 55 | +class Chunker: |
| 56 | + """ |
| 57 | + Splits text into chunks. One of the provided options must be chosen. |
| 58 | + """ |
| 59 | + |
| 60 | + def chunk(self, documents: dict): |
| 61 | + raise NotImplementedError("The chunking strategy is not supported.") |
| 62 | + |
| 63 | + |
| 64 | +class FixedSizeChunker(Chunker): |
| 65 | + """ |
| 66 | + Splits text into chunks of fixed size with overlap between neighbouring ones. |
| 67 | + """ |
| 68 | + |
| 69 | + def __init__(self, chunk_size, chunk_overlap): |
| 70 | + self.chunk_size = chunk_size |
| 71 | + self.chunk_overlap = chunk_overlap |
| 72 | + |
| 73 | + def chunk(self, documents): |
| 74 | + chunked_documents = [] |
| 75 | + for doc in documents: |
| 76 | + tokens = word_tokenize(doc["data"]) |
| 77 | + for i in range(0, len(tokens), self.chunk_size - self.chunk_overlap): |
| 78 | + chunk_id = f"{doc['metadata']['id']}_{i // (self.chunk_size - self.chunk_overlap)}" |
| 79 | + chunk_metadata = doc["metadata"].copy() |
| 80 | + chunk_metadata["id"] = chunk_id |
| 81 | + chunked_documents.append( |
| 82 | + { |
| 83 | + "metadata": chunk_metadata, |
| 84 | + "data": custom_join(tokens[i : i + self.chunk_size]), |
| 85 | + } |
| 86 | + ) |
| 87 | + return chunked_documents |
| 88 | + |
| 89 | + |
| 90 | +class WikiSectionChunker(Chunker): |
| 91 | + """ |
| 92 | + Splits Wiki articles into chunks. |
| 93 | + """ |
| 94 | + |
| 95 | + def __init__(self): |
| 96 | + pass |
| 97 | + |
| 98 | + def chunk(self, documents): |
| 99 | + chunked_documents = [] |
| 100 | + for doc in documents: |
| 101 | + sections = re.split( |
| 102 | + r"==+ [^=]+ ==", doc["data"] |
| 103 | + ) # Wiki section headers are identified by == |
| 104 | + for i, section in enumerate(sections): |
| 105 | + chunk_id = f"{doc['metadata']['id']}_{i}" |
| 106 | + chunk_metadata = doc["metadata"].copy() |
| 107 | + chunk_metadata["id"] = chunk_id |
| 108 | + chunked_documents.append( |
| 109 | + { |
| 110 | + "metadata": chunk_metadata, |
| 111 | + "data": section.strip(), |
| 112 | + } |
| 113 | + ) |
| 114 | + return chunked_documents |
| 115 | + |
| 116 | + |
| 117 | +def load_documents(json_file_path: str): |
| 118 | + """ |
| 119 | + Loads documents from JSON file. |
| 120 | +
|
| 121 | + :param json_file_path: Path to the JSON file containing documents. |
| 122 | + :return: List of documents. |
| 123 | + """ |
| 124 | + with open(json_file_path, encoding="utf-8") as file: |
| 125 | + return json.load(file) |
| 126 | + |
| 127 | + |
| 128 | +def store(name, content): |
| 129 | + json_data = json.dumps(content, indent=4) |
| 130 | + with open(name, "w") as file: |
| 131 | + file.write(json_data) |
| 132 | + |
| 133 | + |
| 134 | +def run(job_input: IJobInput): |
| 135 | + log.info(f"Starting job step {__name__}") |
| 136 | + |
| 137 | + data_job_dir = pathlib.Path(job_input.get_job_directory()) |
| 138 | + input_json = job_input.get_property("data_file", data_job_dir / DOCUMENTS_JSON_FILE) |
| 139 | + output_json = job_input.get_property("chunks_file", data_job_dir / CHUNKS_JSON_FILE) |
| 140 | + chunking_strategy = job_input.get_property("chunking_strategy", "fixed") |
| 141 | + chunk_size = CHUNK_SIZE |
| 142 | + chunk_overlap = CHUNK_OVERLAP |
| 143 | + |
| 144 | + documents = load_documents(input_json) |
| 145 | + print(documents) |
| 146 | + chunker = ChunkerFactory.get_chunker( |
| 147 | + chunking_strategy, chunk_size=chunk_size, chunk_overlap=chunk_overlap |
| 148 | + ) |
| 149 | + chunked_documents = chunker.chunk(documents) |
| 150 | + print(chunked_documents) |
| 151 | + if chunked_documents: |
| 152 | + log.info( |
| 153 | + f"{len(chunked_documents)} documents chunks created using the {chunking_strategy} chunking strategy." |
| 154 | + ) |
| 155 | + store(output_json, chunked_documents) |
| 156 | + log.info(f"Chunks saved to {output_json}") |
0 commit comments