RishuD7 commited on
Commit
0ca7ed3
1 Parent(s): aaa9d4d

Add application file

Browse files
Files changed (10) hide show
  1. .gitignore +172 -0
  2. LICENSE +201 -0
  3. README.md +1 -11
  4. app.py +122 -0
  5. constants.py +15 -0
  6. example.env +6 -0
  7. ingest.py +108 -0
  8. privateGPT.py +57 -0
  9. requirements.txt +15 -0
  10. streamlit_app.py +94 -0
.gitignore ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # OSX
2
+ .DS_STORE
3
+
4
+ # Models
5
+ models/
6
+
7
+ # Local Chroma db
8
+ .chroma/
9
+ db/
10
+
11
+ # Byte-compiled / optimized / DLL files
12
+ __pycache__/
13
+ *.py[cod]
14
+ *$py.class
15
+
16
+ # C extensions
17
+ *.so
18
+
19
+ # Distribution / packaging
20
+ .Python
21
+ build/
22
+ develop-eggs/
23
+ dist/
24
+ downloads/
25
+ eggs/
26
+ .eggs/
27
+ lib/
28
+ lib64/
29
+ parts/
30
+ sdist/
31
+ var/
32
+ wheels/
33
+ share/python-wheels/
34
+ *.egg-info/
35
+ .installed.cfg
36
+ *.egg
37
+ MANIFEST
38
+
39
+ # PyInstaller
40
+ # Usually these files are written by a python script from a template
41
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
42
+ *.manifest
43
+ *.spec
44
+
45
+ # Installer logs
46
+ pip-log.txt
47
+ pip-delete-this-directory.txt
48
+
49
+ # Unit test / coverage reports
50
+ htmlcov/
51
+ .tox/
52
+ .nox/
53
+ .coverage
54
+ .coverage.*
55
+ .cache
56
+ nosetests.xml
57
+ coverage.xml
58
+ *.cover
59
+ *.py,cover
60
+ .hypothesis/
61
+ .pytest_cache/
62
+ cover/
63
+
64
+ # Translations
65
+ *.mo
66
+ *.pot
67
+
68
+ # Django stuff:
69
+ *.log
70
+ local_settings.py
71
+ db.sqlite3
72
+ db.sqlite3-journal
73
+
74
+ # Flask stuff:
75
+ instance/
76
+ .webassets-cache
77
+
78
+ # Scrapy stuff:
79
+ .scrapy
80
+
81
+ # Sphinx documentation
82
+ docs/_build/
83
+
84
+ # PyBuilder
85
+ .pybuilder/
86
+ target/
87
+
88
+ # Jupyter Notebook
89
+ .ipynb_checkpoints
90
+
91
+ # IPython
92
+ profile_default/
93
+ ipython_config.py
94
+
95
+ # pyenv
96
+ # For a library or package, you might want to ignore these files since the code is
97
+ # intended to run in multiple environments; otherwise, check them in:
98
+ # .python-version
99
+
100
+ # pipenv
101
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
102
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
103
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
104
+ # install all needed dependencies.
105
+ #Pipfile.lock
106
+
107
+ # poetry
108
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
109
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
110
+ # commonly ignored for libraries.
111
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
112
+ #poetry.lock
113
+
114
+ # pdm
115
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
116
+ #pdm.lock
117
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
118
+ # in version control.
119
+ # https://pdm.fming.dev/#use-with-ide
120
+ .pdm.toml
121
+
122
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
123
+ __pypackages__/
124
+
125
+ # Celery stuff
126
+ celerybeat-schedule
127
+ celerybeat.pid
128
+
129
+ # SageMath parsed files
130
+ *.sage.py
131
+
132
+ # Environments
133
+ .env
134
+ .venv
135
+ env/
136
+ venv/
137
+ ENV/
138
+ env.bak/
139
+ venv.bak/
140
+
141
+ # Spyder project settings
142
+ .spyderproject
143
+ .spyproject
144
+
145
+ # Rope project settings
146
+ .ropeproject
147
+
148
+ # mkdocs documentation
149
+ /site
150
+
151
+ # mypy
152
+ .mypy_cache/
153
+ .dmypy.json
154
+ dmypy.json
155
+
156
+ # Pyre type checker
157
+ .pyre/
158
+
159
+ # pytype static type analyzer
160
+ .pytype/
161
+
162
+ # Cython debug symbols
163
+ cython_debug/
164
+
165
+ # PyCharm
166
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
167
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
168
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
169
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
170
+ #.idea/
171
+
172
+ .brev/
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md CHANGED
@@ -1,12 +1,2 @@
1
- ---
2
- title: Docx
3
- emoji: 🌖
4
- colorFrom: yellow
5
- colorTo: gray
6
- sdk: streamlit
7
- sdk_version: 1.21.0
8
- app_file: app.py
9
- pinned: false
10
- ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
+ # PrivateGPT App
 
 
 
 
 
 
 
 
 
2
 
 
app.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dotenv import load_dotenv
2
+ from langchain.chains import RetrievalQA
3
+ from langchain.embeddings import HuggingFaceEmbeddings
4
+ from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
5
+ from langchain.vectorstores import Chroma
6
+ import os
7
+ from fastapi import FastAPI, UploadFile, File
8
+ from typing import List, Optional
9
+ import urllib.parse
10
+ from langchain.llms import HuggingFacePipeline
11
+ from transformers import AutoTokenizer, AutoModelForCausalLM
12
+ import transformers
13
+ from torch import cuda, bfloat16
14
+
15
+
16
+
17
+ load_dotenv()
18
+
19
+ embeddings_model_name = "all-MiniLM-L6-v2"
20
+ persist_directory = "db"
21
+ model = "tiiuae/falcon-7b-instruct"
22
+
23
+
24
+ # model_type = os.environ.get('MODEL_TYPE')
25
+ # model_path = os.environ.get('MODEL_PATH')
26
+ # model_n_ctx = os.environ.get('MODEL_N_CTX')
27
+ source_directory = os.environ.get('SOURCE_DIRECTORY', 'source_documents')
28
+
29
+ from constants import CHROMA_SETTINGS
30
+
31
+ # async def test_embedding():
32
+ # # Create the folder if it doesn't exist
33
+ # os.makedirs(source_directory, exist_ok=True)
34
+ # # Create a sample.txt file in the source_documents directory
35
+ # file_path = os.path.join("source_documents", "test.txt")
36
+ # with open(file_path, "w") as file:
37
+ # file.write("This is a test.")
38
+ # # Run the ingest.py command
39
+ # os.system('python ingest.py --collection test')
40
+ # # Delete the sample.txt file
41
+ # os.remove(file_path)
42
+ # print("embeddings working")
43
+
44
+ # async def model_download():
45
+ # match model_type:
46
+ # case "LlamaCpp":
47
+ # url = "https://gpt4all.io/models/ggml-gpt4all-l13b-snoozy.bin"
48
+ # case "GPT4All":
49
+ # url = "https://gpt4all.io/models/ggml-gpt4all-j-v1.3-groovy.bin"
50
+ # folder = "models"
51
+ # parsed_url = urllib.parse.urlparse(url)
52
+ # filename = os.path.join(folder, os.path.basename(parsed_url.path))
53
+ # # Check if the file already exists
54
+ # if os.path.exists(filename):
55
+ # print("File already exists.")
56
+ # return
57
+ # # Create the folder if it doesn't exist
58
+ # os.makedirs(folder, exist_ok=True)
59
+ # # Run wget command to download the file
60
+ # os.system(f"wget {url} -O {filename}")
61
+ # global model_path
62
+ # model_path = filename
63
+ # os.environ['MODEL_PATH'] = filename
64
+ # print("model downloaded")
65
+
66
+
67
+ # Starting the app with embedding and llm download
68
+ # @app.on_event("startup")
69
+ # async def startup_event():
70
+ # await test_embedding()
71
+ # await model_download()
72
+
73
+
74
+ # # Example route
75
+ # @app.get("/")
76
+ # async def root():
77
+ # return {"message": "Hello, the APIs are now ready for your embeds and queries!"}
78
+
79
+ def embed_documents(files, collection_name: Optional[str] = None):
80
+
81
+ saved_files = []
82
+ # Save the files to the specified folder
83
+ for file in files:
84
+ print(file)
85
+ os.makedirs(source_directory, exist_ok= True)
86
+ file_path = os.path.join(source_directory, file.name)
87
+ saved_files.append(file_path)
88
+
89
+ with open(file_path, "wb") as f:
90
+ f.write(file.read())
91
+
92
+ if collection_name is None:
93
+ # Handle the case when the collection_name is not defined
94
+ collection_name = file.filename
95
+
96
+ os.system(f'python ingest.py --collection {collection_name}')
97
+
98
+ # Delete the contents of the folder
99
+ [os.remove(os.path.join(source_directory, file.name)) or os.path.join(source_directory, file.name) for file in files]
100
+
101
+ return {"message": "Files embedded successfully", "saved_files": saved_files}
102
+
103
+ def retrieve_documents(query: str, collection_name:str):
104
+ target_source_chunks = 4
105
+ mute_stream = ""
106
+ embeddings = HuggingFaceEmbeddings(model_name=embeddings_model_name)
107
+ db = Chroma(persist_directory=persist_directory,collection_name=collection_name, embedding_function=embeddings, client_settings=CHROMA_SETTINGS)
108
+ retriever = db.as_retriever(search_kwargs={"k": target_source_chunks})
109
+ # Prepare the LLM
110
+ callbacks = [] if mute_stream else [StreamingStdOutCallbackHandler()]
111
+
112
+ llm = HuggingFacePipeline.from_model_id(model_id=model, task="text-generation", device=0, model_kwargs={"temperature":0.1,"trust_remote_code": True, "max_length":100000, "top_p":0.15, "top_k":0, "repetition_penalty":1.1, "num_return_sequences":1,})
113
+
114
+ qa = RetrievalQA.from_chain_type(llm=llm, chain_type="stuff", retriever=retriever, return_source_documents=False)
115
+
116
+ # Get the answer from the chain
117
+ res = qa(query)
118
+ print(res)
119
+ answer = res['result']
120
+
121
+ st.subheader("Results")
122
+ st.text(answer)
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 = "db"
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
+ )
example.env ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ PERSIST_DIRECTORY=db
2
+ MODEL_TYPE=GPT4All
3
+ MODEL_PATH=models/ggml-gpt4all-j-v1.3-groovy.bin
4
+ EMBEDDINGS_MODEL_NAME=all-MiniLM-L6-v2
5
+ MODEL_N_CTX=1000
6
+ API_BASE_URL=http://localhost:8000
ingest.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import glob
3
+ from typing import List
4
+ from dotenv import load_dotenv
5
+ import argparse
6
+
7
+ from langchain.document_loaders import (
8
+ CSVLoader,
9
+ EverNoteLoader,
10
+ PDFMinerLoader,
11
+ TextLoader,
12
+ UnstructuredEmailLoader,
13
+ UnstructuredEPubLoader,
14
+ UnstructuredHTMLLoader,
15
+ UnstructuredMarkdownLoader,
16
+ UnstructuredODTLoader,
17
+ UnstructuredPowerPointLoader,
18
+ UnstructuredWordDocumentLoader,
19
+ )
20
+
21
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
22
+ from langchain.vectorstores import Chroma
23
+ from langchain.embeddings import HuggingFaceEmbeddings
24
+ from langchain.docstore.document import Document
25
+ from constants import CHROMA_SETTINGS
26
+
27
+
28
+ load_dotenv()
29
+
30
+ embeddings_model_name = "all-MiniLM-L6-v2"
31
+ persist_directory = "db"
32
+ model = "tiiuae/falcon-7b-instruct"
33
+ # Map file extensions to document loaders and their arguments
34
+ LOADER_MAPPING = {
35
+ ".csv": (CSVLoader, {}),
36
+ # ".docx": (Docx2txtLoader, {}),
37
+ ".docx": (UnstructuredWordDocumentLoader, {}),
38
+ ".enex": (EverNoteLoader, {}),
39
+ ".eml": (UnstructuredEmailLoader, {}),
40
+ ".epub": (UnstructuredEPubLoader, {}),
41
+ ".html": (UnstructuredHTMLLoader, {}),
42
+ ".md": (UnstructuredMarkdownLoader, {}),
43
+ ".odt": (UnstructuredODTLoader, {}),
44
+ ".pdf": (PDFMinerLoader, {}),
45
+ ".pptx": (UnstructuredPowerPointLoader, {}),
46
+ ".txt": (TextLoader, {"encoding": "utf8"}),
47
+ # Add more mappings for other file extensions and loaders as needed
48
+ }
49
+
50
+
51
+ load_dotenv()
52
+
53
+
54
+ def load_single_document(file_path: str) -> Document:
55
+ ext = "." + file_path.rsplit(".", 1)[-1]
56
+ if ext in LOADER_MAPPING:
57
+ loader_class, loader_args = LOADER_MAPPING[ext]
58
+ loader = loader_class(file_path, **loader_args)
59
+ return loader.load()[0]
60
+
61
+ raise ValueError(f"Unsupported file extension '{ext}'")
62
+
63
+
64
+ def load_documents(source_dir: str) -> List[Document]:
65
+ # Loads all documents from source documents directory
66
+ all_files = []
67
+ for ext in LOADER_MAPPING:
68
+ all_files.extend(
69
+ glob.glob(os.path.join(source_dir, f"**/*{ext}"), recursive=True)
70
+ )
71
+ return [load_single_document(file_path) for file_path in all_files]
72
+
73
+
74
+ def main(collection):
75
+ # Load environment variables
76
+ embeddings_model_name = "all-MiniLM-L6-v2"
77
+ persist_directory = "db"
78
+ model = "tiiuae/falcon-7b-instruct"
79
+ source_directory = "source_documents"
80
+ os.makedirs(source_directory, exist_ok=True)
81
+ # Load documents and split in chunks
82
+ print(f"Loading documents from {source_directory}")
83
+ chunk_size = 500
84
+ chunk_overlap = 50
85
+ documents = load_documents(source_directory)
86
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
87
+ texts = text_splitter.split_documents(documents)
88
+ print(f"Loaded {len(documents)} documents from {source_directory}")
89
+ print(f"Split into {len(texts)} chunks of text (max. {chunk_size} characters each)")
90
+
91
+ # Create embeddings
92
+ embeddings = HuggingFaceEmbeddings(model_name=embeddings_model_name)
93
+
94
+ # Create and store locally vectorstore
95
+ db = Chroma.from_documents(texts, embeddings, collection_name=collection, persist_directory=persist_directory, client_settings=CHROMA_SETTINGS)
96
+ db.persist()
97
+ db = None
98
+
99
+
100
+ if __name__ == "__main__":
101
+ # Create the argument parser
102
+ parser = argparse.ArgumentParser()
103
+ parser.add_argument("--collection", help="Saves the embedding in a collection name as specified")
104
+
105
+ # Parse the command-line arguments
106
+ args = parser.parse_args()
107
+
108
+ main(args.collection)
privateGPT.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dotenv import load_dotenv
2
+ from langchain.chains import RetrievalQA
3
+ from langchain.embeddings import HuggingFaceEmbeddings
4
+ from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
5
+ from langchain.vectorstores import Chroma
6
+ from langchain.llms import GPT4All, LlamaCpp
7
+ import os
8
+
9
+ load_dotenv()
10
+
11
+ embeddings_model_name = os.environ.get("EMBEDDINGS_MODEL_NAME")
12
+ persist_directory = os.environ.get('PERSIST_DIRECTORY')
13
+
14
+ model_type = os.environ.get('MODEL_TYPE')
15
+ model_path = os.environ.get('MODEL_PATH')
16
+ model_n_ctx = os.environ.get('MODEL_N_CTX')
17
+
18
+ from constants import CHROMA_SETTINGS
19
+
20
+ def main():
21
+ embeddings = HuggingFaceEmbeddings(model_name=embeddings_model_name)
22
+ db = Chroma(persist_directory=persist_directory, embedding_function=embeddings, client_settings=CHROMA_SETTINGS)
23
+ retriever = db.as_retriever()
24
+ # Prepare the LLM
25
+ callbacks = [StreamingStdOutCallbackHandler()]
26
+ match model_type:
27
+ case "LlamaCpp":
28
+ llm = LlamaCpp(model_path=model_path, n_ctx=model_n_ctx, callbacks=callbacks, verbose=False)
29
+ case "GPT4All":
30
+ llm = GPT4All(model=model_path, n_ctx=model_n_ctx, backend='gptj', callbacks=callbacks, verbose=False)
31
+ case _default:
32
+ print(f"Model {model_type} not supported!")
33
+ exit;
34
+ qa = RetrievalQA.from_chain_type(llm=llm, chain_type="stuff", retriever=retriever, return_source_documents=True)
35
+ # Interactive questions and answers
36
+ while True:
37
+ query = input("\nEnter a query: ")
38
+ if query == "exit":
39
+ break
40
+
41
+ # Get the answer from the chain
42
+ res = qa(query)
43
+ answer, docs = res['result'], res['source_documents']
44
+
45
+ # Print the result
46
+ print("\n\n> Question:")
47
+ print(query)
48
+ print("\n> Answer:")
49
+ print(answer)
50
+
51
+ # Print the relevant sources used for the answer
52
+ for document in docs:
53
+ print("\n> " + document.metadata["source"] + ":")
54
+ print(document.page_content)
55
+
56
+ if __name__ == "__main__":
57
+ main()
requirements.txt ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ transformers
2
+ einops
3
+ accelerate
4
+ xformers
5
+ chromadb==0.3.26
6
+ duckdb==0.8.0
7
+ pdfminer.six==20221105
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
+ langchain==0.0.177
14
+ streamlit
15
+ sentence_transformers
streamlit_app.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dotenv import load_dotenv
2
+ import os
3
+ import streamlit as st
4
+ import requests
5
+ from typing import List
6
+ import json
7
+ import socket
8
+ from urllib3.connection import HTTPConnection
9
+ from app import embed_documents, retrieve_documents
10
+
11
+ API_BASE_URL = os.environ.get("API_BASE_URL")
12
+
13
+ load_dotenv()
14
+
15
+ embeddings_model_name = "all-MiniLM-L6-v2"
16
+ persist_directory = "db"
17
+ model = "tiiuae/falcon-7b-instruct"
18
+
19
+ from constants import CHROMA_SETTINGS
20
+ import chromadb
21
+
22
+ def list_of_collections():
23
+ client = chromadb.Client(CHROMA_SETTINGS)
24
+ return (client.list_collections())
25
+
26
+ def main():
27
+ st.title("PrivateGPT App: Document Embedding and Retrieval")
28
+
29
+ # Document upload section
30
+ st.header("Document Upload")
31
+ files = st.file_uploader("Upload document", accept_multiple_files=True)
32
+ # collection_name = st.text_input("Collection Name") not working for some reason
33
+ if st.button("Embed"):
34
+ embed_documents(files, "collection_name")
35
+
36
+ # Query section
37
+ st.header("Document Retrieval")
38
+ collection_names = get_collection_names()
39
+ selected_collection = st.selectbox("Select a document", collection_names)
40
+ if selected_collection:
41
+ query = st.text_input("Query")
42
+ if st.button("Retrieve"):
43
+ retrieve_documents(query, selected_collection)
44
+
45
+ # def embed_documents(files:List[st.runtime.uploaded_file_manager.UploadedFile], collection_name:str):
46
+ # endpoint = f"{API_BASE_URL}/embed"
47
+ # files_data = [("files", file) for file in files]
48
+ # data = {"collection_name": collection_name}
49
+
50
+ # response = requests.post(endpoint, files=files_data, data=data)
51
+ # if response.status_code == 200:
52
+ # st.success("Documents embedded successfully!")
53
+ # else:
54
+ # st.error("Document embedding failed.")
55
+ # st.write(response.text)
56
+
57
+
58
+ def get_collection_names():
59
+
60
+ collections = list_of_collections()
61
+ return [collection.name for collection in collections]
62
+
63
+
64
+
65
+ # def retrieve_documents(query: str, collection_name: str):
66
+ # endpoint = f"{API_BASE_URL}/retrieve"
67
+ # data = {"query": query, "collection_name": collection_name}
68
+
69
+ # # Modify socket options for the HTTPConnection class
70
+ # HTTPConnection.default_socket_options = (
71
+ # HTTPConnection.default_socket_options + [
72
+ # (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
73
+ # (socket.SOL_TCP, socket.TCP_KEEPIDLE, 45),
74
+ # (socket.SOL_TCP, socket.TCP_KEEPINTVL, 10),
75
+ # (socket.SOL_TCP, socket.TCP_KEEPCNT, 6)
76
+ # ]
77
+ # )
78
+
79
+ # response = requests.post(endpoint, params=data)
80
+ # if response.status_code == 200:
81
+ # result = response.json()
82
+ # st.subheader("Results")
83
+ # st.text(result["results"])
84
+
85
+ # st.subheader("Documents")
86
+ # for doc in result["docs"]:
87
+ # st.text(doc)
88
+ # else:
89
+ # st.error("Failed to retrieve documents.")
90
+ # st.write(response.text)
91
+
92
+
93
+ if __name__ == "__main__":
94
+ main()