KishoreKommi commited on
Commit
b23a17d
·
1 Parent(s): 6bb8bf7

Upload 4 files

Browse files
Files changed (4) hide show
  1. constants.py +15 -0
  2. ingest.py +166 -0
  3. privateGPT.py +76 -0
  4. requirements.txt +13 -0
constants.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from dotenv import load_dotenv
3
+ from chromadb.config import Settings
4
+
5
+ load_dotenv()
6
+
7
+ # Define the folder for storing database
8
+ PERSIST_DIRECTORY = os.environ.get('PERSIST_DIRECTORY')
9
+
10
+ # Define the Chroma settings
11
+ CHROMA_SETTINGS = Settings(
12
+ chroma_db_impl='duckdb+parquet',
13
+ persist_directory=PERSIST_DIRECTORY,
14
+ anonymized_telemetry=False
15
+ )
ingest.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import os
3
+ import glob
4
+ from typing import List
5
+ from dotenv import load_dotenv
6
+ from multiprocessing import Pool
7
+ from tqdm import tqdm
8
+
9
+ from langchain.document_loaders import (
10
+ CSVLoader,
11
+ EverNoteLoader,
12
+ PDFMinerLoader,
13
+ TextLoader,
14
+ UnstructuredEmailLoader,
15
+ UnstructuredEPubLoader,
16
+ UnstructuredHTMLLoader,
17
+ UnstructuredMarkdownLoader,
18
+ UnstructuredODTLoader,
19
+ UnstructuredPowerPointLoader,
20
+ UnstructuredWordDocumentLoader,
21
+ )
22
+
23
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
24
+ from langchain.vectorstores import Chroma
25
+ from langchain.embeddings import HuggingFaceEmbeddings
26
+ from langchain.docstore.document import Document
27
+ from constants import CHROMA_SETTINGS
28
+
29
+
30
+ load_dotenv()
31
+
32
+
33
+ # Load environment variables
34
+ persist_directory = os.environ.get('PERSIST_DIRECTORY')
35
+ source_directory = os.environ.get('SOURCE_DIRECTORY', 'source_documents')
36
+ embeddings_model_name = os.environ.get('EMBEDDINGS_MODEL_NAME')
37
+ chunk_size = 500
38
+ chunk_overlap = 50
39
+
40
+
41
+ # Custom document loaders
42
+ class MyElmLoader(UnstructuredEmailLoader):
43
+ """Wrapper to fallback to text/plain when default does not work"""
44
+
45
+ def load(self) -> List[Document]:
46
+ """Wrapper adding fallback for elm without html"""
47
+ try:
48
+ try:
49
+ doc = UnstructuredEmailLoader.load(self)
50
+ except ValueError as e:
51
+ if 'text/html content not found in email' in str(e):
52
+ # Try plain text
53
+ self.unstructured_kwargs["content_source"]="text/plain"
54
+ doc = UnstructuredEmailLoader.load(self)
55
+ else:
56
+ raise
57
+ except Exception as e:
58
+ # Add file_path to exception message
59
+ raise type(e)(f"{self.file_path}: {e}") from e
60
+
61
+ return doc
62
+
63
+
64
+ # Map file extensions to document loaders and their arguments
65
+ LOADER_MAPPING = {
66
+ ".csv": (CSVLoader, {}),
67
+ # ".docx": (Docx2txtLoader, {}),
68
+ ".doc": (UnstructuredWordDocumentLoader, {}),
69
+ ".docx": (UnstructuredWordDocumentLoader, {}),
70
+ ".enex": (EverNoteLoader, {}),
71
+ ".eml": (MyElmLoader, {}),
72
+ ".epub": (UnstructuredEPubLoader, {}),
73
+ ".html": (UnstructuredHTMLLoader, {}),
74
+ ".md": (UnstructuredMarkdownLoader, {}),
75
+ ".odt": (UnstructuredODTLoader, {}),
76
+ ".pdf": (PDFMinerLoader, {}),
77
+ ".ppt": (UnstructuredPowerPointLoader, {}),
78
+ ".pptx": (UnstructuredPowerPointLoader, {}),
79
+ ".txt": (TextLoader, {"encoding": "utf8"}),
80
+ # Add more mappings for other file extensions and loaders as needed
81
+ }
82
+
83
+
84
+ def load_single_document(file_path: str) -> List[Document]:
85
+ ext = "." + file_path.rsplit(".", 1)[-1]
86
+ if ext in LOADER_MAPPING:
87
+ loader_class, loader_args = LOADER_MAPPING[ext]
88
+ loader = loader_class(file_path, **loader_args)
89
+ return loader.load()
90
+
91
+ raise ValueError(f"Unsupported file extension '{ext}'")
92
+
93
+ def load_documents(source_dir: str, ignored_files: List[str] = []) -> List[Document]:
94
+ """
95
+ Loads all documents from the source documents directory, ignoring specified files
96
+ """
97
+ all_files = []
98
+ for ext in LOADER_MAPPING:
99
+ all_files.extend(
100
+ glob.glob(os.path.join(source_dir, f"**/*{ext}"), recursive=True)
101
+ )
102
+ filtered_files = [file_path for file_path in all_files if file_path not in ignored_files]
103
+
104
+ with Pool(processes=os.cpu_count()) as pool:
105
+ results = []
106
+ with tqdm(total=len(filtered_files), desc='Loading new documents', ncols=80) as pbar:
107
+ for i, docs in enumerate(pool.imap_unordered(load_single_document, filtered_files)):
108
+ results.extend(docs)
109
+ pbar.update()
110
+
111
+ return results
112
+
113
+ def process_documents(ignored_files: List[str] = []) -> List[Document]:
114
+ """
115
+ Load documents and split in chunks
116
+ """
117
+ print(f"Loading documents from {source_directory}")
118
+ documents = load_documents(source_directory, ignored_files)
119
+ if not documents:
120
+ print("No new documents to load")
121
+ exit(0)
122
+ print(f"Loaded {len(documents)} new documents from {source_directory}")
123
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
124
+ texts = text_splitter.split_documents(documents)
125
+ print(f"Split into {len(texts)} chunks of text (max. {chunk_size} tokens each)")
126
+ return texts
127
+
128
+ def does_vectorstore_exist(persist_directory: str) -> bool:
129
+ """
130
+ Checks if vectorstore exists
131
+ """
132
+ if os.path.exists(os.path.join(persist_directory, 'index')):
133
+ if os.path.exists(os.path.join(persist_directory, 'chroma-collections.parquet')) and os.path.exists(os.path.join(persist_directory, 'chroma-embeddings.parquet')):
134
+ list_index_files = glob.glob(os.path.join(persist_directory, 'index/*.bin'))
135
+ list_index_files += glob.glob(os.path.join(persist_directory, 'index/*.pkl'))
136
+ # At least 3 documents are needed in a working vectorstore
137
+ if len(list_index_files) > 3:
138
+ return True
139
+ return False
140
+
141
+ def main():
142
+ # Create embeddings
143
+ embeddings = HuggingFaceEmbeddings(model_name=embeddings_model_name)
144
+
145
+ if does_vectorstore_exist(persist_directory):
146
+ # Update and store locally vectorstore
147
+ print(f"Appending to existing vectorstore at {persist_directory}")
148
+ db = Chroma(persist_directory=persist_directory, embedding_function=embeddings, client_settings=CHROMA_SETTINGS)
149
+ collection = db.get()
150
+ texts = process_documents([metadata['source'] for metadata in collection['metadatas']])
151
+ print(f"Creating embeddings. May take some minutes...")
152
+ db.add_documents(texts)
153
+ else:
154
+ # Create and store locally vectorstore
155
+ print("Creating new vectorstore")
156
+ texts = process_documents()
157
+ print(f"Creating embeddings. May take some minutes...")
158
+ db = Chroma.from_documents(texts, embeddings, persist_directory=persist_directory, client_settings=CHROMA_SETTINGS)
159
+ db.persist()
160
+ db = None
161
+
162
+ print(f"Ingestion complete! You can now run privateGPT.py to query your documents")
163
+
164
+
165
+ if __name__ == "__main__":
166
+ main()
privateGPT.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from dotenv import load_dotenv
3
+ from langchain.chains import RetrievalQA
4
+ from langchain.embeddings import HuggingFaceEmbeddings
5
+ from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
6
+ from langchain.vectorstores import Chroma
7
+ from langchain.llms import GPT4All, LlamaCpp
8
+ import os
9
+ import argparse
10
+
11
+ load_dotenv()
12
+
13
+ embeddings_model_name = os.environ.get("EMBEDDINGS_MODEL_NAME")
14
+ persist_directory = os.environ.get('PERSIST_DIRECTORY')
15
+
16
+ model_type = os.environ.get('MODEL_TYPE')
17
+ model_path = os.environ.get('MODEL_PATH')
18
+ model_n_ctx = os.environ.get('MODEL_N_CTX')
19
+ target_source_chunks = int(os.environ.get('TARGET_SOURCE_CHUNKS',4))
20
+
21
+ from constants import CHROMA_SETTINGS
22
+
23
+ def main():
24
+ # Parse the command line arguments
25
+ args = parse_arguments()
26
+ embeddings = HuggingFaceEmbeddings(model_name=embeddings_model_name)
27
+ db = Chroma(persist_directory=persist_directory, embedding_function=embeddings, client_settings=CHROMA_SETTINGS)
28
+ retriever = db.as_retriever(search_kwargs={"k": target_source_chunks})
29
+ # activate/deactivate the streaming StdOut callback for LLMs
30
+ callbacks = [] if args.mute_stream else [StreamingStdOutCallbackHandler()]
31
+ # Prepare the LLM
32
+ match model_type:
33
+ case "LlamaCpp":
34
+ llm = LlamaCpp(model_path=model_path, n_ctx=model_n_ctx, callbacks=callbacks, verbose=False)
35
+ case "GPT4All":
36
+ llm = GPT4All(model=model_path, n_ctx=model_n_ctx, backend='gptj', callbacks=callbacks, verbose=False)
37
+ case _default:
38
+ print(f"Model {model_type} not supported!")
39
+ exit;
40
+ qa = RetrievalQA.from_chain_type(llm=llm, chain_type="stuff", retriever=retriever, return_source_documents= not args.hide_source)
41
+ # Interactive questions and answers
42
+ while True:
43
+ query = input("\nEnter a query: ")
44
+ if query == "exit":
45
+ break
46
+
47
+ # Get the answer from the chain
48
+ res = qa(query)
49
+ answer, docs = res['result'], [] if args.hide_source else res['source_documents']
50
+
51
+ # Print the result
52
+ print("\n\n> Question:")
53
+ print(query)
54
+ print("\n> Answer:")
55
+ print(answer)
56
+
57
+ # Print the relevant sources used for the answer
58
+ for document in docs:
59
+ print("\n> " + document.metadata["source"] + ":")
60
+ print(document.page_content)
61
+
62
+ def parse_arguments():
63
+ parser = argparse.ArgumentParser(description='privateGPT: Ask questions to your documents without an internet connection, '
64
+ 'using the power of LLMs.')
65
+ parser.add_argument("--hide-source", "-S", action='store_true',
66
+ help='Use this flag to disable printing of source documents used for answers.')
67
+
68
+ parser.add_argument("--mute-stream", "-M",
69
+ action='store_true',
70
+ help='Use this flag to disable the streaming StdOut callback for LLMs.')
71
+
72
+ return parser.parse_args()
73
+
74
+
75
+ if __name__ == "__main__":
76
+ main()
requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ langchain==0.0.177
2
+ gpt4all==0.2.3
3
+ chromadb==0.3.23
4
+ llama-cpp-python==0.1.50
5
+ urllib3==2.0.2
6
+ pdfminer.six==20221105
7
+ python-dotenv==1.0.0
8
+ unstructured==0.6.6
9
+ extract-msg==0.41.1
10
+ tabulate==0.9.0
11
+ pandoc==2.3
12
+ pypandoc==1.11
13
+ tqdm==4.65.0