x0x7 commited on
Commit
24f0707
1 Parent(s): ef4ef29

Adding the start of some privateGPT code

Browse files
Files changed (4) hide show
  1. app.py +11 -1
  2. constants.py +15 -0
  3. ingest.py +167 -0
  4. init.yaml +2 -0
app.py CHANGED
@@ -1,8 +1,18 @@
1
  import gradio as gr
2
  import torch
 
3
 
4
  def greet(name):
5
  return torch.cuda.is_available()
6
 
7
  iface = gr.Interface(fn=greet, inputs="text", outputs="text")
8
- iface.launch(share=False)
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
  import torch
3
+ import os
4
 
5
  def greet(name):
6
  return torch.cuda.is_available()
7
 
8
  iface = gr.Interface(fn=greet, inputs="text", outputs="text")
9
+
10
+ if 'HUGGINGFACE_SPACE_ID' in os.environ:
11
+ # Running in Hugging Face Space
12
+ gradio_share = False
13
+ else:
14
+ # Running on desktop
15
+ gradio_share = True
16
+
17
+
18
+ iface.launch(share=gradio_share)
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,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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) -> 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()[0]
90
+
91
+ raise ValueError(f"Unsupported file extension '{ext}'")
92
+
93
+
94
+ def load_documents(source_dir: str, ignored_files: List[str] = []) -> List[Document]:
95
+ """
96
+ Loads all documents from the source documents directory, ignoring specified files
97
+ """
98
+ all_files = []
99
+ for ext in LOADER_MAPPING:
100
+ all_files.extend(
101
+ glob.glob(os.path.join(source_dir, f"**/*{ext}"), recursive=True)
102
+ )
103
+ filtered_files = [file_path for file_path in all_files if file_path not in ignored_files]
104
+
105
+ with Pool(processes=os.cpu_count()) as pool:
106
+ results = []
107
+ with tqdm(total=len(filtered_files), desc='Loading new documents', ncols=80) as pbar:
108
+ for i, doc in enumerate(pool.imap_unordered(load_single_document, filtered_files)):
109
+ results.append(doc)
110
+ pbar.update()
111
+
112
+ return results
113
+
114
+ def process_documents(ignored_files: List[str] = []) -> List[Document]:
115
+ """
116
+ Load documents and split in chunks
117
+ """
118
+ print(f"Loading documents from {source_directory}")
119
+ documents = load_documents(source_directory, ignored_files)
120
+ if not documents:
121
+ print("No new documents to load")
122
+ exit(0)
123
+ print(f"Loaded {len(documents)} new documents from {source_directory}")
124
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
125
+ texts = text_splitter.split_documents(documents)
126
+ print(f"Split into {len(texts)} chunks of text (max. {chunk_size} tokens each)")
127
+ return texts
128
+
129
+ def does_vectorstore_exist(persist_directory: str) -> bool:
130
+ """
131
+ Checks if vectorstore exists
132
+ """
133
+ if os.path.exists(os.path.join(persist_directory, 'index')):
134
+ if os.path.exists(os.path.join(persist_directory, 'chroma-collections.parquet')) and os.path.exists(os.path.join(persist_directory, 'chroma-embeddings.parquet')):
135
+ list_index_files = glob.glob(os.path.join(persist_directory, 'index/*.bin'))
136
+ list_index_files += glob.glob(os.path.join(persist_directory, 'index/*.pkl'))
137
+ # At least 3 documents are needed in a working vectorstore
138
+ if len(list_index_files) > 3:
139
+ return True
140
+ return False
141
+
142
+ def main():
143
+ # Create embeddings
144
+ embeddings = HuggingFaceEmbeddings(model_name=embeddings_model_name)
145
+
146
+ if does_vectorstore_exist(persist_directory):
147
+ # Update and store locally vectorstore
148
+ print(f"Appending to existing vectorstore at {persist_directory}")
149
+ db = Chroma(persist_directory=persist_directory, embedding_function=embeddings, client_settings=CHROMA_SETTINGS)
150
+ collection = db.get()
151
+ texts = process_documents([metadata['source'] for metadata in collection['metadatas']])
152
+ print(f"Creating embeddings. May take some minutes...")
153
+ db.add_documents(texts)
154
+ else:
155
+ # Create and store locally vectorstore
156
+ print("Creating new vectorstore")
157
+ texts = process_documents()
158
+ print(f"Creating embeddings. May take some minutes...")
159
+ db = Chroma.from_documents(texts, embeddings, persist_directory=persist_directory, client_settings=CHROMA_SETTINGS)
160
+ db.persist()
161
+ db = None
162
+
163
+ print(f"Ingestion complete! You can now run privateGPT.py to query your documents")
164
+
165
+
166
+ if __name__ == "__main__":
167
+ main()
init.yaml ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ init:
2
+ - python ingest.py