-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEmbedder.py
More file actions
59 lines (44 loc) · 2.22 KB
/
Embedder.py
File metadata and controls
59 lines (44 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import os
import io
import streamlit as st
from langchain_community.embeddings import OpenAIEmbeddings
from langchain.chains import ConversationalRetrievalChain
from langchain_community.vectorstores import FAISS
from langchain.document_loaders.csv_loader import CSVLoader
class Embedder:
"""
Embedder objects allow to create embeddings of any .csv document.
Use getVectorStore to create a vector store from a .csv document in one line. It can be then used for the retriever.
"""
def __init__(self, OPENAI_API_KEY):
self.API_KEY = OPENAI_API_KEY
self.PATH = ""
# self.PATH = "Embeddings"
# if not os.path.exists(self.PATH):
# os.mkdir(self.PATH)
@staticmethod
def initializeData(data_path: str):
loader = CSVLoader(file_path=data_path, encoding="utf-8", csv_args={
'delimiter': '\n'})
return loader.load()
def getVectorStore(self, data_filename: str):
# If there is no saved vector store, generate a new one and save it before returning it
# Else return the saved vector store
data_path = data_filename + ".csv"
vector_filename = f"vectors_{data_filename}"
vectorsPath = vector_filename + ".pkl"
embeddings = OpenAIEmbeddings(openai_api_key=self.API_KEY)
# If wanted data is already saved in its folder
if(os.path.isdir(vector_filename)):
print(f"Loading saved vectorstore from {vector_filename}")
vectorStore = FAISS.load_local(vector_filename, embeddings, allow_dangerous_deserialization=True)
return vectorStore
# Check if data_filename exists before creating a new vector store
if(not os.path.isfile(data_path)):
raise RuntimeError(f"Error: No such file name as {data_filename}")
with io.open(data_path) as data_file:
data = self.initializeData(data_path)
vectorStore = FAISS.from_documents(data, embeddings)
vectorStore.save_local(vector_filename)
print(f"New vectorstore saved as {vector_filename}")
return vectorStore