ShahzainHaider commited on
Commit
5008030
1 Parent(s): aa24af4

Upload folder using huggingface_hub

Browse files
.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
+ TARGET_SOURCE_CHUNKS=4
.gitattributes CHANGED
@@ -32,3 +32,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
32
  *.zip filter=lfs diff=lfs merge=lfs -text
33
  *.zst filter=lfs diff=lfs merge=lfs -text
34
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
32
  *.zip filter=lfs diff=lfs merge=lfs -text
33
  *.zst filter=lfs diff=lfs merge=lfs -text
34
  *tfevents* filter=lfs diff=lfs merge=lfs -text
35
+ ggml-gpt4all-j-v1.3-groovy.bin.1 filter=lfs diff=lfs merge=lfs -text
36
+ source_documents/Nahjul-Balagha.pdf filter=lfs diff=lfs merge=lfs -text
.github/ISSUE_TEMPLATE/bug_report.md ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: Bug report
3
+ about: Create a report to help us improve
4
+ title: ''
5
+ labels: bug
6
+ assignees: ''
7
+
8
+ ---
9
+
10
+ Note: if you'd like to *ask a question* or *open a discussion*, head over to the [Discussions](https://github.com/imartinez/privateGPT/discussions) section and post it there.
11
+
12
+ **Describe the bug and how to reproduce it**
13
+ A clear and concise description of what the bug is and the steps to reproduce the behavior.
14
+
15
+ **Expected behavior**
16
+ A clear and concise description of what you expected to happen.
17
+
18
+ **Environment (please complete the following information):**
19
+ - OS / hardware: [e.g. macOS 12.6 / M1]
20
+ - Python version [e.g. 3.11.3]
21
+ - Other relevant information
22
+
23
+ **Additional context**
24
+ Add any other context about the problem here.
.github/ISSUE_TEMPLATE/feature_request.md ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: Feature request
3
+ about: Suggest an idea for this project
4
+ title: ''
5
+ labels: enhancement
6
+ assignees: ''
7
+
8
+ ---
9
+
10
+ Note: if you'd like to *ask a question* or *open a discussion*, head over to the [Discussions](https://github.com/imartinez/privateGPT/discussions) section and post it there.
11
+
12
+ **Is your feature request related to a problem? Please describe.**
13
+ A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
14
+
15
+ **Describe the solution you'd like**
16
+ A clear and concise description of what you want to happen.
17
+
18
+ **Describe alternatives you've considered**
19
+ A clear and concise description of any alternative solutions or features you've considered.
20
+
21
+ **Additional context**
22
+ Add any other context or screenshots about the feature request here.
.gitignore ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # OSX
2
+ .DS_STORE
3
+
4
+ # Models
5
+ models/
6
+
7
+ # Source Documents
8
+ source_documents/*
9
+ !source_documents/state_of_the_union.txt
10
+
11
+ # Local Chroma db
12
+ .chroma/
13
+ db/
14
+
15
+ # Byte-compiled / optimized / DLL files
16
+ __pycache__/
17
+ *.py[cod]
18
+ *$py.class
19
+
20
+ # C extensions
21
+ *.so
22
+
23
+ # Distribution / packaging
24
+ .Python
25
+ build/
26
+ develop-eggs/
27
+ dist/
28
+ downloads/
29
+ eggs/
30
+ .eggs/
31
+ lib/
32
+ lib64/
33
+ parts/
34
+ sdist/
35
+ var/
36
+ wheels/
37
+ share/python-wheels/
38
+ *.egg-info/
39
+ .installed.cfg
40
+ *.egg
41
+ MANIFEST
42
+
43
+ # PyInstaller
44
+ # Usually these files are written by a python script from a template
45
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
46
+ *.manifest
47
+ *.spec
48
+
49
+ # Installer logs
50
+ pip-log.txt
51
+ pip-delete-this-directory.txt
52
+
53
+ # Unit test / coverage reports
54
+ htmlcov/
55
+ .tox/
56
+ .nox/
57
+ .coverage
58
+ .coverage.*
59
+ .cache
60
+ nosetests.xml
61
+ coverage.xml
62
+ *.cover
63
+ *.py,cover
64
+ .hypothesis/
65
+ .pytest_cache/
66
+ cover/
67
+
68
+ # Translations
69
+ *.mo
70
+ *.pot
71
+
72
+ # Django stuff:
73
+ *.log
74
+ local_settings.py
75
+ db.sqlite3
76
+ db.sqlite3-journal
77
+
78
+ # Flask stuff:
79
+ instance/
80
+ .webassets-cache
81
+
82
+ # Scrapy stuff:
83
+ .scrapy
84
+
85
+ # Sphinx documentation
86
+ docs/_build/
87
+
88
+ # PyBuilder
89
+ .pybuilder/
90
+ target/
91
+
92
+ # Jupyter Notebook
93
+ .ipynb_checkpoints
94
+
95
+ # IPython
96
+ profile_default/
97
+ ipython_config.py
98
+
99
+ # pyenv
100
+ # For a library or package, you might want to ignore these files since the code is
101
+ # intended to run in multiple environments; otherwise, check them in:
102
+ # .python-version
103
+
104
+ # pipenv
105
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
106
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
107
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
108
+ # install all needed dependencies.
109
+ #Pipfile.lock
110
+
111
+ # poetry
112
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
113
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
114
+ # commonly ignored for libraries.
115
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
116
+ #poetry.lock
117
+
118
+ # pdm
119
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
120
+ #pdm.lock
121
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
122
+ # in version control.
123
+ # https://pdm.fming.dev/#use-with-ide
124
+ .pdm.toml
125
+
126
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
127
+ __pypackages__/
128
+
129
+ # Celery stuff
130
+ celerybeat-schedule
131
+ celerybeat.pid
132
+
133
+ # SageMath parsed files
134
+ *.sage.py
135
+
136
+ # Environments
137
+ .env
138
+ .venv
139
+ env/
140
+ venv/
141
+ ENV/
142
+ env.bak/
143
+ venv.bak/
144
+
145
+ # Spyder project settings
146
+ .spyderproject
147
+ .spyproject
148
+
149
+ # Rope project settings
150
+ .ropeproject
151
+
152
+ # mkdocs documentation
153
+ /site
154
+
155
+ # mypy
156
+ .mypy_cache/
157
+ .dmypy.json
158
+ dmypy.json
159
+
160
+ # Pyre type checker
161
+ .pyre/
162
+
163
+ # pytype static type analyzer
164
+ .pytype/
165
+
166
+ # Cython debug symbols
167
+ cython_debug/
168
+
169
+ # PyCharm
170
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
171
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
172
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
173
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
174
+ #.idea/
.pre-commit-config.yaml ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ files: ^(.*\.(py|json|md|sh|yaml|cfg|txt))$
3
+ exclude: ^(\.[^/]*cache/.*|.*/_user.py|source_documents/)$
4
+ repos:
5
+ - repo: https://github.com/pre-commit/pre-commit-hooks
6
+ rev: v4.4.0
7
+ hooks:
8
+ #- id: no-commit-to-branch
9
+ # args: [--branch, main]
10
+ - id: check-yaml
11
+ args: [--unsafe]
12
+ # - id: debug-statements
13
+ - id: end-of-file-fixer
14
+ - id: trailing-whitespace
15
+ exclude-files: \.md$
16
+ - id: check-json
17
+ - id: mixed-line-ending
18
+ # - id: check-builtin-literals
19
+ # - id: check-ast
20
+ - id: check-merge-conflict
21
+ - id: check-executables-have-shebangs
22
+ - id: check-shebang-scripts-are-executable
23
+ - id: check-docstring-first
24
+ - id: fix-byte-order-marker
25
+ - id: check-case-conflict
26
+ # - id: check-toml
27
+ - repo: https://github.com/adrienverge/yamllint.git
28
+ rev: v1.29.0
29
+ hooks:
30
+ - id: yamllint
31
+ args:
32
+ - --no-warnings
33
+ - -d
34
+ - '{extends: relaxed, rules: {line-length: {max: 90}}}'
35
+ - repo: https://github.com/codespell-project/codespell
36
+ rev: v2.2.2
37
+ hooks:
38
+ - id: codespell
39
+ args:
40
+ # - --builtin=clear,rare,informal,usage,code,names,en-GB_to_en-US
41
+ - --builtin=clear,rare,informal,usage,code,names
42
+ - --ignore-words-list=hass,master
43
+ - --skip="./.*"
44
+ - --quiet-level=2
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,140 @@
1
  ---
2
  title: NehjulBalaghaGPT
3
- emoji: 🔥
4
- colorFrom: green
5
- colorTo: yellow
6
  sdk: gradio
7
  sdk_version: 3.33.1
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
  ---
2
  title: NehjulBalaghaGPT
3
+ app_file: privateGPT.py
 
 
4
  sdk: gradio
5
  sdk_version: 3.33.1
 
 
6
  ---
7
+ # privateGPT
8
+ Ask questions to your documents without an internet connection, using the power of LLMs. 100% private, no data leaves your execution environment at any point. You can ingest documents and ask questions without an internet connection!
9
 
10
+ Built with [LangChain](https://github.com/hwchase17/langchain), [GPT4All](https://github.com/nomic-ai/gpt4all), [LlamaCpp](https://github.com/ggerganov/llama.cpp), [Chroma](https://www.trychroma.com/) and [SentenceTransformers](https://www.sbert.net/).
11
+
12
+ <img width="902" alt="demo" src="https://user-images.githubusercontent.com/721666/236942256-985801c9-25b9-48ef-80be-3acbb4575164.png">
13
+
14
+ # Environment Setup
15
+ In order to set your environment up to run the code here, first install all requirements:
16
+
17
+ ```shell
18
+ pip3 install -r requirements.txt
19
+ ```
20
+
21
+ Then, download the LLM model and place it in a directory of your choice:
22
+ - LLM: default to [ggml-gpt4all-j-v1.3-groovy.bin](https://gpt4all.io/models/ggml-gpt4all-j-v1.3-groovy.bin). If you prefer a different GPT4All-J compatible model, just download it and reference it in your `.env` file.
23
+
24
+ Rename `example.env` to `.env` and edit the variables appropriately.
25
+ ```
26
+ MODEL_TYPE: supports LlamaCpp or GPT4All
27
+ PERSIST_DIRECTORY: is the folder you want your vectorstore in
28
+ MODEL_PATH: Path to your GPT4All or LlamaCpp supported LLM
29
+ MODEL_N_CTX: Maximum token limit for the LLM model
30
+ EMBEDDINGS_MODEL_NAME: SentenceTransformers embeddings model name (see https://www.sbert.net/docs/pretrained_models.html)
31
+ TARGET_SOURCE_CHUNKS: The amount of chunks (sources) that will be used to answer a question
32
+ ```
33
+
34
+ Note: because of the way `langchain` loads the `SentenceTransformers` embeddings, the first time you run the script it will require internet connection to download the embeddings model itself.
35
+
36
+ ## Test dataset
37
+ This repo uses a [state of the union transcript](https://github.com/imartinez/privateGPT/blob/main/source_documents/state_of_the_union.txt) as an example.
38
+
39
+ ## Instructions for ingesting your own dataset
40
+
41
+ Put any and all your files into the `source_documents` directory
42
+
43
+ The supported extensions are:
44
+
45
+ - `.csv`: CSV,
46
+ - `.docx`: Word Document,
47
+ - `.doc`: Word Document,
48
+ - `.enex`: EverNote,
49
+ - `.eml`: Email,
50
+ - `.epub`: EPub,
51
+ - `.html`: HTML File,
52
+ - `.md`: Markdown,
53
+ - `.msg`: Outlook Message,
54
+ - `.odt`: Open Document Text,
55
+ - `.pdf`: Portable Document Format (PDF),
56
+ - `.pptx` : PowerPoint Document,
57
+ - `.ppt` : PowerPoint Document,
58
+ - `.txt`: Text file (UTF-8),
59
+
60
+ Run the following command to ingest all the data.
61
+
62
+ ```shell
63
+ python ingest.py
64
+ ```
65
+
66
+ Output should look like this:
67
+
68
+ ```shell
69
+ Creating new vectorstore
70
+ Loading documents from source_documents
71
+ Loading new documents: 100%|██████████████████████| 1/1 [00:01<00:00, 1.73s/it]
72
+ Loaded 1 new documents from source_documents
73
+ Split into 90 chunks of text (max. 500 tokens each)
74
+ Creating embeddings. May take some minutes...
75
+ Using embedded DuckDB with persistence: data will be stored in: db
76
+ Ingestion complete! You can now run privateGPT.py to query your documents
77
+ ```
78
+
79
+ It will create a `db` folder containing the local vectorstore. Will take 20-30 seconds per document, depending on the size of the document.
80
+ You can ingest as many documents as you want, and all will be accumulated in the local embeddings database.
81
+ If you want to start from an empty database, delete the `db` folder.
82
+
83
+ Note: during the ingest process no data leaves your local environment. You could ingest without an internet connection, except for the first time you run the ingest script, when the embeddings model is downloaded.
84
+
85
+ ## Ask questions to your documents, locally!
86
+ In order to ask a question, run a command like:
87
+
88
+ ```shell
89
+ python privateGPT.py
90
+ ```
91
+
92
+ And wait for the script to require your input.
93
+
94
+ ```plaintext
95
+ > Enter a query:
96
+ ```
97
+
98
+ Hit enter. You'll need to wait 20-30 seconds (depending on your machine) while the LLM model consumes the prompt and prepares the answer. Once done, it will print the answer and the 4 sources it used as context from your documents; you can then ask another question without re-running the script, just wait for the prompt again.
99
+
100
+ Note: you could turn off your internet connection, and the script inference would still work. No data gets out of your local environment.
101
+
102
+ Type `exit` to finish the script.
103
+
104
+
105
+ ### CLI
106
+ The script also supports optional command-line arguments to modify its behavior. You can see a full list of these arguments by running the command ```python privateGPT.py --help``` in your terminal.
107
+
108
+
109
+ # How does it work?
110
+ Selecting the right local models and the power of `LangChain` you can run the entire pipeline locally, without any data leaving your environment, and with reasonable performance.
111
+
112
+ - `ingest.py` uses `LangChain` tools to parse the document and create embeddings locally using `HuggingFaceEmbeddings` (`SentenceTransformers`). It then stores the result in a local vector database using `Chroma` vector store.
113
+ - `privateGPT.py` uses a local LLM based on `GPT4All-J` or `LlamaCpp` to understand questions and create answers. The context for the answers is extracted from the local vector store using a similarity search to locate the right piece of context from the docs.
114
+ - `GPT4All-J` wrapper was introduced in LangChain 0.0.162.
115
+
116
+ # System Requirements
117
+
118
+ ## Python Version
119
+ To use this software, you must have Python 3.10 or later installed. Earlier versions of Python will not compile.
120
+
121
+ ## C++ Compiler
122
+ If you encounter an error while building a wheel during the `pip install` process, you may need to install a C++ compiler on your computer.
123
+
124
+ ### For Windows 10/11
125
+ To install a C++ compiler on Windows 10/11, follow these steps:
126
+
127
+ 1. Install Visual Studio 2022.
128
+ 2. Make sure the following components are selected:
129
+ * Universal Windows Platform development
130
+ * C++ CMake tools for Windows
131
+ 3. Download the MinGW installer from the [MinGW website](https://sourceforge.net/projects/mingw/).
132
+ 4. Run the installer and select the `gcc` component.
133
+
134
+ ## Mac Running Intel
135
+ When running a Mac with Intel hardware (not M1), you may run into _clang: error: the clang compiler does not support '-march=native'_ during pip install.
136
+
137
+ If so set your archflags during pip install. eg: _ARCHFLAGS="-arch x86_64" pip3 install -r requirements.txt_
138
+
139
+ # Disclaimer
140
+ This is a test project to validate the feasibility of a fully private solution for question answering using LLMs and Vector embeddings. It is not production ready, and it is not meant to be used in production. The models selection is not optimized for performance, but for privacy; but it is possible to use different models and vectorstores to improve performance.
__pycache__/constants.cpython-310.pyc ADDED
Binary file (406 Bytes). View file
 
__pycache__/privateGPT.cpython-310.pyc ADDED
Binary file (2.55 kB). View file
 
__pycache__/utils.cpython-310.pyc ADDED
Binary file (1.13 kB). View file
 
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
+ )
db/chroma-collections.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4e58d605b72e3b2f70ac5baee7ee82cb59e92151c24427a8cbf3af4605533157
3
+ size 557
db/chroma-embeddings.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6a3147bdcc10105514d3bc21ac1c3c92c09961d03cab9fa8cae95358489d05d4
3
+ size 19447271
db/index/id_to_uuid_5c6348bb-98af-47a3-9f6e-c7961cccd199.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3d428c9925b8af9b8673432954bc74faa74722ed1527f819e476101efd39963a
3
+ size 242233
db/index/index_5c6348bb-98af-47a3-9f6e-c7961cccd199.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:65792766e92bd503502f0fa182c0f5b79f238487a9615b1966c2d2e5b7c0bb34
3
+ size 12562808
db/index/index_metadata_5c6348bb-98af-47a3-9f6e-c7961cccd199.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ed6f59a7e023cc9a938824d05713cd026705c7faf06f906c03c36bba8b74c5fb
3
+ size 74
db/index/uuid_to_id_5c6348bb-98af-47a3-9f6e-c7961cccd199.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c728bbc42a1c02fba81783faa75576a62956866b76dd6dacc93cd62c3e2254b5
3
+ size 283177
ggml-gpt4all-j-v1.3-groovy.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3b2fd7cca97284467de0be8f638925f40cbff4c70a2e10ba1094f83bfa24d86b
3
+ size 3785248281
ggml-gpt4all-j-v1.3-groovy.bin.1 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9d1b44213428ef0ae0e31e5b4f8fb321bcc7edfebe1a55ab26a5be88e20d0807
3
+ size 117438735
ingest.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from utils import *
9
+
10
+ from langchain.document_loaders import (
11
+ CSVLoader,
12
+ EverNoteLoader,
13
+ PDFMinerLoader,
14
+ TextLoader,
15
+ UnstructuredEmailLoader,
16
+ UnstructuredEPubLoader,
17
+ UnstructuredHTMLLoader,
18
+ UnstructuredMarkdownLoader,
19
+ UnstructuredODTLoader,
20
+ UnstructuredPowerPointLoader,
21
+ UnstructuredWordDocumentLoader,
22
+ )
23
+
24
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
25
+ from langchain.vectorstores import Chroma
26
+ from langchain.embeddings import HuggingFaceEmbeddings
27
+ from langchain.docstore.document import Document
28
+ from constants import CHROMA_SETTINGS
29
+
30
+
31
+ load_dotenv()
32
+
33
+
34
+ # Load environment variables
35
+ persist_directory = os.environ.get('PERSIST_DIRECTORY')
36
+ source_directory = os.environ.get('SOURCE_DIRECTORY', 'source_documents')
37
+ embeddings_model_name = os.environ.get('EMBEDDINGS_MODEL_NAME')
38
+ chunk_size = 500
39
+ chunk_overlap = 50
40
+
41
+
42
+ # Custom document loaders
43
+ class MyElmLoader(UnstructuredEmailLoader):
44
+ """Wrapper to fallback to text/plain when default does not work"""
45
+
46
+ def load(self) -> List[Document]:
47
+ """Wrapper adding fallback for elm without html"""
48
+ try:
49
+ try:
50
+ doc = UnstructuredEmailLoader.load(self)
51
+ except ValueError as e:
52
+ if 'text/html content not found in email' in str(e):
53
+ # Try plain text
54
+ self.unstructured_kwargs["content_source"]="text/plain"
55
+ doc = UnstructuredEmailLoader.load(self)
56
+ else:
57
+ raise
58
+ except Exception as e:
59
+ # Add file_path to exception message
60
+ raise type(e)(f"{self.file_path}: {e}") from e
61
+
62
+ return doc
63
+
64
+
65
+ # Map file extensions to document loaders and their arguments
66
+ LOADER_MAPPING = {
67
+ ".csv": (CSVLoader, {}),
68
+ # ".docx": (Docx2txtLoader, {}),
69
+ ".doc": (UnstructuredWordDocumentLoader, {}),
70
+ ".docx": (UnstructuredWordDocumentLoader, {}),
71
+ ".enex": (EverNoteLoader, {}),
72
+ ".eml": (MyElmLoader, {}),
73
+ ".epub": (UnstructuredEPubLoader, {}),
74
+ ".html": (UnstructuredHTMLLoader, {}),
75
+ ".md": (UnstructuredMarkdownLoader, {}),
76
+ ".odt": (UnstructuredODTLoader, {}),
77
+ ".pdf": (PDFMinerLoader, {}),
78
+ ".ppt": (UnstructuredPowerPointLoader, {}),
79
+ ".pptx": (UnstructuredPowerPointLoader, {}),
80
+ ".txt": (TextLoader, {"encoding": "utf8"}),
81
+ # Add more mappings for other file extensions and loaders as needed
82
+ }
83
+
84
+
85
+ def load_single_document(file_path: str) -> List[Document]:
86
+ ext = "." + file_path.rsplit(".", 1)[-1]
87
+ if ext in LOADER_MAPPING:
88
+ loader_class, loader_args = LOADER_MAPPING[ext]
89
+ loader = loader_class(file_path, **loader_args)
90
+ return loader.load()
91
+
92
+ raise ValueError(f"Unsupported file extension '{ext}'")
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, docs in enumerate(pool.imap_unordered(load_single_document, filtered_files)):
109
+ results.extend(docs)
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 main():
130
+ # Create embeddings
131
+ ensure_integrity(persist_directory, True)
132
+ embeddings = HuggingFaceEmbeddings(model_name=embeddings_model_name)
133
+ db = Chroma(persist_directory=persist_directory, embedding_function=embeddings, client_settings=CHROMA_SETTINGS)
134
+ collection = db.get()
135
+ texts = process_documents([metadata['source'] for metadata in collection['metadatas']])
136
+ print(f"Creating embeddings. May take some minutes...")
137
+ db.add_documents(texts)
138
+ db.persist()
139
+ db = None
140
+
141
+ print(f"Ingestion complete! You can now run privateGPT.py to query your documents")
142
+
143
+
144
+ if __name__ == "__main__":
145
+ main()
models/ggml-gpt4all-j-v1.3-groovy.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3b2fd7cca97284467de0be8f638925f40cbff4c70a2e10ba1094f83bfa24d86b
3
+ size 3785248281
privateGPT.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from utils import *
11
+ import gradio as gr
12
+
13
+ load_dotenv()
14
+
15
+ embeddings_model_name = os.environ.get("EMBEDDINGS_MODEL_NAME")
16
+ persist_directory = os.environ.get('PERSIST_DIRECTORY')
17
+
18
+ model_type = os.environ.get('MODEL_TYPE')
19
+ model_path = os.environ.get('MODEL_PATH')
20
+ model_n_ctx = os.environ.get('MODEL_N_CTX')
21
+ target_source_chunks = int(os.environ.get('TARGET_SOURCE_CHUNKS',4))
22
+
23
+ from constants import CHROMA_SETTINGS
24
+
25
+ def main():
26
+
27
+ demo = gr.Interface(
28
+ fn=GPT,
29
+ inputs=gr.Textbox(label = "Ask your questions", lines=2, placeholder="Question?"),
30
+ outputs=gr.Textbox(lines=20, placeholder=""),
31
+ )
32
+ demo.launch(share=True)
33
+
34
+
35
+ def GPT(name):
36
+ ensure_integrity(persist_directory, False)
37
+ # Parse the command line arguments
38
+ args = parse_arguments()
39
+ embeddings = HuggingFaceEmbeddings(model_name=embeddings_model_name)
40
+ db = Chroma(persist_directory=persist_directory, embedding_function=embeddings, client_settings=CHROMA_SETTINGS)
41
+ retriever = db.as_retriever(search_kwargs={"k": target_source_chunks})
42
+ # activate/deactivate the streaming StdOut callback for LLMs
43
+ callbacks = [] if args.mute_stream else [StreamingStdOutCallbackHandler()]
44
+ # Prepare the LLM
45
+ match model_type:
46
+ case "LlamaCpp":
47
+ llm = LlamaCpp(model_path=model_path, n_ctx=model_n_ctx, callbacks=callbacks, verbose=False)
48
+ case "GPT4All":
49
+ llm = GPT4All(model=model_path, n_ctx=model_n_ctx, backend='gptj', callbacks=callbacks, verbose=False)
50
+ case _default:
51
+ print(f"Model {model_type} not supported!")
52
+ exit;
53
+ qa = RetrievalQA.from_chain_type(llm=llm, chain_type="stuff", retriever=retriever, return_source_documents= not args.hide_source)
54
+ # Interactive questions and answers
55
+ while True:
56
+ query = name
57
+ print(query)
58
+ # query = input("\nEnter a query: ")
59
+ if query == "exit":
60
+ break
61
+
62
+ # Get the answer from the chain
63
+ res = qa(query)
64
+ answer, docs = res['result'], [] if args.hide_source else res['source_documents']
65
+
66
+ # Print the result
67
+ print("\n\n> Question:")
68
+ print(query)
69
+ print("\n> Answer:")
70
+ print(answer)
71
+
72
+ # Print the relevant sources used for the answer
73
+ for document in docs:
74
+ print("\n> " + document.metadata["source"] + ":")
75
+ print(document.page_content)
76
+
77
+ return answer
78
+
79
+ def parse_arguments():
80
+ parser = argparse.ArgumentParser(description='privateGPT: Ask questions to your documents without an internet connection, '
81
+ 'using the power of LLMs.')
82
+ parser.add_argument("--hide-source", "-S", action='store_true',
83
+ help='Use this flag to disable printing of source documents used for answers.')
84
+
85
+ parser.add_argument("--mute-stream", "-M",
86
+ action='store_true',
87
+ help='Use this flag to disable the streaming StdOut callback for LLMs.')
88
+
89
+ return parser.parse_args()
90
+
91
+
92
+ if __name__ == "__main__":
93
+ 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
source_documents/Nahjul-Balagha.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:26150eaff546bba9d45acb98b057fa4be1b4ec2b0eb5fed555131398f18289a0
3
+ size 3167124
utils.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import glob
3
+
4
+ def ensure_integrity(persist_directory: str, is_caller_ingest: bool) -> None:
5
+ """
6
+ Checks if vectorstore exists, and if it does, if it is valid
7
+ """
8
+ if not os.path.exists(os.path.join(persist_directory, 'index')) and not is_caller_ingest:
9
+ print("No vectorstore found. Please run ingest.py first.")
10
+ exit(1)
11
+ list_index_files = glob.glob(os.path.join(persist_directory, 'index/*.bin'))
12
+ list_index_files += glob.glob(os.path.join(persist_directory, 'index/*.pkl'))
13
+ if os.path.exists(os.path.join(persist_directory, 'index')) and (not os.path.exists(os.path.join(persist_directory, 'chroma-collections.parquet')) or not os.path.exists(os.path.join(persist_directory, 'chroma-embeddings.parquet')) or not len(list_index_files) > 3):
14
+ print(f"Current vectorstore is not valid. Aborting.")
15
+ print(f"If you deleted any files in the '{persist_directory}' folder, please restore them (if possible) and run privateGPT.py again.")
16
+ print("If you want to start from scratch, delete the '{persist_directory}' folder and its contents and run ingest.py again.")
17
+ exit(1)