Spaces:
Running
Running
File size: 10,595 Bytes
ba9f995 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 |
"""
This module save documents to embeddings and langchain Documents.
"""
import os
import glob
import pickle
from typing import List
from multiprocessing import Pool
from collections import deque
import hashlib
import tiktoken
from tqdm import tqdm
from langchain.schema import Document
from langchain.vectorstores import Chroma
from langchain.text_splitter import (
RecursiveCharacterTextSplitter,
)
from langchain.document_loaders import (
PyPDFLoader,
TextLoader,
)
from toolkit.utils import Config, choose_embeddings, clean_text
# Load the config file
configs = Config("configparser.ini")
os.environ["OPENAI_API_KEY"] = configs.openai_api_key
os.environ["ANTHROPIC_API_KEY"] = configs.anthropic_api_key
embedding_store_path = configs.db_dir
files_path = glob.glob(configs.docs_dir + "/*")
tokenizer_name = tiktoken.encoding_for_model("gpt-3.5-turbo")
tokenizer = tiktoken.get_encoding(tokenizer_name.name)
loaders = {
"pdf": (PyPDFLoader, {}),
"txt": (TextLoader, {}),
}
def tiktoken_len(text: str):
"""Calculate the token length of a given text string using TikToken.
Args:
text (str): The text to be tokenized.
Returns:
int: The length of the tokenized text.
"""
tokens = tokenizer.encode(text, disallowed_special=())
return len(tokens)
def string2md5(text: str):
"""Convert a string to its MD5 hash.
Args:
text (str): The text to be hashed.
Returns:
str: The MD5 hash of the input string.
"""
hash_md5 = hashlib.md5()
hash_md5.update(text.encode("utf-8"))
return hash_md5.hexdigest()
def load_file(file_path):
"""Load a file and return its content as a Document object.
Args:
file_path (str): The path to the file.
Returns:
Document: The loaded document.
"""
ext = file_path.split(".")[-1]
if ext in loaders:
loader_type, args = loaders[ext]
loader = loader_type(file_path, **args)
doc = loader.load()
return doc
raise ValueError(f"Extension {ext} not supported")
def docs2vectorstore(docs: List[Document], embedding_name: str, suffix: str = ""):
"""Convert a list of Documents into a Chroma vector store.
Args:
docs (Document): The list of Documents.
suffix (str, optional): Suffix for the embedding. Defaults to "".
"""
embedding = choose_embeddings(embedding_name)
name = f"{embedding_name}_{suffix}"
# if embedding_store_path is not existing, create it
if not os.path.exists(embedding_store_path):
os.makedirs(embedding_store_path)
Chroma.from_documents(
docs,
embedding,
persist_directory=f"{embedding_store_path}/chroma_{name}",
)
def file_names2pickle(file_names: list, save_name: str = ""):
"""Save the list of file names to a pickle file.
Args:
file_names (list): The list of file names.
save_name (str, optional): The name for the saved pickle file. Defaults to "".
"""
name = f"{save_name}"
if not os.path.exists(embedding_store_path):
os.makedirs(embedding_store_path)
with open(f"{embedding_store_path}/{name}.pkl", "wb") as file:
pickle.dump(file_names, file)
def docs2pickle(docs: List[Document], suffix: str = ""):
"""Serializes a list of Document objects to a pickle file.
Args:
docs (Document): List of Document objects.
suffix (str, optional): Suffix for the pickle file. Defaults to "".
"""
for doc in docs:
doc.page_content = clean_text(doc.page_content)
name = f"pickle_{suffix}"
if not os.path.exists(embedding_store_path):
os.makedirs(embedding_store_path)
with open(f"{embedding_store_path}/docs_{name}.pkl", "wb") as file:
pickle.dump(docs, file)
def split_doc(
doc: List[Document], chunk_size: int, chunk_overlap: int, chunk_idx_name: str
):
"""Splits a document into smaller chunks based on the provided size and overlap.
Args:
doc (Document): Document to be split.
chunk_size (int): Size of each chunk.
chunk_overlap (int): Overlap between adjacent chunks.
chunk_idx_name (str): Metadata key for storing chunk indices.
Returns:
list: List of Document objects representing the chunks.
"""
data_splitter = RecursiveCharacterTextSplitter(
chunk_size=chunk_size,
chunk_overlap=chunk_overlap,
length_function=tiktoken_len,
)
doc_split = data_splitter.split_documents(doc)
chunk_idx = 0
for d_split in doc_split:
d_split.metadata[chunk_idx_name] = chunk_idx
chunk_idx += 1
return doc_split
def process_metadata(doc: List[Document]):
"""Processes and updates the metadata for a list of Document objects.
Args:
doc (list): List of Document objects.
"""
# get file name and remove extension
file_name_with_extension = os.path.basename(doc[0].metadata["source"])
file_name, _ = os.path.splitext(file_name_with_extension)
for _, item in enumerate(doc):
for key, value in item.metadata.items():
if isinstance(value, list):
item.metadata[key] = str(value)
item.metadata["page_content"] = item.page_content
item.metadata["page_content_md5"] = string2md5(item.page_content)
item.metadata["source_md5"] = string2md5(item.metadata["source"])
item.page_content = f"{file_name}\n{item.page_content}"
def add_window(
doc: Document, window_steps: int, window_size: int, window_idx_name: str
):
"""Adds windowing information to the metadata of each document in the list.
Args:
doc (Document): List of Document objects.
window_steps (int): Step size for windowing.
window_size (int): Size of each window.
window_idx_name (str): Metadata key for storing window indices.
"""
window_id = 0
window_deque = deque()
for idx, item in enumerate(doc):
if idx % window_steps == 0 and idx != 0 and idx < len(doc) - window_size:
window_id += 1
window_deque.append(window_id)
if len(window_deque) > window_size:
for _ in range(window_steps):
window_deque.popleft()
window = set(window_deque)
item.metadata[f"{window_idx_name}_lower_bound"] = min(window)
item.metadata[f"{window_idx_name}_upper_bound"] = max(window)
def merge_metadata(dicts_list: dict):
"""Merges a list of metadata dictionaries into a single dictionary.
Args:
dicts_list (list): List of metadata dictionaries.
Returns:
dict: Merged metadata dictionary.
"""
merged_dict = {}
bounds_dict = {}
keys_to_remove = set()
for dic in dicts_list:
for key, value in dic.items():
if key in merged_dict:
if value not in merged_dict[key]:
merged_dict[key].append(value)
else:
merged_dict[key] = [value]
for key, values in merged_dict.items():
if len(values) > 1 and all(isinstance(x, (int, float)) for x in values):
bounds_dict[f"{key}_lower_bound"] = min(values)
bounds_dict[f"{key}_upper_bound"] = max(values)
keys_to_remove.add(key)
merged_dict.update(bounds_dict)
for key in keys_to_remove:
del merged_dict[key]
return {
k: v[0] if isinstance(v, list) and len(v) == 1 else v
for k, v in merged_dict.items()
}
def merge_chunks(doc: Document, scale_factor: int, chunk_idx_name: str):
"""Merges adjacent chunks into larger chunks based on a scaling factor.
Args:
doc (Document): List of Document objects.
scale_factor (int): The number of small chunks to merge into a larger chunk.
chunk_idx_name (str): Metadata key for storing chunk indices.
Returns:
list: List of Document objects representing the merged chunks.
"""
merged_doc = []
page_content = ""
metadata_list = []
chunk_idx = 0
for idx, item in enumerate(doc):
page_content += item.page_content
metadata_list.append(item.metadata)
if (idx + 1) % scale_factor == 0 or idx == len(doc) - 1:
metadata = merge_metadata(metadata_list)
metadata[chunk_idx_name] = chunk_idx
merged_doc.append(
Document(
page_content=page_content,
metadata=metadata,
)
)
chunk_idx += 1
page_content = ""
metadata_list = []
return merged_doc
def process_files():
"""Main function for processing files. Loads, tokenizes, and saves document data."""
with Pool() as pool:
chunks_small = []
chunks_medium = []
file_names = []
with tqdm(total=len(files_path), desc="Processing files", ncols=80) as pbar:
for doc in pool.imap_unordered(load_file, files_path):
file_name_with_extension = os.path.basename(doc[0].metadata["source"])
# file_name, _ = os.path.splitext(file_name_with_extension)
chunk_split_small = split_doc(
doc=doc,
chunk_size=configs.base_chunk_size,
chunk_overlap=configs.chunk_overlap,
chunk_idx_name="small_chunk_idx",
)
add_window(
doc=chunk_split_small,
window_steps=configs.window_steps,
window_size=configs.window_scale,
window_idx_name="large_chunks_idx",
)
chunk_split_medium = merge_chunks(
doc=chunk_split_small,
scale_factor=configs.chunk_scale,
chunk_idx_name="medium_chunk_idx",
)
process_metadata(chunk_split_small)
process_metadata(chunk_split_medium)
file_names.append(file_name_with_extension)
chunks_small.extend(chunk_split_small)
chunks_medium.extend(chunk_split_medium)
pbar.update()
file_names2pickle(file_names, save_name="file_names")
docs2vectorstore(chunks_small, configs.embedding_name, suffix="chunks_small")
docs2vectorstore(chunks_medium, configs.embedding_name, suffix="chunks_medium")
docs2pickle(chunks_small, suffix="chunks_small")
docs2pickle(chunks_medium, suffix="chunks_medium")
if __name__ == "__main__":
process_files()
|