Indexing_RAPTOR.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. from langchain_community.vectorstores import Chroma
  2. from typing import Dict, List, Optional, Tuple
  3. import numpy as np
  4. import pandas as pd
  5. import umap
  6. from langchain.prompts import ChatPromptTemplate
  7. from langchain_core.output_parsers import StrOutputParser
  8. from sklearn.mixture import GaussianMixture
  9. from dotenv import load_dotenv
  10. load_dotenv()
  11. import os
  12. os.environ["PATH"] += os.pathsep + "C:/Users/lzl/anaconda3/Lib/site-packages/poppler-24.02.0/Library/bin"
  13. os.environ["PATH"] += os.pathsep + r"C:\Program Files\Tesseract-OCR\tessdata"
  14. os.environ["PATH"] += os.pathsep + r"C:\Program Files\Tesseract-OCR"
  15. os.environ["TESSDATA_PREFIX"] = r"C:\Program Files\Tesseract-OCR\tessdata"
  16. from langchain_openai import OpenAIEmbeddings
  17. embd = OpenAIEmbeddings()
  18. from langchain_openai import ChatOpenAI
  19. model = ChatOpenAI(temperature=0, model="gpt-4-1106-preview")
  20. RANDOM_SEED = 224 # Fixed seed for reproducibility
  21. ### --- Code from citations referenced above (added comments and docstrings) --- ###
  22. def global_cluster_embeddings(
  23. embeddings: np.ndarray,
  24. dim: int,
  25. n_neighbors: Optional[int] = None,
  26. metric: str = "cosine",
  27. ) -> np.ndarray:
  28. """
  29. Perform global dimensionality reduction on the embeddings using UMAP.
  30. Parameters:
  31. - embeddings: The input embeddings as a numpy array.
  32. - dim: The target dimensionality for the reduced space.
  33. - n_neighbors: Optional; the number of neighbors to consider for each point.
  34. If not provided, it defaults to the square root of the number of embeddings.
  35. - metric: The distance metric to use for UMAP.
  36. Returns:
  37. - A numpy array of the embeddings reduced to the specified dimensionality.
  38. """
  39. if n_neighbors is None:
  40. n_neighbors = int((len(embeddings) - 1) ** 0.5)
  41. return umap.UMAP(
  42. n_neighbors=n_neighbors, n_components=dim, metric=metric
  43. ).fit_transform(embeddings)
  44. def local_cluster_embeddings(
  45. embeddings: np.ndarray, dim: int, num_neighbors: int = 10, metric: str = "cosine"
  46. ) -> np.ndarray:
  47. """
  48. Perform local dimensionality reduction on the embeddings using UMAP, typically after global clustering.
  49. Parameters:
  50. - embeddings: The input embeddings as a numpy array.
  51. - dim: The target dimensionality for the reduced space.
  52. - num_neighbors: The number of neighbors to consider for each point.
  53. - metric: The distance metric to use for UMAP.
  54. Returns:
  55. - A numpy array of the embeddings reduced to the specified dimensionality.
  56. """
  57. return umap.UMAP(
  58. n_neighbors=num_neighbors, n_components=dim, metric=metric
  59. ).fit_transform(embeddings)
  60. def get_optimal_clusters(
  61. embeddings: np.ndarray, max_clusters: int = 50, random_state: int = RANDOM_SEED
  62. ) -> int:
  63. """
  64. Determine the optimal number of clusters using the Bayesian Information Criterion (BIC) with a Gaussian Mixture Model.
  65. Parameters:
  66. - embeddings: The input embeddings as a numpy array.
  67. - max_clusters: The maximum number of clusters to consider.
  68. - random_state: Seed for reproducibility.
  69. Returns:
  70. - An integer representing the optimal number of clusters found.
  71. """
  72. max_clusters = min(max_clusters, len(embeddings))
  73. n_clusters = np.arange(1, max_clusters)
  74. bics = []
  75. for n in n_clusters:
  76. gm = GaussianMixture(n_components=n, random_state=random_state)
  77. gm.fit(embeddings)
  78. bics.append(gm.bic(embeddings))
  79. return n_clusters[np.argmin(bics)]
  80. def GMM_cluster(embeddings: np.ndarray, threshold: float, random_state: int = 0):
  81. """
  82. Cluster embeddings using a Gaussian Mixture Model (GMM) based on a probability threshold.
  83. Parameters:
  84. - embeddings: The input embeddings as a numpy array.
  85. - threshold: The probability threshold for assigning an embedding to a cluster.
  86. - random_state: Seed for reproducibility.
  87. Returns:
  88. - A tuple containing the cluster labels and the number of clusters determined.
  89. """
  90. n_clusters = get_optimal_clusters(embeddings)
  91. gm = GaussianMixture(n_components=n_clusters, random_state=random_state)
  92. gm.fit(embeddings)
  93. probs = gm.predict_proba(embeddings)
  94. labels = [np.where(prob > threshold)[0] for prob in probs]
  95. return labels, n_clusters
  96. def perform_clustering(
  97. embeddings: np.ndarray,
  98. dim: int,
  99. threshold: float,
  100. ) -> List[np.ndarray]:
  101. """
  102. Perform clustering on the embeddings by first reducing their dimensionality globally, then clustering
  103. using a Gaussian Mixture Model, and finally performing local clustering within each global cluster.
  104. Parameters:
  105. - embeddings: The input embeddings as a numpy array.
  106. - dim: The target dimensionality for UMAP reduction.
  107. - threshold: The probability threshold for assigning an embedding to a cluster in GMM.
  108. Returns:
  109. - A list of numpy arrays, where each array contains the cluster IDs for each embedding.
  110. """
  111. if len(embeddings) <= dim + 1:
  112. # Avoid clustering when there's insufficient data
  113. return [np.array([0]) for _ in range(len(embeddings))]
  114. # Global dimensionality reduction
  115. reduced_embeddings_global = global_cluster_embeddings(embeddings, dim)
  116. # Global clustering
  117. global_clusters, n_global_clusters = GMM_cluster(
  118. reduced_embeddings_global, threshold
  119. )
  120. all_local_clusters = [np.array([]) for _ in range(len(embeddings))]
  121. total_clusters = 0
  122. # Iterate through each global cluster to perform local clustering
  123. for i in range(n_global_clusters):
  124. # Extract embeddings belonging to the current global cluster
  125. global_cluster_embeddings_ = embeddings[
  126. np.array([i in gc for gc in global_clusters])
  127. ]
  128. if len(global_cluster_embeddings_) == 0:
  129. continue
  130. if len(global_cluster_embeddings_) <= dim + 1:
  131. # Handle small clusters with direct assignment
  132. local_clusters = [np.array([0]) for _ in global_cluster_embeddings_]
  133. n_local_clusters = 1
  134. else:
  135. # Local dimensionality reduction and clustering
  136. reduced_embeddings_local = local_cluster_embeddings(
  137. global_cluster_embeddings_, dim
  138. )
  139. local_clusters, n_local_clusters = GMM_cluster(
  140. reduced_embeddings_local, threshold
  141. )
  142. # Assign local cluster IDs, adjusting for total clusters already processed
  143. for j in range(n_local_clusters):
  144. local_cluster_embeddings_ = global_cluster_embeddings_[
  145. np.array([j in lc for lc in local_clusters])
  146. ]
  147. indices = np.where(
  148. (embeddings == local_cluster_embeddings_[:, None]).all(-1)
  149. )[1]
  150. for idx in indices:
  151. all_local_clusters[idx] = np.append(
  152. all_local_clusters[idx], j + total_clusters
  153. )
  154. total_clusters += n_local_clusters
  155. return all_local_clusters
  156. ### --- Our code below --- ###
  157. def embed(texts):
  158. """
  159. Generate embeddings for a list of text documents.
  160. This function assumes the existence of an `embd` object with a method `embed_documents`
  161. that takes a list of texts and returns their embeddings.
  162. Parameters:
  163. - texts: List[str], a list of text documents to be embedded.
  164. Returns:
  165. - numpy.ndarray: An array of embeddings for the given text documents.
  166. """
  167. text_embeddings = embd.embed_documents(texts)
  168. text_embeddings_np = np.array(text_embeddings)
  169. return text_embeddings_np
  170. def embed_cluster_texts(texts):
  171. """
  172. Embeds a list of texts and clusters them, returning a DataFrame with texts, their embeddings, and cluster labels.
  173. This function combines embedding generation and clustering into a single step. It assumes the existence
  174. of a previously defined `perform_clustering` function that performs clustering on the embeddings.
  175. Parameters:
  176. - texts: List[str], a list of text documents to be processed.
  177. Returns:
  178. - pandas.DataFrame: A DataFrame containing the original texts, their embeddings, and the assigned cluster labels.
  179. """
  180. text_embeddings_np = embed(texts) # Generate embeddings
  181. cluster_labels = perform_clustering(
  182. text_embeddings_np, 10, 0.1
  183. ) # Perform clustering on the embeddings
  184. df = pd.DataFrame() # Initialize a DataFrame to store the results
  185. df["text"] = texts # Store original texts
  186. df["embd"] = list(text_embeddings_np) # Store embeddings as a list in the DataFrame
  187. df["cluster"] = cluster_labels # Store cluster labels
  188. return df
  189. def fmt_txt(df: pd.DataFrame) -> str:
  190. """
  191. Formats the text documents in a DataFrame into a single string.
  192. Parameters:
  193. - df: DataFrame containing the 'text' column with text documents to format.
  194. Returns:
  195. - A single string where all text documents are joined by a specific delimiter.
  196. """
  197. unique_txt = df["text"].tolist()
  198. return "--- --- \n --- --- ".join(unique_txt)
  199. def embed_cluster_summarize_texts(
  200. texts: List[str], level: int
  201. ) -> Tuple[pd.DataFrame, pd.DataFrame]:
  202. """
  203. Embeds, clusters, and summarizes a list of texts. This function first generates embeddings for the texts,
  204. clusters them based on similarity, expands the cluster assignments for easier processing, and then summarizes
  205. the content within each cluster.
  206. Parameters:
  207. - texts: A list of text documents to be processed.
  208. - level: An integer parameter that could define the depth or detail of processing.
  209. Returns:
  210. - Tuple containing two DataFrames:
  211. 1. The first DataFrame (`df_clusters`) includes the original texts, their embeddings, and cluster assignments.
  212. 2. The second DataFrame (`df_summary`) contains summaries for each cluster, the specified level of detail,
  213. and the cluster identifiers.
  214. """
  215. # Embed and cluster the texts, resulting in a DataFrame with 'text', 'embd', and 'cluster' columns
  216. df_clusters = embed_cluster_texts(texts)
  217. # Prepare to expand the DataFrame for easier manipulation of clusters
  218. expanded_list = []
  219. # Expand DataFrame entries to document-cluster pairings for straightforward processing
  220. for index, row in df_clusters.iterrows():
  221. for cluster in row["cluster"]:
  222. expanded_list.append(
  223. {"text": row["text"], "embd": row["embd"], "cluster": cluster}
  224. )
  225. # Create a new DataFrame from the expanded list
  226. expanded_df = pd.DataFrame(expanded_list)
  227. # Retrieve unique cluster identifiers for processing
  228. all_clusters = expanded_df["cluster"].unique()
  229. print(f"--Generated {len(all_clusters)} clusters--")
  230. # Summarization
  231. template = """Here is a sub-set of LangChain Expression Langauge doc.
  232. LangChain Expression Langauge provides a way to compose chain in LangChain.
  233. Give a detailed summary of the documentation provided.
  234. Documentation:
  235. {context}
  236. """
  237. prompt = ChatPromptTemplate.from_template(template)
  238. chain = prompt | model | StrOutputParser()
  239. # Format text within each cluster for summarization
  240. summaries = []
  241. for i in all_clusters:
  242. df_cluster = expanded_df[expanded_df["cluster"] == i]
  243. formatted_txt = fmt_txt(df_cluster)
  244. summaries.append(chain.invoke({"context": formatted_txt}))
  245. # Create a DataFrame to store summaries with their corresponding cluster and level
  246. df_summary = pd.DataFrame(
  247. {
  248. "summaries": summaries,
  249. "level": [level] * len(summaries),
  250. "cluster": list(all_clusters),
  251. }
  252. )
  253. return df_clusters, df_summary
  254. def recursive_embed_cluster_summarize(
  255. texts: List[str], level: int = 1, n_levels: int = 3
  256. ) -> Dict[int, Tuple[pd.DataFrame, pd.DataFrame]]:
  257. """
  258. Recursively embeds, clusters, and summarizes texts up to a specified level or until
  259. the number of unique clusters becomes 1, storing the results at each level.
  260. Parameters:
  261. - texts: List[str], texts to be processed.
  262. - level: int, current recursion level (starts at 1).
  263. - n_levels: int, maximum depth of recursion.
  264. Returns:
  265. - Dict[int, Tuple[pd.DataFrame, pd.DataFrame]], a dictionary where keys are the recursion
  266. levels and values are tuples containing the clusters DataFrame and summaries DataFrame at that level.
  267. """
  268. results = {} # Dictionary to store results at each level
  269. # Perform embedding, clustering, and summarization for the current level
  270. df_clusters, df_summary = embed_cluster_summarize_texts(texts, level)
  271. # Store the results of the current level
  272. results[level] = (df_clusters, df_summary)
  273. # Determine if further recursion is possible and meaningful
  274. unique_clusters = df_summary["cluster"].nunique()
  275. if level < n_levels and unique_clusters > 1:
  276. # Use summaries as the input texts for the next level of recursion
  277. new_texts = df_summary["summaries"].tolist()
  278. next_level_results = recursive_embed_cluster_summarize(
  279. new_texts, level + 1, n_levels
  280. )
  281. # Merge the results from the next level into the current results dictionary
  282. results.update(next_level_results)
  283. return results
  284. def create_retriever(path='Documents', extension="txt"):
  285. def preprocessing(path, extension):
  286. from langchain_community.document_loaders import DirectoryLoader
  287. loader = DirectoryLoader(path, glob=f'**/*.{extension}', show_progress=True)
  288. docs = loader.load()
  289. docs_texts = [d.page_content for d in docs]
  290. return docs_texts
  291. # Build tree
  292. leaf_texts = preprocessing(path, extension)
  293. results = recursive_embed_cluster_summarize(leaf_texts, level=1, n_levels=3)
  294. # Initialize all_texts with leaf_texts
  295. all_texts = leaf_texts.copy()
  296. # Iterate through the results to extract summaries from each level and add them to all_texts
  297. for level in sorted(results.keys()):
  298. # Extract summaries from the current level's DataFrame
  299. summaries = results[level][1]["summaries"].tolist()
  300. # Extend all_texts with the summaries from the current level
  301. all_texts.extend(summaries)
  302. # Now, use all_texts to build the vectorstore with Chroma
  303. embd = OpenAIEmbeddings()
  304. vectorstore = Chroma.from_texts(texts=all_texts, embedding=embd)
  305. retriever = vectorstore.as_retriever()
  306. return retriever