Saraay commited on
Commit
2892a63
·
verified ·
1 Parent(s): f63dbe5

Upload generate_embeddings.py

Browse files
Files changed (1) hide show
  1. generate_embeddings.py +104 -0
generate_embeddings.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pickle
3
+ import time
4
+ from langchain_community.vectorstores import Chroma
5
+ from langchain_huggingface import HuggingFaceEmbeddings
6
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
7
+ from langchain_community.document_loaders import PyPDFLoader
8
+ from langchain.docstore.document import Document
9
+ from typing import List
10
+ import re
11
+ from nltk.corpus import stopwords
12
+ from nltk.stem import WordNetLemmatizer
13
+ import nltk
14
+
15
+ # Download NLTK stopwords (run once)
16
+ nltk.download('stopwords')
17
+ nltk.download('wordnet')
18
+ # Specify the folder containing PDF documents
19
+ folder_path = r'/mnt/e/ML/projects/my_own_projects/nutrition/documents'
20
+
21
+ # Initialize stopwords
22
+ stop_words = set(stopwords.words('english'))
23
+
24
+ # Function to clean and preprocess text
25
+ lemmatizer = WordNetLemmatizer()
26
+
27
+ def clean_text(text: str) -> str:
28
+ # Remove special characters (keep numbers)
29
+ text = re.sub(r'[^\w\s\d]', ' ', text)
30
+ # Convert to lowercase
31
+ text = text.lower()
32
+ # Remove stopwords
33
+ text = ' '.join([word for word in text.split() if word not in stop_words])
34
+ # Lemmatize words
35
+ text = ' '.join([lemmatizer.lemmatize(word) for word in text.split()])
36
+ return text
37
+
38
+ # Function to process PDFs and extract metadata
39
+ def process_pdfs(folder_path: str) -> List[Document]:
40
+ docs = []
41
+ pdf_count = 0
42
+ for filename in os.listdir(folder_path):
43
+ if filename.endswith('.pdf'):
44
+ pdf_count += 1
45
+ file_path = os.path.join(folder_path, filename)
46
+ print(f"Processing PDF {pdf_count}: {filename}")
47
+ loader = PyPDFLoader(file_path)
48
+ pages = loader.load()
49
+ for page in pages:
50
+ # Clean the text
51
+ page.page_content = clean_text(page.page_content)
52
+ # Add metadata (e.g., filename)
53
+ page.metadata['source'] = filename
54
+ docs.extend(pages)
55
+ print(f"Total number of PDFs processed: {pdf_count}")
56
+ return docs
57
+
58
+ # Function to split documents into chunks
59
+ def split_documents(docs: List[Document]) -> List[Document]:
60
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
61
+ chunks = text_splitter.split_documents(docs)
62
+ print(f"Total number of chunks generated for embeddings: {len(chunks)}")
63
+ return chunks
64
+
65
+ # Function to generate embeddings and create vectorstore
66
+ def create_vectorstore(docs: List[Document], persist_directory: str = "./chroma_db_nccn") -> Chroma:
67
+ # Initialize the HuggingFace embeddings function
68
+ embedding_function = HuggingFaceEmbeddings(
69
+ model_name="sentence-transformers/all-MiniLM-L6-v2",
70
+ model_kwargs={'device': 'cpu'} # Use 'cpu' if GPU is not available
71
+ )
72
+
73
+ # Create Chroma vectorstore and persist it
74
+ print("Creating vectorstore...")
75
+ start_time = time.time()
76
+ vectorstore = Chroma.from_documents(docs, embedding_function, persist_directory=persist_directory)
77
+ end_time = time.time()
78
+ print(f"Time taken to create vectorstore: {end_time - start_time} seconds")
79
+ return vectorstore
80
+
81
+ # Main function
82
+ def main():
83
+ # Check if processed documents already exist
84
+ if os.path.exists("processed_docs.pkl"):
85
+ print("Loading processed documents from file...")
86
+ with open("processed_docs.pkl", "rb") as f:
87
+ docs = pickle.load(f)
88
+ else:
89
+ print("Processing PDFs...")
90
+ docs = process_pdfs(folder_path)
91
+ print("Splitting documents into chunks...")
92
+ docs = split_documents(docs)
93
+ # Save processed documents to file
94
+ with open("processed_docs.pkl", "wb") as f:
95
+ pickle.dump(docs, f)
96
+
97
+ # Create vectorstore
98
+ vectorstore = create_vectorstore(docs)
99
+
100
+ # Debugging message: Number of documents stored in vectorstore
101
+ print(f"Number of documents stored in the vectorstore: {vectorstore._collection.count()}")
102
+
103
+ if __name__ == "__main__":
104
+ main()