Update retriever/embed_documents.py
Browse files- retriever/embed_documents.py +99 -98
retriever/embed_documents.py
CHANGED
@@ -1,98 +1,99 @@
|
|
1 |
-
'''import os
|
2 |
-
import logging
|
3 |
-
from langchain_huggingface import HuggingFaceEmbeddings
|
4 |
-
from langchain_community.vectorstores import FAISS
|
5 |
-
|
6 |
-
from config import ConfigConstants
|
7 |
-
|
8 |
-
def embed_documents(documents, embedding_path="embeddings.faiss"):
|
9 |
-
embedding_model = HuggingFaceEmbeddings(model_name=ConfigConstants.EMBEDDING_MODEL_NAME)
|
10 |
-
|
11 |
-
if os.path.exists(embedding_path):
|
12 |
-
logging.info("Loading embeddings from local file")
|
13 |
-
vector_store = FAISS.load_local(embedding_path, embedding_model, allow_dangerous_deserialization=True)
|
14 |
-
else:
|
15 |
-
logging.info("Generating and saving embeddings")
|
16 |
-
vector_store = FAISS.from_texts([doc['text'] for doc in documents], embedding_model)
|
17 |
-
vector_store.save_local(embedding_path)
|
18 |
-
|
19 |
-
return vector_store'''
|
20 |
-
|
21 |
-
import os
|
22 |
-
import logging
|
23 |
-
import hashlib
|
24 |
-
from typing import List, Dict
|
25 |
-
from concurrent.futures import ThreadPoolExecutor
|
26 |
-
from tqdm import tqdm
|
27 |
-
from langchain_community.vectorstores import FAISS
|
28 |
-
from langchain_huggingface import HuggingFaceEmbeddings
|
29 |
-
from config import ConfigConstants
|
30 |
-
|
31 |
-
|
32 |
-
def embed_documents(documents: List[Dict], embedding_path: str = ConfigConstants.DATA_SET_PATH + "embeddings/embeddings.faiss", metadata_path: str = ConfigConstants.DATA_SET_PATH + "embeddings/metadata.json") -> FAISS:
|
33 |
-
logging.info(f"Total documents got :{len(documents)}")
|
34 |
-
os.makedirs(
|
35 |
-
os.makedirs(
|
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 |
-
|
|
|
|
1 |
+
'''import os
|
2 |
+
import logging
|
3 |
+
from langchain_huggingface import HuggingFaceEmbeddings
|
4 |
+
from langchain_community.vectorstores import FAISS
|
5 |
+
|
6 |
+
from config import ConfigConstants
|
7 |
+
|
8 |
+
def embed_documents(documents, embedding_path="embeddings.faiss"):
|
9 |
+
embedding_model = HuggingFaceEmbeddings(model_name=ConfigConstants.EMBEDDING_MODEL_NAME)
|
10 |
+
|
11 |
+
if os.path.exists(embedding_path):
|
12 |
+
logging.info("Loading embeddings from local file")
|
13 |
+
vector_store = FAISS.load_local(embedding_path, embedding_model, allow_dangerous_deserialization=True)
|
14 |
+
else:
|
15 |
+
logging.info("Generating and saving embeddings")
|
16 |
+
vector_store = FAISS.from_texts([doc['text'] for doc in documents], embedding_model)
|
17 |
+
vector_store.save_local(embedding_path)
|
18 |
+
|
19 |
+
return vector_store'''
|
20 |
+
|
21 |
+
import os
|
22 |
+
import logging
|
23 |
+
import hashlib
|
24 |
+
from typing import List, Dict
|
25 |
+
from concurrent.futures import ThreadPoolExecutor
|
26 |
+
from tqdm import tqdm
|
27 |
+
from langchain_community.vectorstores import FAISS
|
28 |
+
from langchain_huggingface import HuggingFaceEmbeddings
|
29 |
+
from config import ConfigConstants
|
30 |
+
|
31 |
+
|
32 |
+
def embed_documents(documents: List[Dict], embedding_path: str = ConfigConstants.DATA_SET_PATH + "embeddings/embeddings.faiss", metadata_path: str = ConfigConstants.DATA_SET_PATH + "embeddings/metadata.json") -> FAISS:
|
33 |
+
logging.info(f"Total documents got :{len(documents)}")
|
34 |
+
os.makedirs(embedding_path, exist_ok=True)
|
35 |
+
os.makedirs(metadata_path, exist_ok=True)
|
36 |
+
|
37 |
+
embedding_model = HuggingFaceEmbeddings(model_name=ConfigConstants.EMBEDDING_MODEL_NAME)
|
38 |
+
|
39 |
+
if os.path.exists(embedding_path) and os.path.exists(metadata_path):
|
40 |
+
logging.info("Loading embeddings and metadata from local files")
|
41 |
+
vector_store = FAISS.load_local(embedding_path, embedding_model, allow_dangerous_deserialization=True)
|
42 |
+
existing_metadata = _load_metadata(metadata_path)
|
43 |
+
else:
|
44 |
+
# Initialize FAISS with at least one document to avoid the IndexError
|
45 |
+
if documents:
|
46 |
+
vector_store = FAISS.from_texts([documents[0]['text']], embedding_model)
|
47 |
+
else:
|
48 |
+
# If no documents are provided, initialize an empty FAISS index with a dummy document
|
49 |
+
vector_store = FAISS.from_texts(["dummy document"], embedding_model)
|
50 |
+
existing_metadata = {}
|
51 |
+
|
52 |
+
# Identify new or modified documents
|
53 |
+
new_documents = []
|
54 |
+
for doc in documents:
|
55 |
+
doc_hash = _generate_document_hash(doc['text'])
|
56 |
+
if doc_hash not in existing_metadata:
|
57 |
+
new_documents.append(doc)
|
58 |
+
existing_metadata[doc_hash] = True # Mark as processed
|
59 |
+
|
60 |
+
if new_documents:
|
61 |
+
logging.info(f"Generating embeddings for {len(new_documents)} new documents")
|
62 |
+
with ThreadPoolExecutor() as executor:
|
63 |
+
futures = []
|
64 |
+
for doc in new_documents:
|
65 |
+
futures.append(executor.submit(_embed_single_document, doc, embedding_model))
|
66 |
+
|
67 |
+
for future in tqdm(futures, desc="Generating embeddings", unit="doc"):
|
68 |
+
vector_store.add_texts([future.result()])
|
69 |
+
|
70 |
+
# Save updated embeddings and metadata
|
71 |
+
vector_store.save_local(embedding_path)
|
72 |
+
_save_metadata(metadata_path, existing_metadata)
|
73 |
+
else:
|
74 |
+
logging.info("No new documents to process. Using existing embeddings.")
|
75 |
+
|
76 |
+
return vector_store
|
77 |
+
|
78 |
+
def _embed_single_document(doc: Dict, embedding_model: HuggingFaceEmbeddings) -> str:
|
79 |
+
return doc['text']
|
80 |
+
|
81 |
+
def _generate_document_hash(text: str) -> str:
|
82 |
+
"""Generate a unique hash for a document based on its text."""
|
83 |
+
return hashlib.sha256(text.encode()).hexdigest()
|
84 |
+
|
85 |
+
def _load_metadata(metadata_path: str) -> Dict[str, bool]:
|
86 |
+
"""Load metadata from a file."""
|
87 |
+
import json
|
88 |
+
if os.path.exists(metadata_path):
|
89 |
+
with open(metadata_path, "r") as f:
|
90 |
+
return json.load(f)
|
91 |
+
return {}
|
92 |
+
|
93 |
+
def _save_metadata(metadata_path: str, metadata: Dict[str, bool]):
|
94 |
+
"""Save metadata to a file."""
|
95 |
+
import json
|
96 |
+
with open(metadata_path, "w") as f:
|
97 |
+
json.dump(metadata, f)
|
98 |
+
|
99 |
+
|