jarif commited on
Commit
c2d2148
·
verified ·
1 Parent(s): b5d8569

Update ingest.py

Browse files
Files changed (1) hide show
  1. ingest.py +14 -10
ingest.py CHANGED
@@ -1,22 +1,25 @@
1
  import os
2
  import logging
3
  import faiss
4
- import numpy as np
5
  from langchain_community.document_loaders import PDFMinerLoader
6
  from langchain.text_splitter import RecursiveCharacterTextSplitter
7
  from langchain_community.embeddings import HuggingFaceEmbeddings
 
8
 
 
9
  logging.basicConfig(level=logging.INFO)
10
  logger = logging.getLogger(__name__)
11
 
12
  def create_faiss_index():
13
  documents = []
14
- docs_dir = "docs"
15
 
 
16
  if not os.path.exists(docs_dir):
17
  logger.error(f"The directory '{docs_dir}' does not exist.")
18
  return
19
 
 
20
  for root, dirs, files in os.walk(docs_dir):
21
  for file in files:
22
  if file.endswith(".pdf"):
@@ -33,38 +36,39 @@ def create_faiss_index():
33
  except Exception as e:
34
  logger.error(f"Error loading {file_path}: {e}")
35
 
 
36
  if not documents:
37
  logger.error("No documents were loaded. Check the 'docs' directory and file paths.")
38
  return
39
 
40
  logger.info(f"Loaded {len(documents)} documents.")
41
 
 
42
  text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
43
  texts = text_splitter.split_documents(documents)
44
  logger.info(f"Created {len(texts)} text chunks.")
 
 
45
  if not texts:
46
  logger.error("No text chunks created. Check the text splitting process.")
47
  return
48
 
49
  try:
 
50
  embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
51
  logger.info("Embeddings initialized successfully.")
52
  except Exception as e:
53
  logger.error(f"Failed to initialize embeddings: {e}")
54
  return
55
 
56
- embedding_vectors = np.array([embeddings.embed(text) for text in texts])
57
- dimension = embedding_vectors.shape[1]
58
-
59
  try:
60
- faiss_index = faiss.IndexFlatL2(dimension)
61
- faiss_index.add(embedding_vectors)
62
- os.makedirs("faiss_index", exist_ok=True) # Create directory if it doesn't exist
63
- faiss.write_index(faiss_index, "faiss_index/index.faiss")
64
  logger.info(f"Created FAISS index with {len(texts)} vectors.")
65
  except Exception as e:
66
  logger.error(f"Failed to create FAISS index: {e}")
67
- return
68
 
69
  if __name__ == "__main__":
70
  create_faiss_index()
 
1
  import os
2
  import logging
3
  import faiss
 
4
  from langchain_community.document_loaders import PDFMinerLoader
5
  from langchain.text_splitter import RecursiveCharacterTextSplitter
6
  from langchain_community.embeddings import HuggingFaceEmbeddings
7
+ from langchain.vectorstores import FAISS
8
 
9
+ # Configure logging
10
  logging.basicConfig(level=logging.INFO)
11
  logger = logging.getLogger(__name__)
12
 
13
  def create_faiss_index():
14
  documents = []
15
+ docs_dir = "docs" # Directory where PDF files are stored
16
 
17
+ # Check if the 'docs' directory exists
18
  if not os.path.exists(docs_dir):
19
  logger.error(f"The directory '{docs_dir}' does not exist.")
20
  return
21
 
22
+ # Walk through the 'docs' directory and load PDF files
23
  for root, dirs, files in os.walk(docs_dir):
24
  for file in files:
25
  if file.endswith(".pdf"):
 
36
  except Exception as e:
37
  logger.error(f"Error loading {file_path}: {e}")
38
 
39
+ # Check if any documents were loaded
40
  if not documents:
41
  logger.error("No documents were loaded. Check the 'docs' directory and file paths.")
42
  return
43
 
44
  logger.info(f"Loaded {len(documents)} documents.")
45
 
46
+ # Split documents into text chunks
47
  text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
48
  texts = text_splitter.split_documents(documents)
49
  logger.info(f"Created {len(texts)} text chunks.")
50
+
51
+ # Check if text chunks were created
52
  if not texts:
53
  logger.error("No text chunks created. Check the text splitting process.")
54
  return
55
 
56
  try:
57
+ # Initialize embeddings using HuggingFace models
58
  embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
59
  logger.info("Embeddings initialized successfully.")
60
  except Exception as e:
61
  logger.error(f"Failed to initialize embeddings: {e}")
62
  return
63
 
 
 
 
64
  try:
65
+ # Create a FAISS index and save it
66
+ index = faiss.IndexFlatL2(embeddings.embedding_size)
67
+ vector_store = FAISS.from_documents(texts, embeddings, index)
68
+ vector_store.save_local("faiss_index")
69
  logger.info(f"Created FAISS index with {len(texts)} vectors.")
70
  except Exception as e:
71
  logger.error(f"Failed to create FAISS index: {e}")
 
72
 
73
  if __name__ == "__main__":
74
  create_faiss_index()