Update app/vectorstore.py
Browse files- app/vectorstore.py +342 -342
app/vectorstore.py
CHANGED
|
@@ -1,343 +1,343 @@
|
|
| 1 |
-
# vectorstore.py
|
| 2 |
-
import os
|
| 3 |
-
import json
|
| 4 |
-
from datetime import datetime
|
| 5 |
-
import faiss
|
| 6 |
-
import numpy as np
|
| 7 |
-
from sentence_transformers import SentenceTransformer
|
| 8 |
-
from pypdf import PdfReader
|
| 9 |
-
import requests
|
| 10 |
-
from bs4 import BeautifulSoup
|
| 11 |
-
|
| 12 |
-
# Updated LangChain imports
|
| 13 |
-
from langchain_community.document_loaders import PyPDFLoader
|
| 14 |
-
from langchain_community.document_loaders import WebBaseLoader
|
| 15 |
-
from langchain_community.vectorstores import FAISS
|
| 16 |
-
from langchain_huggingface import HuggingFaceEmbeddings
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
class vectorstore:
|
| 20 |
-
# 1 is pdf, 2 is website, and 3 is an already created vectorstore
|
| 21 |
-
def __init__(self, path, Initlize_with=3):
|
| 22 |
-
if Initlize_with == 1:
|
| 23 |
-
self.index_path = self.create_vectorstore_from_pdf(path, embedder_model="all-MiniLM-L6-v2")
|
| 24 |
-
self.vectorstore = self.load_vectorstore(self.index_path)
|
| 25 |
-
elif Initlize_with == 2:
|
| 26 |
-
self.index_path = self.create_vectorstore_from_website(path, embedder_model="all-MiniLM-L6-v2")
|
| 27 |
-
self.vectorstore = self.load_vectorstore(self.index_path)
|
| 28 |
-
elif Initlize_with == 3:
|
| 29 |
-
self.index_path = path
|
| 30 |
-
self.vectorstore = self.load_vectorstore(self.index_path)
|
| 31 |
-
|
| 32 |
-
def chunk_text(self,text, chunk_size=300):
|
| 33 |
-
"""
|
| 34 |
-
Split text into chunks of approximately 'chunk_size' words.
|
| 35 |
-
|
| 36 |
-
Parameters:
|
| 37 |
-
text (str): The input text.
|
| 38 |
-
chunk_size (int): Maximum number of words per chunk.
|
| 39 |
-
|
| 40 |
-
Returns:
|
| 41 |
-
List[str]: A list of text chunks.
|
| 42 |
-
"""
|
| 43 |
-
words = text.split()
|
| 44 |
-
chunks = []
|
| 45 |
-
for i in range(0, len(words), chunk_size):
|
| 46 |
-
chunk = " ".join(words[i:i+chunk_size])
|
| 47 |
-
chunks.append(chunk)
|
| 48 |
-
return chunks
|
| 49 |
-
|
| 50 |
-
def create_vectorstore_from_pdf(self,pdf_path, chunk_size=500, embedder_model="all-MiniLM-L6-v2"):
|
| 51 |
-
"""
|
| 52 |
-
Extract text from a PDF using pypdf, chunk the text, compute embeddings,
|
| 53 |
-
and create a FAISS index.
|
| 54 |
-
|
| 55 |
-
Parameters:
|
| 56 |
-
pdf_path (str): Path to the PDF file.
|
| 57 |
-
chunk_size (int): Number of words per chunk.
|
| 58 |
-
embedder_model (str): The sentence-transformer model to use.
|
| 59 |
-
|
| 60 |
-
Returns:
|
| 61 |
-
index: A FAISS index containing the embeddings.
|
| 62 |
-
chunks: A list of text chunks.
|
| 63 |
-
embedder: The SentenceTransformer embedder.
|
| 64 |
-
"""
|
| 65 |
-
# Load PDF using LangChain's PyPDFLoader
|
| 66 |
-
loader = PyPDFLoader(pdf_path)
|
| 67 |
-
documents = loader.load()
|
| 68 |
-
text = " ".join([doc.page_content for doc in documents])
|
| 69 |
-
|
| 70 |
-
# Chunk text using existing method (word-based)
|
| 71 |
-
chunks = self.chunk_text(text, chunk_size)
|
| 72 |
-
|
| 73 |
-
# Create embeddings and FAISS vectorstore with LangChain
|
| 74 |
-
embedder = HuggingFaceEmbeddings(model_name=embedder_model)
|
| 75 |
-
vectorstore = FAISS.from_texts(chunks, embedder)
|
| 76 |
-
|
| 77 |
-
# Save the vectorstore
|
| 78 |
-
index_path = self.save_vectorstore_with_timestamp_and_without(vectorstore, embedder_model)
|
| 79 |
-
return index_path
|
| 80 |
-
|
| 81 |
-
def create_vectorstore_from_website(self, url, chunk_size=300, embedder_model="all-MiniLM-L6-v2"):
|
| 82 |
-
"""
|
| 83 |
-
Fetch text from a website, chunk the text, compute embeddings,
|
| 84 |
-
and create a FAISS index.
|
| 85 |
-
|
| 86 |
-
Parameters:
|
| 87 |
-
url (str): The URL of the website.
|
| 88 |
-
chunk_size (int): Number of words per chunk.
|
| 89 |
-
embedder_model (str): The sentence-transformer model to use.
|
| 90 |
-
|
| 91 |
-
Returns:
|
| 92 |
-
index: A FAISS index containing the embeddings.
|
| 93 |
-
chunks: A list of text chunks.
|
| 94 |
-
embedder: The SentenceTransformer embedder.
|
| 95 |
-
"""
|
| 96 |
-
# Load website using LangChain's WebBaseLoader
|
| 97 |
-
loader = WebBaseLoader(url)
|
| 98 |
-
documents = loader.load()
|
| 99 |
-
text = " ".join([doc.page_content for doc in documents])
|
| 100 |
-
|
| 101 |
-
# Chunk text using existing method
|
| 102 |
-
chunks = self.chunk_text(text, chunk_size)
|
| 103 |
-
|
| 104 |
-
# Create embeddings and FAISS vectorstore
|
| 105 |
-
embedder = HuggingFaceEmbeddings(model_name=embedder_model)
|
| 106 |
-
vectorstore = FAISS.from_texts(chunks, embedder)
|
| 107 |
-
|
| 108 |
-
# Save the vectorstore
|
| 109 |
-
index_path = self.save_vectorstore_with_timestamp_and_without(vectorstore, embedder_model)
|
| 110 |
-
return index_path
|
| 111 |
-
|
| 112 |
-
def add_to_vectorstore_web(self, url, index_file_path, chunk_size=300):
|
| 113 |
-
"""
|
| 114 |
-
Fetch text from a website, chunk the text, compute embeddings using the existing embedder,
|
| 115 |
-
and add them to the existing FAISS vectorstore.
|
| 116 |
-
|
| 117 |
-
Parameters:
|
| 118 |
-
url (str): The URL of the website.
|
| 119 |
-
index_file_path (str): The file path of the saved vectorstore index.
|
| 120 |
-
chunk_size (int): Maximum number of words per chunk.
|
| 121 |
-
|
| 122 |
-
Returns:
|
| 123 |
-
str: The updated vectorstore index file path.
|
| 124 |
-
"""
|
| 125 |
-
# Load the existing vectorstore
|
| 126 |
-
vectorstore = self.load_vectorstore(index_file_path)
|
| 127 |
-
|
| 128 |
-
# Fetch and extract text from the website
|
| 129 |
-
loader = WebBaseLoader(url)
|
| 130 |
-
documents = loader.load()
|
| 131 |
-
text = " ".join([doc.page_content for doc in documents])
|
| 132 |
-
|
| 133 |
-
# Chunk the text
|
| 134 |
-
new_chunks = self.chunk_text(text, chunk_size)
|
| 135 |
-
|
| 136 |
-
# Add new chunks to the vectorstore
|
| 137 |
-
vectorstore.add_texts(new_chunks)
|
| 138 |
-
|
| 139 |
-
# Save the updated vectorstore
|
| 140 |
-
updated_index_path = self.save_vectorstore_with_timestamp_and_without(vectorstore, vectorstore.embedding_function.model_name)
|
| 141 |
-
return updated_index_path
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
def add_to_vectorstore_from_pdf(self, pdf_path, chunk_size=500):
|
| 145 |
-
"""
|
| 146 |
-
Extract text from a PDF using PyPDF2, chunk the text, compute embeddings using the existing embedder,
|
| 147 |
-
and add them to the existing FAISS vectorstore.
|
| 148 |
-
|
| 149 |
-
Parameters:
|
| 150 |
-
pdf_path (str): Path to the PDF file.
|
| 151 |
-
index_file_path (str): The file path of the saved vectorstore index.
|
| 152 |
-
chunk_size (int): Maximum number of words per chunk.
|
| 153 |
-
|
| 154 |
-
Returns:
|
| 155 |
-
str: The updated vectorstore index file path.
|
| 156 |
-
"""
|
| 157 |
-
# Extract text from PDF
|
| 158 |
-
loader = PyPDFLoader(pdf_path)
|
| 159 |
-
documents = loader.load()
|
| 160 |
-
text = " ".join([doc.page_content for doc in documents])
|
| 161 |
-
|
| 162 |
-
# Chunk the text
|
| 163 |
-
new_chunks = self.chunk_text(text, chunk_size)
|
| 164 |
-
|
| 165 |
-
# Add new chunks to the existing vectorstore
|
| 166 |
-
self.vectorstore.add_texts(new_chunks)
|
| 167 |
-
|
| 168 |
-
# Save the updated vectorstore
|
| 169 |
-
self.index_path = self.save_vectorstore_with_timestamp_and_without(self.vectorstore, self.vectorstore.embedding_function.model_name)
|
| 170 |
-
return self.index_path
|
| 171 |
-
|
| 172 |
-
def save_vectorstore_with_timestamp_and_without(self, vectorstore, embedder_model=None):
|
| 173 |
-
vector_db_folder = os.path.join(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")), "VectorDB")
|
| 174 |
-
os.makedirs(vector_db_folder, exist_ok=True)
|
| 175 |
-
|
| 176 |
-
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 177 |
-
folder_name = f"vectorstore_{timestamp}"
|
| 178 |
-
folder_path = os.path.join(vector_db_folder, folder_name)
|
| 179 |
-
|
| 180 |
-
# Save the LangChain FAISS vectorstore
|
| 181 |
-
vectorstore.save_local(folder_path)
|
| 182 |
-
|
| 183 |
-
# Save metadata with embedder model name
|
| 184 |
-
metadata = {"embedder_model": embedder_model or "all-MiniLM-L6-v2"}
|
| 185 |
-
with open(os.path.join(folder_path, "metadata.json"), "w") as f:
|
| 186 |
-
json.dump(metadata, f)
|
| 187 |
-
|
| 188 |
-
# Save to main folder
|
| 189 |
-
main_folder = os.path.join(vector_db_folder, "vectorstore_mainV2")
|
| 190 |
-
vectorstore.save_local(main_folder)
|
| 191 |
-
with open(os.path.join(main_folder, "metadata.json"), "w") as f:
|
| 192 |
-
json.dump(metadata, f)
|
| 193 |
-
|
| 194 |
-
return main_folder
|
| 195 |
-
|
| 196 |
-
def load_vectorstore(self, index_path):
|
| 197 |
-
# Load metadata to get embedder model
|
| 198 |
-
metadata_path = os.path.join(index_path, "metadata.json")
|
| 199 |
-
with open(metadata_path, "r") as f:
|
| 200 |
-
metadata = json.load(f)
|
| 201 |
-
embedder_model = metadata["embedder_model"]
|
| 202 |
-
|
| 203 |
-
# Create embedder and load vectorstore
|
| 204 |
-
embedder = HuggingFaceEmbeddings(model_name=embedder_model)
|
| 205 |
-
vectorstore = FAISS.load_local(index_path, embedder
|
| 206 |
-
return vectorstore
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
def search_vectorstore(self, query, top_k=5):
|
| 210 |
-
# Search using LangChain's similarity_search
|
| 211 |
-
docs = self.vectorstore.similarity_search(query, k=top_k)
|
| 212 |
-
results = [doc.page_content for doc in docs]
|
| 213 |
-
return results
|
| 214 |
-
|
| 215 |
-
def log_conversation(self, user_text, bot_text=""):
|
| 216 |
-
# Existing JSON logging
|
| 217 |
-
logs_folder = os.path.join(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")), "logs")
|
| 218 |
-
os.makedirs(logs_folder, exist_ok=True)
|
| 219 |
-
log_file = os.path.join(logs_folder, "conversation_logs.json")
|
| 220 |
-
entry = {
|
| 221 |
-
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
| 222 |
-
"User": {"text": user_text},
|
| 223 |
-
"bot": {"text": bot_text}
|
| 224 |
-
}
|
| 225 |
-
if os.path.exists(log_file):
|
| 226 |
-
with open(log_file, "r", encoding="utf-8") as f:
|
| 227 |
-
try:
|
| 228 |
-
logs = json.load(f)
|
| 229 |
-
except json.JSONDecodeError:
|
| 230 |
-
logs = []
|
| 231 |
-
else:
|
| 232 |
-
logs = []
|
| 233 |
-
logs.append(entry)
|
| 234 |
-
with open(log_file, "w", encoding="utf-8") as f:
|
| 235 |
-
json.dump(logs, f, indent=4)
|
| 236 |
-
|
| 237 |
-
# Add to LangMem memory
|
| 238 |
-
self.memory.add_message({"role": "user", "content": user_text})
|
| 239 |
-
if bot_text:
|
| 240 |
-
self.memory.add_message({"role": "assistant", "content": bot_text})
|
| 241 |
-
|
| 242 |
-
# # ...existing code...
|
| 243 |
-
|
| 244 |
-
# import re
|
| 245 |
-
# import requests
|
| 246 |
-
# import nltk
|
| 247 |
-
# from nltk.tokenize import sent_tokenize
|
| 248 |
-
# import numpy as np
|
| 249 |
-
|
| 250 |
-
# # Download NLTK data (only once; consider moving this to a setup step)
|
| 251 |
-
# nltk.download('punkt')
|
| 252 |
-
# nltk.download('punkt_tab')
|
| 253 |
-
|
| 254 |
-
# class CancerDataIngestor:
|
| 255 |
-
# def __init__(self,vector_db=None, source_urls=None, embedding_model=None):
|
| 256 |
-
# """
|
| 257 |
-
# Initialize with:
|
| 258 |
-
# - source_urls: a dictionary mapping source names to URLs.
|
| 259 |
-
# - embedding_model: a callable that takes text and returns an embedding.
|
| 260 |
-
# - vector_db: an instance of your vector database.
|
| 261 |
-
# """
|
| 262 |
-
# self.sources = source_urls if source_urls is not None else {
|
| 263 |
-
# 'PMC': 'https://www.ncbi.nlm.nih.gov/pmc/',
|
| 264 |
-
# 'NCI': 'https://www.cancer.gov/about-cancer/understanding/statistics',
|
| 265 |
-
# 'WHO': 'https://www.who.int/cancer/en/',
|
| 266 |
-
# 'ClinicalTrials': 'https://clinicaltrials.gov/',
|
| 267 |
-
# 'Kaggle': 'https://www.kaggle.com/datasets'
|
| 268 |
-
# }
|
| 269 |
-
# # Use the provided embedding model or default to self.get_embedding
|
| 270 |
-
# self.embedding_model = embedding_model if embedding_model is not None else self.get_embedding
|
| 271 |
-
# if vector_db is None:
|
| 272 |
-
# raise ValueError("A valid vector DB instance must be provided.")
|
| 273 |
-
# self.vector_db = vector_db
|
| 274 |
-
# # Initialize the SentenceTransformer model once.
|
| 275 |
-
# self.model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 276 |
-
|
| 277 |
-
# def fetch_html(self, url):
|
| 278 |
-
# """Fetch HTML content from a given URL."""
|
| 279 |
-
# try:
|
| 280 |
-
# response = requests.get(url)
|
| 281 |
-
# response.raise_for_status()
|
| 282 |
-
# return response.text
|
| 283 |
-
# except Exception as e:
|
| 284 |
-
# print(f"Error fetching URL {url}: {e}")
|
| 285 |
-
# return None
|
| 286 |
-
|
| 287 |
-
# def clean_html(self, html):
|
| 288 |
-
# """Extract text from HTML and remove tags and extra spaces."""
|
| 289 |
-
# if html is None:
|
| 290 |
-
# return ""
|
| 291 |
-
# from bs4 import BeautifulSoup # in case not already imported above
|
| 292 |
-
# soup = BeautifulSoup(html, 'html.parser')
|
| 293 |
-
# for tag in soup(['script', 'style']):
|
| 294 |
-
# tag.decompose()
|
| 295 |
-
# text = soup.get_text(separator=' ')
|
| 296 |
-
# text = re.sub(r'[^a-zA-Z0-9.,;:?!\s]', ' ', text)
|
| 297 |
-
# text = re.sub(r'\s+', ' ', text)
|
| 298 |
-
# return text.strip()
|
| 299 |
-
|
| 300 |
-
# def preprocess_text(self, text):
|
| 301 |
-
# """Lowercase the text and tokenize into sentences."""
|
| 302 |
-
# text = text.lower()
|
| 303 |
-
# sentences = sent_tokenize(text)
|
| 304 |
-
# return sentences
|
| 305 |
-
|
| 306 |
-
# def get_embedding(self, text):
|
| 307 |
-
# """
|
| 308 |
-
# Compute the embedding for a given text using the "all-MiniLM-L6-v2" model.
|
| 309 |
-
# """
|
| 310 |
-
# return self.model.encode(text)
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
# def add_data_to_vectordb(self):
|
| 315 |
-
# """
|
| 316 |
-
# Iterate through all defined sources, fetch and clean the text,
|
| 317 |
-
# generate embeddings for each sufficiently long sentence,
|
| 318 |
-
# and add them to the vector DB using its underlying FAISS add_texts method.
|
| 319 |
-
# """
|
| 320 |
-
# for source, url in self.sources.items():
|
| 321 |
-
# print(f"Processing source: {source}")
|
| 322 |
-
# html_content = self.fetch_html(url)
|
| 323 |
-
# cleaned_text = self.clean_html(html_content)
|
| 324 |
-
# if not cleaned_text:
|
| 325 |
-
# print(f"No text fetched from {url}")
|
| 326 |
-
# continue
|
| 327 |
-
# sentences = self.preprocess_text(cleaned_text)
|
| 328 |
-
# texts = []
|
| 329 |
-
# metadatas = []
|
| 330 |
-
# for i, sentence in enumerate(sentences):
|
| 331 |
-
# if len(sentence) < 50:
|
| 332 |
-
# continue
|
| 333 |
-
# texts.append(sentence)
|
| 334 |
-
# metadatas.append({
|
| 335 |
-
# 'source': source,
|
| 336 |
-
# 'url': url,
|
| 337 |
-
# 'sentence_index': i,
|
| 338 |
-
# 'text': sentence
|
| 339 |
-
# })
|
| 340 |
-
# if texts:
|
| 341 |
-
# # Use the underlying FAISS vectorstore
|
| 342 |
-
# self.vector_db.vectorstore.add_texts(texts, metadatas=metadatas)
|
| 343 |
# print(f"Added {len(texts)} sentences from {source} to vector DB.")
|
|
|
|
| 1 |
+
# vectorstore.py
|
| 2 |
+
import os
|
| 3 |
+
import json
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
import faiss
|
| 6 |
+
import numpy as np
|
| 7 |
+
from sentence_transformers import SentenceTransformer
|
| 8 |
+
from pypdf import PdfReader
|
| 9 |
+
import requests
|
| 10 |
+
from bs4 import BeautifulSoup
|
| 11 |
+
|
| 12 |
+
# Updated LangChain imports
|
| 13 |
+
from langchain_community.document_loaders import PyPDFLoader
|
| 14 |
+
from langchain_community.document_loaders import WebBaseLoader
|
| 15 |
+
from langchain_community.vectorstores import FAISS
|
| 16 |
+
from langchain_huggingface import HuggingFaceEmbeddings
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class vectorstore:
|
| 20 |
+
# 1 is pdf, 2 is website, and 3 is an already created vectorstore
|
| 21 |
+
def __init__(self, path, Initlize_with=3):
|
| 22 |
+
if Initlize_with == 1:
|
| 23 |
+
self.index_path = self.create_vectorstore_from_pdf(path, embedder_model="all-MiniLM-L6-v2")
|
| 24 |
+
self.vectorstore = self.load_vectorstore(self.index_path)
|
| 25 |
+
elif Initlize_with == 2:
|
| 26 |
+
self.index_path = self.create_vectorstore_from_website(path, embedder_model="all-MiniLM-L6-v2")
|
| 27 |
+
self.vectorstore = self.load_vectorstore(self.index_path)
|
| 28 |
+
elif Initlize_with == 3:
|
| 29 |
+
self.index_path = path
|
| 30 |
+
self.vectorstore = self.load_vectorstore(self.index_path)
|
| 31 |
+
|
| 32 |
+
def chunk_text(self,text, chunk_size=300):
|
| 33 |
+
"""
|
| 34 |
+
Split text into chunks of approximately 'chunk_size' words.
|
| 35 |
+
|
| 36 |
+
Parameters:
|
| 37 |
+
text (str): The input text.
|
| 38 |
+
chunk_size (int): Maximum number of words per chunk.
|
| 39 |
+
|
| 40 |
+
Returns:
|
| 41 |
+
List[str]: A list of text chunks.
|
| 42 |
+
"""
|
| 43 |
+
words = text.split()
|
| 44 |
+
chunks = []
|
| 45 |
+
for i in range(0, len(words), chunk_size):
|
| 46 |
+
chunk = " ".join(words[i:i+chunk_size])
|
| 47 |
+
chunks.append(chunk)
|
| 48 |
+
return chunks
|
| 49 |
+
|
| 50 |
+
def create_vectorstore_from_pdf(self,pdf_path, chunk_size=500, embedder_model="all-MiniLM-L6-v2"):
|
| 51 |
+
"""
|
| 52 |
+
Extract text from a PDF using pypdf, chunk the text, compute embeddings,
|
| 53 |
+
and create a FAISS index.
|
| 54 |
+
|
| 55 |
+
Parameters:
|
| 56 |
+
pdf_path (str): Path to the PDF file.
|
| 57 |
+
chunk_size (int): Number of words per chunk.
|
| 58 |
+
embedder_model (str): The sentence-transformer model to use.
|
| 59 |
+
|
| 60 |
+
Returns:
|
| 61 |
+
index: A FAISS index containing the embeddings.
|
| 62 |
+
chunks: A list of text chunks.
|
| 63 |
+
embedder: The SentenceTransformer embedder.
|
| 64 |
+
"""
|
| 65 |
+
# Load PDF using LangChain's PyPDFLoader
|
| 66 |
+
loader = PyPDFLoader(pdf_path)
|
| 67 |
+
documents = loader.load()
|
| 68 |
+
text = " ".join([doc.page_content for doc in documents])
|
| 69 |
+
|
| 70 |
+
# Chunk text using existing method (word-based)
|
| 71 |
+
chunks = self.chunk_text(text, chunk_size)
|
| 72 |
+
|
| 73 |
+
# Create embeddings and FAISS vectorstore with LangChain
|
| 74 |
+
embedder = HuggingFaceEmbeddings(model_name=embedder_model)
|
| 75 |
+
vectorstore = FAISS.from_texts(chunks, embedder)
|
| 76 |
+
|
| 77 |
+
# Save the vectorstore
|
| 78 |
+
index_path = self.save_vectorstore_with_timestamp_and_without(vectorstore, embedder_model)
|
| 79 |
+
return index_path
|
| 80 |
+
|
| 81 |
+
def create_vectorstore_from_website(self, url, chunk_size=300, embedder_model="all-MiniLM-L6-v2"):
|
| 82 |
+
"""
|
| 83 |
+
Fetch text from a website, chunk the text, compute embeddings,
|
| 84 |
+
and create a FAISS index.
|
| 85 |
+
|
| 86 |
+
Parameters:
|
| 87 |
+
url (str): The URL of the website.
|
| 88 |
+
chunk_size (int): Number of words per chunk.
|
| 89 |
+
embedder_model (str): The sentence-transformer model to use.
|
| 90 |
+
|
| 91 |
+
Returns:
|
| 92 |
+
index: A FAISS index containing the embeddings.
|
| 93 |
+
chunks: A list of text chunks.
|
| 94 |
+
embedder: The SentenceTransformer embedder.
|
| 95 |
+
"""
|
| 96 |
+
# Load website using LangChain's WebBaseLoader
|
| 97 |
+
loader = WebBaseLoader(url)
|
| 98 |
+
documents = loader.load()
|
| 99 |
+
text = " ".join([doc.page_content for doc in documents])
|
| 100 |
+
|
| 101 |
+
# Chunk text using existing method
|
| 102 |
+
chunks = self.chunk_text(text, chunk_size)
|
| 103 |
+
|
| 104 |
+
# Create embeddings and FAISS vectorstore
|
| 105 |
+
embedder = HuggingFaceEmbeddings(model_name=embedder_model)
|
| 106 |
+
vectorstore = FAISS.from_texts(chunks, embedder)
|
| 107 |
+
|
| 108 |
+
# Save the vectorstore
|
| 109 |
+
index_path = self.save_vectorstore_with_timestamp_and_without(vectorstore, embedder_model)
|
| 110 |
+
return index_path
|
| 111 |
+
|
| 112 |
+
def add_to_vectorstore_web(self, url, index_file_path, chunk_size=300):
|
| 113 |
+
"""
|
| 114 |
+
Fetch text from a website, chunk the text, compute embeddings using the existing embedder,
|
| 115 |
+
and add them to the existing FAISS vectorstore.
|
| 116 |
+
|
| 117 |
+
Parameters:
|
| 118 |
+
url (str): The URL of the website.
|
| 119 |
+
index_file_path (str): The file path of the saved vectorstore index.
|
| 120 |
+
chunk_size (int): Maximum number of words per chunk.
|
| 121 |
+
|
| 122 |
+
Returns:
|
| 123 |
+
str: The updated vectorstore index file path.
|
| 124 |
+
"""
|
| 125 |
+
# Load the existing vectorstore
|
| 126 |
+
vectorstore = self.load_vectorstore(index_file_path)
|
| 127 |
+
|
| 128 |
+
# Fetch and extract text from the website
|
| 129 |
+
loader = WebBaseLoader(url)
|
| 130 |
+
documents = loader.load()
|
| 131 |
+
text = " ".join([doc.page_content for doc in documents])
|
| 132 |
+
|
| 133 |
+
# Chunk the text
|
| 134 |
+
new_chunks = self.chunk_text(text, chunk_size)
|
| 135 |
+
|
| 136 |
+
# Add new chunks to the vectorstore
|
| 137 |
+
vectorstore.add_texts(new_chunks)
|
| 138 |
+
|
| 139 |
+
# Save the updated vectorstore
|
| 140 |
+
updated_index_path = self.save_vectorstore_with_timestamp_and_without(vectorstore, vectorstore.embedding_function.model_name)
|
| 141 |
+
return updated_index_path
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def add_to_vectorstore_from_pdf(self, pdf_path, chunk_size=500):
|
| 145 |
+
"""
|
| 146 |
+
Extract text from a PDF using PyPDF2, chunk the text, compute embeddings using the existing embedder,
|
| 147 |
+
and add them to the existing FAISS vectorstore.
|
| 148 |
+
|
| 149 |
+
Parameters:
|
| 150 |
+
pdf_path (str): Path to the PDF file.
|
| 151 |
+
index_file_path (str): The file path of the saved vectorstore index.
|
| 152 |
+
chunk_size (int): Maximum number of words per chunk.
|
| 153 |
+
|
| 154 |
+
Returns:
|
| 155 |
+
str: The updated vectorstore index file path.
|
| 156 |
+
"""
|
| 157 |
+
# Extract text from PDF
|
| 158 |
+
loader = PyPDFLoader(pdf_path)
|
| 159 |
+
documents = loader.load()
|
| 160 |
+
text = " ".join([doc.page_content for doc in documents])
|
| 161 |
+
|
| 162 |
+
# Chunk the text
|
| 163 |
+
new_chunks = self.chunk_text(text, chunk_size)
|
| 164 |
+
|
| 165 |
+
# Add new chunks to the existing vectorstore
|
| 166 |
+
self.vectorstore.add_texts(new_chunks)
|
| 167 |
+
|
| 168 |
+
# Save the updated vectorstore
|
| 169 |
+
self.index_path = self.save_vectorstore_with_timestamp_and_without(self.vectorstore, self.vectorstore.embedding_function.model_name)
|
| 170 |
+
return self.index_path
|
| 171 |
+
|
| 172 |
+
def save_vectorstore_with_timestamp_and_without(self, vectorstore, embedder_model=None):
|
| 173 |
+
vector_db_folder = os.path.join(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")), "VectorDB")
|
| 174 |
+
os.makedirs(vector_db_folder, exist_ok=True)
|
| 175 |
+
|
| 176 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 177 |
+
folder_name = f"vectorstore_{timestamp}"
|
| 178 |
+
folder_path = os.path.join(vector_db_folder, folder_name)
|
| 179 |
+
|
| 180 |
+
# Save the LangChain FAISS vectorstore
|
| 181 |
+
vectorstore.save_local(folder_path)
|
| 182 |
+
|
| 183 |
+
# Save metadata with embedder model name
|
| 184 |
+
metadata = {"embedder_model": embedder_model or "all-MiniLM-L6-v2"}
|
| 185 |
+
with open(os.path.join(folder_path, "metadata.json"), "w") as f:
|
| 186 |
+
json.dump(metadata, f)
|
| 187 |
+
|
| 188 |
+
# Save to main folder
|
| 189 |
+
main_folder = os.path.join(vector_db_folder, "vectorstore_mainV2")
|
| 190 |
+
vectorstore.save_local(main_folder)
|
| 191 |
+
with open(os.path.join(main_folder, "metadata.json"), "w") as f:
|
| 192 |
+
json.dump(metadata, f)
|
| 193 |
+
|
| 194 |
+
return main_folder
|
| 195 |
+
|
| 196 |
+
def load_vectorstore(self, index_path):
|
| 197 |
+
# Load metadata to get embedder model
|
| 198 |
+
metadata_path = os.path.join(index_path, "metadata.json")
|
| 199 |
+
with open(metadata_path, "r") as f:
|
| 200 |
+
metadata = json.load(f)
|
| 201 |
+
embedder_model = metadata["embedder_model"]
|
| 202 |
+
|
| 203 |
+
# Create embedder and load vectorstore
|
| 204 |
+
embedder = HuggingFaceEmbeddings(model_name=embedder_model)
|
| 205 |
+
vectorstore = FAISS.load_local(index_path, embedder)
|
| 206 |
+
return vectorstore
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def search_vectorstore(self, query, top_k=5):
|
| 210 |
+
# Search using LangChain's similarity_search
|
| 211 |
+
docs = self.vectorstore.similarity_search(query, k=top_k)
|
| 212 |
+
results = [doc.page_content for doc in docs]
|
| 213 |
+
return results
|
| 214 |
+
|
| 215 |
+
def log_conversation(self, user_text, bot_text=""):
|
| 216 |
+
# Existing JSON logging
|
| 217 |
+
logs_folder = os.path.join(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")), "logs")
|
| 218 |
+
os.makedirs(logs_folder, exist_ok=True)
|
| 219 |
+
log_file = os.path.join(logs_folder, "conversation_logs.json")
|
| 220 |
+
entry = {
|
| 221 |
+
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
| 222 |
+
"User": {"text": user_text},
|
| 223 |
+
"bot": {"text": bot_text}
|
| 224 |
+
}
|
| 225 |
+
if os.path.exists(log_file):
|
| 226 |
+
with open(log_file, "r", encoding="utf-8") as f:
|
| 227 |
+
try:
|
| 228 |
+
logs = json.load(f)
|
| 229 |
+
except json.JSONDecodeError:
|
| 230 |
+
logs = []
|
| 231 |
+
else:
|
| 232 |
+
logs = []
|
| 233 |
+
logs.append(entry)
|
| 234 |
+
with open(log_file, "w", encoding="utf-8") as f:
|
| 235 |
+
json.dump(logs, f, indent=4)
|
| 236 |
+
|
| 237 |
+
# Add to LangMem memory
|
| 238 |
+
self.memory.add_message({"role": "user", "content": user_text})
|
| 239 |
+
if bot_text:
|
| 240 |
+
self.memory.add_message({"role": "assistant", "content": bot_text})
|
| 241 |
+
|
| 242 |
+
# # ...existing code...
|
| 243 |
+
|
| 244 |
+
# import re
|
| 245 |
+
# import requests
|
| 246 |
+
# import nltk
|
| 247 |
+
# from nltk.tokenize import sent_tokenize
|
| 248 |
+
# import numpy as np
|
| 249 |
+
|
| 250 |
+
# # Download NLTK data (only once; consider moving this to a setup step)
|
| 251 |
+
# nltk.download('punkt')
|
| 252 |
+
# nltk.download('punkt_tab')
|
| 253 |
+
|
| 254 |
+
# class CancerDataIngestor:
|
| 255 |
+
# def __init__(self,vector_db=None, source_urls=None, embedding_model=None):
|
| 256 |
+
# """
|
| 257 |
+
# Initialize with:
|
| 258 |
+
# - source_urls: a dictionary mapping source names to URLs.
|
| 259 |
+
# - embedding_model: a callable that takes text and returns an embedding.
|
| 260 |
+
# - vector_db: an instance of your vector database.
|
| 261 |
+
# """
|
| 262 |
+
# self.sources = source_urls if source_urls is not None else {
|
| 263 |
+
# 'PMC': 'https://www.ncbi.nlm.nih.gov/pmc/',
|
| 264 |
+
# 'NCI': 'https://www.cancer.gov/about-cancer/understanding/statistics',
|
| 265 |
+
# 'WHO': 'https://www.who.int/cancer/en/',
|
| 266 |
+
# 'ClinicalTrials': 'https://clinicaltrials.gov/',
|
| 267 |
+
# 'Kaggle': 'https://www.kaggle.com/datasets'
|
| 268 |
+
# }
|
| 269 |
+
# # Use the provided embedding model or default to self.get_embedding
|
| 270 |
+
# self.embedding_model = embedding_model if embedding_model is not None else self.get_embedding
|
| 271 |
+
# if vector_db is None:
|
| 272 |
+
# raise ValueError("A valid vector DB instance must be provided.")
|
| 273 |
+
# self.vector_db = vector_db
|
| 274 |
+
# # Initialize the SentenceTransformer model once.
|
| 275 |
+
# self.model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 276 |
+
|
| 277 |
+
# def fetch_html(self, url):
|
| 278 |
+
# """Fetch HTML content from a given URL."""
|
| 279 |
+
# try:
|
| 280 |
+
# response = requests.get(url)
|
| 281 |
+
# response.raise_for_status()
|
| 282 |
+
# return response.text
|
| 283 |
+
# except Exception as e:
|
| 284 |
+
# print(f"Error fetching URL {url}: {e}")
|
| 285 |
+
# return None
|
| 286 |
+
|
| 287 |
+
# def clean_html(self, html):
|
| 288 |
+
# """Extract text from HTML and remove tags and extra spaces."""
|
| 289 |
+
# if html is None:
|
| 290 |
+
# return ""
|
| 291 |
+
# from bs4 import BeautifulSoup # in case not already imported above
|
| 292 |
+
# soup = BeautifulSoup(html, 'html.parser')
|
| 293 |
+
# for tag in soup(['script', 'style']):
|
| 294 |
+
# tag.decompose()
|
| 295 |
+
# text = soup.get_text(separator=' ')
|
| 296 |
+
# text = re.sub(r'[^a-zA-Z0-9.,;:?!\s]', ' ', text)
|
| 297 |
+
# text = re.sub(r'\s+', ' ', text)
|
| 298 |
+
# return text.strip()
|
| 299 |
+
|
| 300 |
+
# def preprocess_text(self, text):
|
| 301 |
+
# """Lowercase the text and tokenize into sentences."""
|
| 302 |
+
# text = text.lower()
|
| 303 |
+
# sentences = sent_tokenize(text)
|
| 304 |
+
# return sentences
|
| 305 |
+
|
| 306 |
+
# def get_embedding(self, text):
|
| 307 |
+
# """
|
| 308 |
+
# Compute the embedding for a given text using the "all-MiniLM-L6-v2" model.
|
| 309 |
+
# """
|
| 310 |
+
# return self.model.encode(text)
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
# def add_data_to_vectordb(self):
|
| 315 |
+
# """
|
| 316 |
+
# Iterate through all defined sources, fetch and clean the text,
|
| 317 |
+
# generate embeddings for each sufficiently long sentence,
|
| 318 |
+
# and add them to the vector DB using its underlying FAISS add_texts method.
|
| 319 |
+
# """
|
| 320 |
+
# for source, url in self.sources.items():
|
| 321 |
+
# print(f"Processing source: {source}")
|
| 322 |
+
# html_content = self.fetch_html(url)
|
| 323 |
+
# cleaned_text = self.clean_html(html_content)
|
| 324 |
+
# if not cleaned_text:
|
| 325 |
+
# print(f"No text fetched from {url}")
|
| 326 |
+
# continue
|
| 327 |
+
# sentences = self.preprocess_text(cleaned_text)
|
| 328 |
+
# texts = []
|
| 329 |
+
# metadatas = []
|
| 330 |
+
# for i, sentence in enumerate(sentences):
|
| 331 |
+
# if len(sentence) < 50:
|
| 332 |
+
# continue
|
| 333 |
+
# texts.append(sentence)
|
| 334 |
+
# metadatas.append({
|
| 335 |
+
# 'source': source,
|
| 336 |
+
# 'url': url,
|
| 337 |
+
# 'sentence_index': i,
|
| 338 |
+
# 'text': sentence
|
| 339 |
+
# })
|
| 340 |
+
# if texts:
|
| 341 |
+
# # Use the underlying FAISS vectorstore
|
| 342 |
+
# self.vector_db.vectorstore.add_texts(texts, metadatas=metadatas)
|
| 343 |
# print(f"Added {len(texts)} sentences from {source} to vector DB.")
|