Chng Siong Huat commited on
Commit
939a909
1 Parent(s): 160c677

Initial Commit

Browse files
ConversaDocs_Colab.ipynb ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {
6
+ "colab_type": "text",
7
+ "id": "view-in-github"
8
+ },
9
+ "source": [
10
+ "<a href=\"https://colab.research.google.com/github/R3gm/ConversaDocs/blob/main/ConversaDocs_Colab.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
11
+ ]
12
+ },
13
+ {
14
+ "cell_type": "markdown",
15
+ "metadata": {
16
+ "id": "EnzlcRZycXnr"
17
+ },
18
+ "source": [
19
+ "# ConversaDocs\n",
20
+ "\n",
21
+ "`Chat with your documents using Llama 2, Falcon or OpenAI`\n",
22
+ "\n",
23
+ "- You can upload multiple documents at once to a single database.\n",
24
+ "- Every time a new database is created, the previous one is deleted.\n",
25
+ "- For maximum privacy, you can click \"Load LLAMA GGUF Model\" to use a Llama 2 model. By default, the model llama-2_7B-Chat is loaded.\n",
26
+ "\n",
27
+ "Program that enables seamless interaction with your documents through an advanced vector database and the power of Large Language Model (LLM) technology.\n",
28
+ "\n",
29
+ "| Description | Link |\n",
30
+ "| ----------- | ---- |\n",
31
+ "| 📙 Colab Notebook | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/R3gm/ConversaDocs/blob/main/ConversaDocs_Colab.ipynb) |\n",
32
+ "| 🎉 Repository | [![GitHub Repository](https://img.shields.io/badge/GitHub-Repository-black?style=flat-square&logo=github)](https://github.com/R3gm/ConversaDocs/) |\n",
33
+ "| 🚀 Online Demo | [![Hugging Face Spaces](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue)](https://huggingface.co/spaces/r3gm/ConversaDocs) |\n",
34
+ "\n"
35
+ ]
36
+ },
37
+ {
38
+ "cell_type": "code",
39
+ "execution_count": null,
40
+ "metadata": {
41
+ "id": "S5awiNy-A50W"
42
+ },
43
+ "outputs": [],
44
+ "source": [
45
+ "!git clone https://github.com/R3gm/ConversaDocs.git\n",
46
+ "%cd ConversaDocs\n",
47
+ "!pip install -r requirements.txt"
48
+ ]
49
+ },
50
+ {
51
+ "cell_type": "markdown",
52
+ "metadata": {
53
+ "id": "_EShTkcgAOWa"
54
+ },
55
+ "source": [
56
+ "Install llama-cpp-python, whether for use on a GPU or solely on a CPU."
57
+ ]
58
+ },
59
+ {
60
+ "cell_type": "code",
61
+ "execution_count": 1,
62
+ "metadata": {
63
+ "id": "fyPLgbJW95ah"
64
+ },
65
+ "outputs": [
66
+ {
67
+ "name": "stdout",
68
+ "output_type": "stream",
69
+ "text": [
70
+ "CUDA is not available on this system.\n"
71
+ ]
72
+ }
73
+ ],
74
+ "source": [
75
+ "import torch\n",
76
+ "import os\n",
77
+ "if torch.cuda.is_available():\n",
78
+ " print(\"CUDA is available on this system.\")\n",
79
+ " os.system('CMAKE_ARGS=\"-DLLAMA_CUBLAS=on\" FORCE_CMAKE=1 pip install llama-cpp-python==0.1.78 --force-reinstall --upgrade --no-cache-dir --verbose')\n",
80
+ "else:\n",
81
+ " print(\"CUDA is not available on this system.\")\n",
82
+ " os.system('pip install llama-cpp-python==0.1.78')"
83
+ ]
84
+ },
85
+ {
86
+ "cell_type": "markdown",
87
+ "metadata": {
88
+ "id": "jLfxiOyMEcGF"
89
+ },
90
+ "source": [
91
+ "`RESTART THE RUNTIME` before executing the next cell."
92
+ ]
93
+ },
94
+ {
95
+ "cell_type": "code",
96
+ "execution_count": 2,
97
+ "metadata": {
98
+ "id": "2F2VGAJtEbb3"
99
+ },
100
+ "outputs": [
101
+ {
102
+ "name": "stdout",
103
+ "output_type": "stream",
104
+ "text": [
105
+ "[WinError 3] The system cannot find the path specified: '/content/ConversaDocs'\n",
106
+ "C:\\Users\\Siong Huat\\Project\\ConversaDocs\n"
107
+ ]
108
+ },
109
+ {
110
+ "name": "stderr",
111
+ "output_type": "stream",
112
+ "text": [
113
+ "Traceback (most recent call last):\n",
114
+ " File \"app.py\", line 13, in <module>\n",
115
+ " import gradio as gr\n",
116
+ "ModuleNotFoundError: No module named 'gradio'\n"
117
+ ]
118
+ }
119
+ ],
120
+ "source": [
121
+ "# RUN APP\n",
122
+ "%cd /content/ConversaDocs\n",
123
+ "!python app.py"
124
+ ]
125
+ },
126
+ {
127
+ "cell_type": "markdown",
128
+ "metadata": {
129
+ "id": "3aEEcmchZIlf"
130
+ },
131
+ "source": [
132
+ "Open the `public URL` when it appears"
133
+ ]
134
+ }
135
+ ],
136
+ "metadata": {
137
+ "accelerator": "GPU",
138
+ "colab": {
139
+ "gpuType": "T4",
140
+ "include_colab_link": true,
141
+ "provenance": [],
142
+ "toc_visible": true
143
+ },
144
+ "kernelspec": {
145
+ "display_name": "Python 3 (ipykernel)",
146
+ "language": "python",
147
+ "name": "python3"
148
+ },
149
+ "language_info": {
150
+ "codemirror_mode": {
151
+ "name": "ipython",
152
+ "version": 3
153
+ },
154
+ "file_extension": ".py",
155
+ "mimetype": "text/x-python",
156
+ "name": "python",
157
+ "nbconvert_exporter": "python",
158
+ "pygments_lexer": "ipython3",
159
+ "version": "3.8.18"
160
+ }
161
+ },
162
+ "nbformat": 4,
163
+ "nbformat_minor": 1
164
+ }
LICENSE ADDED
@@ -0,0 +1,543 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <<<<<<< HEAD
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
203
+ =======
204
+ GNU GENERAL PUBLIC LICENSE
205
+ Version 2, June 1991
206
+
207
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
208
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
209
+ Everyone is permitted to copy and distribute verbatim copies
210
+ of this license document, but changing it is not allowed.
211
+
212
+ Preamble
213
+
214
+ The licenses for most software are designed to take away your
215
+ freedom to share and change it. By contrast, the GNU General Public
216
+ License is intended to guarantee your freedom to share and change free
217
+ software--to make sure the software is free for all its users. This
218
+ General Public License applies to most of the Free Software
219
+ Foundation's software and to any other program whose authors commit to
220
+ using it. (Some other Free Software Foundation software is covered by
221
+ the GNU Lesser General Public License instead.) You can apply it to
222
+ your programs, too.
223
+
224
+ When we speak of free software, we are referring to freedom, not
225
+ price. Our General Public Licenses are designed to make sure that you
226
+ have the freedom to distribute copies of free software (and charge for
227
+ this service if you wish), that you receive source code or can get it
228
+ if you want it, that you can change the software or use pieces of it
229
+ in new free programs; and that you know you can do these things.
230
+
231
+ To protect your rights, we need to make restrictions that forbid
232
+ anyone to deny you these rights or to ask you to surrender the rights.
233
+ These restrictions translate to certain responsibilities for you if you
234
+ distribute copies of the software, or if you modify it.
235
+
236
+ For example, if you distribute copies of such a program, whether
237
+ gratis or for a fee, you must give the recipients all the rights that
238
+ you have. You must make sure that they, too, receive or can get the
239
+ source code. And you must show them these terms so they know their
240
+ rights.
241
+
242
+ We protect your rights with two steps: (1) copyright the software, and
243
+ (2) offer you this license which gives you legal permission to copy,
244
+ distribute and/or modify the software.
245
+
246
+ Also, for each author's protection and ours, we want to make certain
247
+ that everyone understands that there is no warranty for this free
248
+ software. If the software is modified by someone else and passed on, we
249
+ want its recipients to know that what they have is not the original, so
250
+ that any problems introduced by others will not reflect on the original
251
+ authors' reputations.
252
+
253
+ Finally, any free program is threatened constantly by software
254
+ patents. We wish to avoid the danger that redistributors of a free
255
+ program will individually obtain patent licenses, in effect making the
256
+ program proprietary. To prevent this, we have made it clear that any
257
+ patent must be licensed for everyone's free use or not licensed at all.
258
+
259
+ The precise terms and conditions for copying, distribution and
260
+ modification follow.
261
+
262
+ GNU GENERAL PUBLIC LICENSE
263
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
264
+
265
+ 0. This License applies to any program or other work which contains
266
+ a notice placed by the copyright holder saying it may be distributed
267
+ under the terms of this General Public License. The "Program", below,
268
+ refers to any such program or work, and a "work based on the Program"
269
+ means either the Program or any derivative work under copyright law:
270
+ that is to say, a work containing the Program or a portion of it,
271
+ either verbatim or with modifications and/or translated into another
272
+ language. (Hereinafter, translation is included without limitation in
273
+ the term "modification".) Each licensee is addressed as "you".
274
+
275
+ Activities other than copying, distribution and modification are not
276
+ covered by this License; they are outside its scope. The act of
277
+ running the Program is not restricted, and the output from the Program
278
+ is covered only if its contents constitute a work based on the
279
+ Program (independent of having been made by running the Program).
280
+ Whether that is true depends on what the Program does.
281
+
282
+ 1. You may copy and distribute verbatim copies of the Program's
283
+ source code as you receive it, in any medium, provided that you
284
+ conspicuously and appropriately publish on each copy an appropriate
285
+ copyright notice and disclaimer of warranty; keep intact all the
286
+ notices that refer to this License and to the absence of any warranty;
287
+ and give any other recipients of the Program a copy of this License
288
+ along with the Program.
289
+
290
+ You may charge a fee for the physical act of transferring a copy, and
291
+ you may at your option offer warranty protection in exchange for a fee.
292
+
293
+ 2. You may modify your copy or copies of the Program or any portion
294
+ of it, thus forming a work based on the Program, and copy and
295
+ distribute such modifications or work under the terms of Section 1
296
+ above, provided that you also meet all of these conditions:
297
+
298
+ a) You must cause the modified files to carry prominent notices
299
+ stating that you changed the files and the date of any change.
300
+
301
+ b) You must cause any work that you distribute or publish, that in
302
+ whole or in part contains or is derived from the Program or any
303
+ part thereof, to be licensed as a whole at no charge to all third
304
+ parties under the terms of this License.
305
+
306
+ c) If the modified program normally reads commands interactively
307
+ when run, you must cause it, when started running for such
308
+ interactive use in the most ordinary way, to print or display an
309
+ announcement including an appropriate copyright notice and a
310
+ notice that there is no warranty (or else, saying that you provide
311
+ a warranty) and that users may redistribute the program under
312
+ these conditions, and telling the user how to view a copy of this
313
+ License. (Exception: if the Program itself is interactive but
314
+ does not normally print such an announcement, your work based on
315
+ the Program is not required to print an announcement.)
316
+
317
+ These requirements apply to the modified work as a whole. If
318
+ identifiable sections of that work are not derived from the Program,
319
+ and can be reasonably considered independent and separate works in
320
+ themselves, then this License, and its terms, do not apply to those
321
+ sections when you distribute them as separate works. But when you
322
+ distribute the same sections as part of a whole which is a work based
323
+ on the Program, the distribution of the whole must be on the terms of
324
+ this License, whose permissions for other licensees extend to the
325
+ entire whole, and thus to each and every part regardless of who wrote it.
326
+
327
+ Thus, it is not the intent of this section to claim rights or contest
328
+ your rights to work written entirely by you; rather, the intent is to
329
+ exercise the right to control the distribution of derivative or
330
+ collective works based on the Program.
331
+
332
+ In addition, mere aggregation of another work not based on the Program
333
+ with the Program (or with a work based on the Program) on a volume of
334
+ a storage or distribution medium does not bring the other work under
335
+ the scope of this License.
336
+
337
+ 3. You may copy and distribute the Program (or a work based on it,
338
+ under Section 2) in object code or executable form under the terms of
339
+ Sections 1 and 2 above provided that you also do one of the following:
340
+
341
+ a) Accompany it with the complete corresponding machine-readable
342
+ source code, which must be distributed under the terms of Sections
343
+ 1 and 2 above on a medium customarily used for software interchange; or,
344
+
345
+ b) Accompany it with a written offer, valid for at least three
346
+ years, to give any third party, for a charge no more than your
347
+ cost of physically performing source distribution, a complete
348
+ machine-readable copy of the corresponding source code, to be
349
+ distributed under the terms of Sections 1 and 2 above on a medium
350
+ customarily used for software interchange; or,
351
+
352
+ c) Accompany it with the information you received as to the offer
353
+ to distribute corresponding source code. (This alternative is
354
+ allowed only for noncommercial distribution and only if you
355
+ received the program in object code or executable form with such
356
+ an offer, in accord with Subsection b above.)
357
+
358
+ The source code for a work means the preferred form of the work for
359
+ making modifications to it. For an executable work, complete source
360
+ code means all the source code for all modules it contains, plus any
361
+ associated interface definition files, plus the scripts used to
362
+ control compilation and installation of the executable. However, as a
363
+ special exception, the source code distributed need not include
364
+ anything that is normally distributed (in either source or binary
365
+ form) with the major components (compiler, kernel, and so on) of the
366
+ operating system on which the executable runs, unless that component
367
+ itself accompanies the executable.
368
+
369
+ If distribution of executable or object code is made by offering
370
+ access to copy from a designated place, then offering equivalent
371
+ access to copy the source code from the same place counts as
372
+ distribution of the source code, even though third parties are not
373
+ compelled to copy the source along with the object code.
374
+
375
+ 4. You may not copy, modify, sublicense, or distribute the Program
376
+ except as expressly provided under this License. Any attempt
377
+ otherwise to copy, modify, sublicense or distribute the Program is
378
+ void, and will automatically terminate your rights under this License.
379
+ However, parties who have received copies, or rights, from you under
380
+ this License will not have their licenses terminated so long as such
381
+ parties remain in full compliance.
382
+
383
+ 5. You are not required to accept this License, since you have not
384
+ signed it. However, nothing else grants you permission to modify or
385
+ distribute the Program or its derivative works. These actions are
386
+ prohibited by law if you do not accept this License. Therefore, by
387
+ modifying or distributing the Program (or any work based on the
388
+ Program), you indicate your acceptance of this License to do so, and
389
+ all its terms and conditions for copying, distributing or modifying
390
+ the Program or works based on it.
391
+
392
+ 6. Each time you redistribute the Program (or any work based on the
393
+ Program), the recipient automatically receives a license from the
394
+ original licensor to copy, distribute or modify the Program subject to
395
+ these terms and conditions. You may not impose any further
396
+ restrictions on the recipients' exercise of the rights granted herein.
397
+ You are not responsible for enforcing compliance by third parties to
398
+ this License.
399
+
400
+ 7. If, as a consequence of a court judgment or allegation of patent
401
+ infringement or for any other reason (not limited to patent issues),
402
+ conditions are imposed on you (whether by court order, agreement or
403
+ otherwise) that contradict the conditions of this License, they do not
404
+ excuse you from the conditions of this License. If you cannot
405
+ distribute so as to satisfy simultaneously your obligations under this
406
+ License and any other pertinent obligations, then as a consequence you
407
+ may not distribute the Program at all. For example, if a patent
408
+ license would not permit royalty-free redistribution of the Program by
409
+ all those who receive copies directly or indirectly through you, then
410
+ the only way you could satisfy both it and this License would be to
411
+ refrain entirely from distribution of the Program.
412
+
413
+ If any portion of this section is held invalid or unenforceable under
414
+ any particular circumstance, the balance of the section is intended to
415
+ apply and the section as a whole is intended to apply in other
416
+ circumstances.
417
+
418
+ It is not the purpose of this section to induce you to infringe any
419
+ patents or other property right claims or to contest validity of any
420
+ such claims; this section has the sole purpose of protecting the
421
+ integrity of the free software distribution system, which is
422
+ implemented by public license practices. Many people have made
423
+ generous contributions to the wide range of software distributed
424
+ through that system in reliance on consistent application of that
425
+ system; it is up to the author/donor to decide if he or she is willing
426
+ to distribute software through any other system and a licensee cannot
427
+ impose that choice.
428
+
429
+ This section is intended to make thoroughly clear what is believed to
430
+ be a consequence of the rest of this License.
431
+
432
+ 8. If the distribution and/or use of the Program is restricted in
433
+ certain countries either by patents or by copyrighted interfaces, the
434
+ original copyright holder who places the Program under this License
435
+ may add an explicit geographical distribution limitation excluding
436
+ those countries, so that distribution is permitted only in or among
437
+ countries not thus excluded. In such case, this License incorporates
438
+ the limitation as if written in the body of this License.
439
+
440
+ 9. The Free Software Foundation may publish revised and/or new versions
441
+ of the General Public License from time to time. Such new versions will
442
+ be similar in spirit to the present version, but may differ in detail to
443
+ address new problems or concerns.
444
+
445
+ Each version is given a distinguishing version number. If the Program
446
+ specifies a version number of this License which applies to it and "any
447
+ later version", you have the option of following the terms and conditions
448
+ either of that version or of any later version published by the Free
449
+ Software Foundation. If the Program does not specify a version number of
450
+ this License, you may choose any version ever published by the Free Software
451
+ Foundation.
452
+
453
+ 10. If you wish to incorporate parts of the Program into other free
454
+ programs whose distribution conditions are different, write to the author
455
+ to ask for permission. For software which is copyrighted by the Free
456
+ Software Foundation, write to the Free Software Foundation; we sometimes
457
+ make exceptions for this. Our decision will be guided by the two goals
458
+ of preserving the free status of all derivatives of our free software and
459
+ of promoting the sharing and reuse of software generally.
460
+
461
+ NO WARRANTY
462
+
463
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
464
+ FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
465
+ OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
466
+ PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
467
+ OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
468
+ MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
469
+ TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
470
+ PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
471
+ REPAIR OR CORRECTION.
472
+
473
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
474
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
475
+ REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
476
+ INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
477
+ OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
478
+ TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
479
+ YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
480
+ PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
481
+ POSSIBILITY OF SUCH DAMAGES.
482
+
483
+ END OF TERMS AND CONDITIONS
484
+
485
+ How to Apply These Terms to Your New Programs
486
+
487
+ If you develop a new program, and you want it to be of the greatest
488
+ possible use to the public, the best way to achieve this is to make it
489
+ free software which everyone can redistribute and change under these terms.
490
+
491
+ To do so, attach the following notices to the program. It is safest
492
+ to attach them to the start of each source file to most effectively
493
+ convey the exclusion of warranty; and each file should have at least
494
+ the "copyright" line and a pointer to where the full notice is found.
495
+
496
+ <one line to give the program's name and a brief idea of what it does.>
497
+ Copyright (C) <year> <name of author>
498
+
499
+ This program is free software; you can redistribute it and/or modify
500
+ it under the terms of the GNU General Public License as published by
501
+ the Free Software Foundation; either version 2 of the License, or
502
+ (at your option) any later version.
503
+
504
+ This program is distributed in the hope that it will be useful,
505
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
506
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
507
+ GNU General Public License for more details.
508
+
509
+ You should have received a copy of the GNU General Public License along
510
+ with this program; if not, write to the Free Software Foundation, Inc.,
511
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
512
+
513
+ Also add information on how to contact you by electronic and paper mail.
514
+
515
+ If the program is interactive, make it output a short notice like this
516
+ when it starts in an interactive mode:
517
+
518
+ Gnomovision version 69, Copyright (C) year name of author
519
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
520
+ This is free software, and you are welcome to redistribute it
521
+ under certain conditions; type `show c' for details.
522
+
523
+ The hypothetical commands `show w' and `show c' should show the appropriate
524
+ parts of the General Public License. Of course, the commands you use may
525
+ be called something other than `show w' and `show c'; they could even be
526
+ mouse-clicks or menu items--whatever suits your program.
527
+
528
+ You should also get your employer (if you work as a programmer) or your
529
+ school, if any, to sign a "copyright disclaimer" for the program, if
530
+ necessary. Here is a sample; alter the names:
531
+
532
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
533
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
534
+
535
+ <signature of Ty Coon>, 1 April 1989
536
+ Ty Coon, President of Vice
537
+
538
+ This General Public License does not permit incorporating your program into
539
+ proprietary programs. If your program is a subroutine library, you may
540
+ consider it more useful to permit linking proprietary applications with the
541
+ library. If this is what you want to do, use the GNU Lesser General
542
+ Public License instead of this License.
543
+ >>>>>>> 33954e5 (Initial commit)
app.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import os
3
+ try:
4
+ from llama_cpp import Llama
5
+ except:
6
+ if torch.cuda.is_available():
7
+ print("CUDA is available on this system.")
8
+ os.system('CMAKE_ARGS="-DLLAMA_CUBLAS=on" FORCE_CMAKE=1 pip install llama-cpp-python --force-reinstall --upgrade --no-cache-dir --verbose')
9
+ else:
10
+ print("CUDA is not available on this system.")
11
+ os.system('pip install llama-cpp-python')
12
+
13
+ import gradio as gr
14
+ from langchain.embeddings.openai import OpenAIEmbeddings
15
+ from langchain.text_splitter import CharacterTextSplitter, RecursiveCharacterTextSplitter
16
+ from langchain.vectorstores import DocArrayInMemorySearch
17
+ from langchain.chains import RetrievalQA, ConversationalRetrievalChain
18
+ from langchain.memory import ConversationBufferMemory
19
+ from langchain.chat_models import ChatOpenAI
20
+ from langchain.embeddings import HuggingFaceEmbeddings
21
+ from langchain import HuggingFaceHub
22
+ from langchain.llms import LlamaCpp
23
+ from huggingface_hub import hf_hub_download
24
+ from langchain.document_loaders import (
25
+ EverNoteLoader,
26
+ TextLoader,
27
+ UnstructuredEPubLoader,
28
+ UnstructuredHTMLLoader,
29
+ UnstructuredMarkdownLoader,
30
+ UnstructuredODTLoader,
31
+ UnstructuredPowerPointLoader,
32
+ UnstructuredWordDocumentLoader,
33
+ PyPDFLoader,
34
+ )
35
+ import param
36
+ from conversadocs.bones import DocChat
37
+ dc = DocChat()
38
+ ##### GRADIO CONFIG ####
39
+
40
+ css="""
41
+ #col-container {max-width: 1500px; margin-left: auto; margin-right: auto;}
42
+ """
43
+
44
+ title = """
45
+ <div style="text-align: center;max-width: 1500px;">
46
+ <h2>Augmented Analytic 📚 </h2>
47
+ <p style="text-align: center;">Upload log, txt, pdf, doc, docx, enex, epub, html, md, odt, ptt and pttx.<br /></p>
48
+ </div>
49
+ """
50
+
51
+ description = """
52
+ # Application Information
53
+
54
+ - Notebook for run ConversaDocs in Colab [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/R3gm/ConversaDocs/blob/main/ConversaDocs_Colab.ipynb)
55
+
56
+ - Oficial Repository [![a](https://img.shields.io/badge/GitHub-Repository-black?style=flat-square&logo=github)](https://github.com/R3gm/ConversaDocs/)
57
+
58
+ - You can upload multiple documents at once to a single database.
59
+
60
+ - Every time a new database is created, the previous one is deleted.
61
+
62
+ - For maximum privacy, you can click "Load LLAMA GGUF Model" to use a Llama 2 model. By default, the model llama-2_7B-Chat is loaded.
63
+
64
+ - This application works on both CPU and GPU. For fast inference with GGUF models, use the GPU.
65
+
66
+ - For more information about what GGUF models are, you can visit this notebook [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/R3gm/InsightSolver-Colab/blob/main/LLM_Inference_with_llama_cpp_python__Llama_2_13b_chat.ipynb)
67
+
68
+ ## 📖 News
69
+
70
+ 🔥 2023/07/24: Document summarization was added.
71
+
72
+ 🔥 2023/07/29: Error with llama 70B was fixed.
73
+
74
+ 🔥 2023/08/07: ♟️ Chessboard was added for playing with a LLM.
75
+
76
+
77
+ """
78
+
79
+ theme='aliabid94/new-theme'
80
+
81
+ def flag():
82
+ return "PROCESSING..."
83
+
84
+ def upload_file(files, max_docs):
85
+ file_paths = [file.name for file in files]
86
+ return dc.call_load_db(file_paths, max_docs)
87
+
88
+ def predict(message, chat_history, max_k, check_memory):
89
+ print(message)
90
+ bot_message = dc.convchain(message, max_k, check_memory)
91
+ print(bot_message)
92
+ return "", dc.get_chats()
93
+
94
+ def convert():
95
+ docs = dc.get_sources()
96
+ data_docs = ""
97
+ for i in range(0,len(docs),2):
98
+ txt = docs[i][1].replace("\n","<br>")
99
+ sc = "Archive: " + docs[i+1][1]["source"]
100
+ try:
101
+ pg = "Page: " + str(docs[i+1][1]["page"])
102
+ except:
103
+ pg = "Document Data"
104
+ data_docs += f"<hr><h3 style='color:red;'>{pg}</h2><p>{txt}</p><p>{sc}</p>"
105
+ return data_docs
106
+
107
+ def clear_api_key(api_key):
108
+ return 'api_key...', dc.openai_model(api_key)
109
+
110
+ # Max values in generation
111
+ DOC_DB_LIMIT = 20
112
+ MAX_NEW_TOKENS = 32000
113
+ REPO = "TheBloke/Mistral-7B-OpenOrca-GGUF"
114
+ MODEL = "mistral-7b-openorca.Q4_K_M.gguf"
115
+ # Limit in HF, no need to set it
116
+ if "SET_LIMIT" == os.getenv("DEMO"):
117
+ DOC_DB_LIMIT = 4
118
+ MAX_NEW_TOKENS = 32
119
+
120
+ with gr.Blocks(theme=theme, css=css) as demo:
121
+ with gr.Tab("Chat"):
122
+
123
+ with gr.Column():
124
+ gr.HTML(title)
125
+ upload_button = gr.UploadButton("Click to Upload Files", file_count="multiple")
126
+ file_output = gr.HTML()
127
+
128
+ chatbot = gr.Chatbot([], elem_id="chatbot") #.style(height=300)
129
+ msg = gr.Textbox(label="Question", placeholder="Type your question and hit Enter ")
130
+ with gr.Row():
131
+ check_memory = gr.inputs.Checkbox(label="Remember previous messages")
132
+ clear_button = gr.Button("CLEAR CHAT HISTORY", )
133
+ max_docs = gr.inputs.Slider(1, DOC_DB_LIMIT, default=3, label="Maximum querys to the DB.", step=1)
134
+
135
+ with gr.Column():
136
+ link_output = gr.HTML("")
137
+ sou = gr.HTML("")
138
+
139
+ clear_button.click(flag,[],[link_output]).then(dc.clr_history,[], [link_output]).then(lambda: None, None, chatbot, queue=False)
140
+ upload_button.upload(flag,[],[file_output]).then(upload_file, [upload_button, max_docs], file_output).then(dc.clr_history,[], [link_output])
141
+
142
+ with gr.Tab("Experimental Summarization"):
143
+ default_model = gr.HTML("<hr>From DB<br>It may take approximately 5 minutes to complete 15 pages in GPU. Please use files with fewer pages if you want to use summarization.<br></h2>")
144
+ summarize_button = gr.Button("Start summarization")
145
+
146
+ summarize_verify = gr.HTML(" ")
147
+ summarize_button.click(dc.summarize, [], [summarize_verify])
148
+
149
+ with gr.Tab("Config llama-2 model"):
150
+ gr.HTML("<h3>Only models from the GGUF library are accepted. To apply the new configurations, please reload the model.</h3>")
151
+ repo_ = gr.Textbox(label="Repository" ,value=REPO)
152
+ file_ = gr.Textbox(label="File name" ,value=MODEL)
153
+ max_tokens = gr.inputs.Slider(1, MAX_NEW_TOKENS, default=256, label="Max new tokens", step=1)
154
+ temperature = gr.inputs.Slider(0.1, 1., default=0.2, label="Temperature", step=0.1)
155
+ top_k = gr.inputs.Slider(0.01, 1., default=0.95, label="Top K", step=0.01)
156
+ top_p = gr.inputs.Slider(0, 100, default=50, label="Top P", step=1)
157
+ repeat_penalty = gr.inputs.Slider(0.1, 100., default=1.2, label="Repeat penalty", step=0.1)
158
+ change_model_button = gr.Button("Load Llama GGUF Model")
159
+
160
+ model_verify_GGUF = gr.HTML("Loaded model Llama-2")
161
+
162
+ with gr.Tab("API Models"):
163
+
164
+ default_model = gr.HTML("<hr>Falcon Model</h2>")
165
+ hf_key = gr.Textbox(label="HF TOKEN", value="token...")
166
+ falcon_button = gr.Button("Load FALCON 7B-Instruct")
167
+
168
+ openai_gpt_model = gr.HTML("<hr>OpenAI Model gpt-3.5-turbo</h2>")
169
+ api_key = gr.Textbox(label="API KEY", value="api_key...")
170
+ openai_button = gr.Button("Load gpt-3.5-turbo")
171
+
172
+ line_ = gr.HTML("<hr> </h2>")
173
+ model_verify = gr.HTML(" ")
174
+
175
+ with gr.Tab("Help"):
176
+ description_md = gr.Markdown(description)
177
+
178
+ msg.submit(predict,[msg, chatbot, max_docs, check_memory],[msg, chatbot]).then(convert,[],[sou])
179
+
180
+ change_model_button.click(dc.change_llm,[repo_, file_, max_tokens, temperature, top_p, top_k, repeat_penalty, max_docs],[model_verify_GGUF])
181
+
182
+ falcon_button.click(dc.default_falcon_model, [hf_key], [model_verify])
183
+ openai_button.click(clear_api_key, [api_key], [api_key, model_verify])
184
+
185
+ demo.launch(debug=True, share=True, enable_queue=True)
conversadocs/__pycache__/bones.cpython-38.pyc ADDED
Binary file (7.88 kB). View file
 
conversadocs/__pycache__/llamacppmodels.cpython-38.pyc ADDED
Binary file (7.57 kB). View file
 
conversadocs/__pycache__/llm_chess.cpython-38.pyc ADDED
Binary file (3.17 kB). View file
 
conversadocs/bones.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from langchain.embeddings.openai import OpenAIEmbeddings
3
+ from langchain.text_splitter import CharacterTextSplitter, RecursiveCharacterTextSplitter
4
+ from langchain.vectorstores import DocArrayInMemorySearch
5
+ from langchain.chains import RetrievalQA, ConversationalRetrievalChain
6
+ from langchain.memory import ConversationBufferMemory
7
+ from langchain.chat_models import ChatOpenAI
8
+ from langchain.embeddings import HuggingFaceEmbeddings
9
+ from langchain import HuggingFaceHub
10
+ from conversadocs.llamacppmodels import LlamaCpp #from langchain.llms import LlamaCpp
11
+ from huggingface_hub import hf_hub_download
12
+ import param
13
+ import os
14
+ import torch
15
+ from langchain.document_loaders import (
16
+ EverNoteLoader,
17
+ TextLoader,
18
+ UnstructuredEPubLoader,
19
+ UnstructuredHTMLLoader,
20
+ UnstructuredMarkdownLoader,
21
+ UnstructuredODTLoader,
22
+ UnstructuredPowerPointLoader,
23
+ UnstructuredWordDocumentLoader,
24
+ PyPDFLoader,
25
+ )
26
+ import gc
27
+ gc.collect()
28
+ torch.cuda.empty_cache()
29
+
30
+ #YOUR_HF_TOKEN = os.getenv("My_hf_token")
31
+ REPO = "TheBloke/Mistral-7B-OpenOrca-GGUF"
32
+ MODEL = "mistral-7b-openorca.Q4_K_M.gguf"
33
+ MAX_TOKEN = 32000
34
+ EXTENSIONS = {
35
+ ".txt": (TextLoader, {"encoding": "utf8"}),
36
+ ".pdf": (PyPDFLoader, {}),
37
+ ".log": (TextLoader, {"encoding": "utf8"}),
38
+ ".doc": (UnstructuredWordDocumentLoader, {}),
39
+ ".docx": (UnstructuredWordDocumentLoader, {}),
40
+ ".enex": (EverNoteLoader, {}),
41
+ ".epub": (UnstructuredEPubLoader, {}),
42
+ ".html": (UnstructuredHTMLLoader, {}),
43
+ ".md": (UnstructuredMarkdownLoader, {}),
44
+ ".odt": (UnstructuredODTLoader, {}),
45
+ ".ppt": (UnstructuredPowerPointLoader, {}),
46
+ ".pptx": (UnstructuredPowerPointLoader, {}),
47
+ }
48
+
49
+ #alter
50
+ def load_db(files):
51
+
52
+ # select extensions loader
53
+ documents = []
54
+ for file in files:
55
+ ext = "." + file.rsplit(".", 1)[-1]
56
+ if ext in EXTENSIONS:
57
+ loader_class, loader_args = EXTENSIONS[ext]
58
+ loader = loader_class(file, **loader_args)
59
+ documents.extend(loader.load())
60
+ else:
61
+ pass
62
+
63
+ # load documents
64
+ if documents == []:
65
+ loader_class, loader_args = EXTENSIONS['.txt']
66
+ loader = loader_class('demo_docs/demo.txt', **loader_args)
67
+ documents = loader.load()
68
+
69
+ # split documents
70
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=150)
71
+ docs = text_splitter.split_documents(documents)
72
+
73
+ # define embedding
74
+ embeddings = HuggingFaceEmbeddings(model_name='all-MiniLM-L6-v2') # all-mpnet-base-v2 #embeddings = OpenAIEmbeddings()
75
+
76
+ # create vector database from data
77
+ db = DocArrayInMemorySearch.from_documents(docs, embeddings)
78
+ return db
79
+
80
+ def q_a(db, chain_type="stuff", k=3, llm=None):
81
+ retriever = db.as_retriever(search_type="similarity", search_kwargs={"k": k})
82
+ # create a chatbot chain. Memory is managed externally.
83
+ qa = ConversationalRetrievalChain.from_llm(
84
+ llm=llm,
85
+ chain_type=chain_type,
86
+ retriever=retriever,
87
+ return_source_documents=True,
88
+ return_generated_question=True,
89
+ )
90
+ return qa
91
+
92
+
93
+
94
+ class DocChat(param.Parameterized):
95
+ chat_history = param.List([])
96
+ answer = param.String("")
97
+ db_query = param.String("")
98
+ db_response = param.List([])
99
+ k_value = param.Integer(3)
100
+ llm = None
101
+
102
+ def __init__(self, **params):
103
+ super(DocChat, self).__init__( **params)
104
+ self.loaded_file = ["demo_docs/demo.txt"]
105
+ self.db = load_db(self.loaded_file)
106
+ self.change_llm(REPO, MODEL, max_tokens=MAX_TOKEN, temperature=0.2, top_p=0.95, top_k=50, repeat_penalty=1.2, k=3)
107
+ self.qa = q_a(self.db, "stuff", self.k_value, self.llm)
108
+
109
+
110
+ def call_load_db(self, path_file, k):
111
+ if not os.path.exists(path_file[0]): # init or no file specified
112
+ return "No file loaded"
113
+ else:
114
+ try:
115
+ self.db = load_db(path_file)
116
+ self.loaded_file = path_file
117
+ self.qa = q_a(self.db, "stuff", k, self.llm)
118
+ self.k_value = k
119
+ #self.clr_history()
120
+ return f"New DB created and history cleared | Loaded File: {self.loaded_file}"
121
+ except:
122
+ return f'No valid file'
123
+
124
+
125
+ # chat
126
+ def convchain(self, query, k_max, recall_previous_messages):
127
+ if k_max != self.k_value:
128
+ print("Maximum querys changed")
129
+ self.qa = q_a(self.db, "stuff", k_max, self.llm)
130
+ self.k_value = k_max
131
+
132
+ if not recall_previous_messages:
133
+ self.clr_history()
134
+
135
+ try:
136
+ result = self.qa({"question": query, "chat_history": self.chat_history})
137
+ except:
138
+ print("Error not get response from model, reloaded default llama-2 7B config")
139
+ self.change_llm(REPO, MODEL, max_tokens=32000, temperature=0.2, top_p=0.95, top_k=50, repeat_penalty=1.2, k=3)
140
+ self.qa = q_a(self.db, "stuff", k_max, self.llm)
141
+ result = self.qa({"question": query, "chat_history": self.chat_history})
142
+
143
+ self.chat_history.extend([(query, result["answer"])])
144
+ self.db_query = result["generated_question"]
145
+ self.db_response = result["source_documents"]
146
+ self.answer = result['answer']
147
+ return self.answer
148
+
149
+ def summarize(self, chunk_size=2000, chunk_overlap=100):
150
+ # load docs
151
+ documents = []
152
+ for file in self.loaded_file:
153
+ ext = "." + file.rsplit(".", 1)[-1]
154
+ if ext in EXTENSIONS:
155
+ loader_class, loader_args = EXTENSIONS[ext]
156
+ loader = loader_class(file, **loader_args)
157
+ documents.extend(loader.load_and_split())
158
+
159
+ if documents == []:
160
+ return "Error in summarization"
161
+
162
+ # split documents
163
+ text_splitter = RecursiveCharacterTextSplitter(
164
+ chunk_size=chunk_size,
165
+ chunk_overlap=chunk_overlap,
166
+ separators=["\n\n", "\n", "(?<=\. )", " ", ""]
167
+ )
168
+ docs = text_splitter.split_documents(documents)
169
+ # summarize
170
+ from langchain.chains.summarize import load_summarize_chain
171
+ chain = load_summarize_chain(self.llm, chain_type='map_reduce', verbose=True)
172
+ return chain.run(docs)
173
+
174
+ def change_llm(self, repo_, file_, max_tokens=MAX_TOKEN, temperature=0.2, top_p=0.95, top_k=50, repeat_penalty=1.2, k=3):
175
+
176
+ if torch.cuda.is_available():
177
+ try:
178
+ model_path = hf_hub_download(repo_id=repo_, filename=file_)
179
+ self.qa = None
180
+ self.llm = None
181
+ gc.collect()
182
+ torch.cuda.empty_cache()
183
+ gpu_llm_layers = 43 if not '70B' in repo_.upper() else 25 # fix for 70B
184
+ print("GPU Layers: ", gpu_llm_layers)
185
+ self.llm = LlamaCpp(
186
+ model_path=model_path,
187
+ n_ctx=MAX_TOKEN,
188
+ n_batch=512,
189
+ n_gpu_layers=gpu_llm_layers,
190
+ max_tokens=max_tokens,
191
+ verbose=True,
192
+ temperature=temperature,
193
+ top_p=top_p,
194
+ top_k=top_k,
195
+ repeat_penalty=repeat_penalty,
196
+ )
197
+ self.qa = q_a(self.db, "stuff", k, self.llm)
198
+ self.k_value = k
199
+ return f"Loaded {file_} [GPU INFERENCE]"
200
+ except:
201
+ self.change_llm(REPO, MODEL, max_tokens=MAX_TOKEN, temperature=0.2, top_p=0.95, top_k=50, repeat_penalty=1.2, k=3)
202
+ return "No valid model | Reloaded Reloaded default llama-2 7B config"
203
+ else:
204
+ try:
205
+ model_path = hf_hub_download(repo_id=repo_, filename=file_)
206
+
207
+ self.qa = None
208
+ self.llm = None
209
+ gc.collect()
210
+ torch.cuda.empty_cache()
211
+
212
+ self.llm = LlamaCpp(
213
+ model_path=model_path,
214
+ n_ctx=2048,
215
+ n_batch=8,
216
+ max_tokens=max_tokens,
217
+ verbose=True,
218
+ temperature=temperature,
219
+ top_p=top_p,
220
+ top_k=top_k,
221
+ repeat_penalty=repeat_penalty,
222
+ )
223
+ self.qa = q_a(self.db, "stuff", k, self.llm)
224
+ self.k_value = k
225
+ return f"Loaded {file_} [CPU INFERENCE SLOW]"
226
+ except:
227
+ self.change_llm(REPO, MODEL, max_tokens=2048, temperature=0.2, top_p=0.95, top_k=50, repeat_penalty=1.2, k=3)
228
+ return "No valid model | Reloaded default llama-2 7B config"
229
+
230
+ def default_falcon_model(self, HF_TOKEN):
231
+ self.llm = llm_api=HuggingFaceHub(
232
+ huggingfacehub_api_token=HF_TOKEN,
233
+ repo_id="tiiuae/falcon-7b-instruct",
234
+ model_kwargs={
235
+ "temperature":0.2,
236
+ "max_new_tokens":500,
237
+ "top_k":50,
238
+ "top_p":0.95,
239
+ "repetition_penalty":1.2,
240
+ },)
241
+ self.qa = q_a(self.db, "stuff", self.k_value, self.llm)
242
+ return "Loaded model Falcon 7B-instruct [API FAST INFERENCE]"
243
+
244
+ def openai_model(self, API_KEY):
245
+ self.llm = ChatOpenAI(temperature=0, openai_api_key=API_KEY, model_name='gpt-3.5-turbo')
246
+ self.qa = q_a(self.db, "stuff", self.k_value, self.llm)
247
+ API_KEY = ""
248
+ return "Loaded model OpenAI gpt-3.5-turbo [API FAST INFERENCE]"
249
+
250
+ @param.depends('db_query ', )
251
+ def get_lquest(self):
252
+ if not self.db_query :
253
+ return print("Last question to DB: no DB accesses so far")
254
+ return self.db_query
255
+
256
+ @param.depends('db_response', )
257
+ def get_sources(self):
258
+ if not self.db_response:
259
+ return
260
+ #rlist=[f"Result of DB lookup:"]
261
+ rlist=[]
262
+ for doc in self.db_response:
263
+ for element in doc:
264
+ rlist.append(element)
265
+ return rlist
266
+
267
+ @param.depends('convchain', 'clr_history')
268
+ def get_chats(self):
269
+ if not self.chat_history:
270
+ return "No History Yet"
271
+ #rlist=[f"Current Chat History variable"]
272
+ rlist=[]
273
+ for exchange in self.chat_history:
274
+ rlist.append(exchange)
275
+ return rlist
276
+
277
+ def clr_history(self,count=0):
278
+ self.chat_history = []
279
+ return "HISTORY CLEARED"
conversadocs/llamacppmodels.py ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from typing import Any, Dict, Iterator, List, Optional
3
+
4
+ from pydantic import Field, root_validator
5
+
6
+ from langchain.callbacks.manager import CallbackManagerForLLMRun
7
+ from langchain.llms.base import LLM
8
+ from langchain.schema.output import GenerationChunk
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+
13
+ class LlamaCpp(LLM):
14
+ """llama.cpp model.
15
+
16
+ To use, you should have the llama-cpp-python library installed, and provide the
17
+ path to the Llama model as a named parameter to the constructor.
18
+ Check out: https://github.com/abetlen/llama-cpp-python
19
+
20
+ Example:
21
+ .. code-block:: python
22
+
23
+ from langchain.llms import LlamaCpp
24
+ llm = LlamaCpp(model_path="/path/to/llama/model")
25
+ """
26
+
27
+ client: Any #: :meta private:
28
+ model_path: str
29
+ """The path to the Llama model file."""
30
+
31
+ lora_base: Optional[str] = None
32
+ """The path to the Llama LoRA base model."""
33
+
34
+ lora_path: Optional[str] = None
35
+ """The path to the Llama LoRA. If None, no LoRa is loaded."""
36
+
37
+ n_ctx: int = Field(512, alias="n_ctx")
38
+ """Token context window."""
39
+
40
+ n_parts: int = Field(-1, alias="n_parts")
41
+ """Number of parts to split the model into.
42
+ If -1, the number of parts is automatically determined."""
43
+
44
+ seed: int = Field(-1, alias="seed")
45
+ """Seed. If -1, a random seed is used."""
46
+
47
+ f16_kv: bool = Field(True, alias="f16_kv")
48
+ """Use half-precision for key/value cache."""
49
+
50
+ logits_all: bool = Field(False, alias="logits_all")
51
+ """Return logits for all tokens, not just the last token."""
52
+
53
+ vocab_only: bool = Field(False, alias="vocab_only")
54
+ """Only load the vocabulary, no weights."""
55
+
56
+ use_mlock: bool = Field(False, alias="use_mlock")
57
+ """Force system to keep model in RAM."""
58
+
59
+ n_threads: Optional[int] = Field(None, alias="n_threads")
60
+ """Number of threads to use.
61
+ If None, the number of threads is automatically determined."""
62
+
63
+ n_batch: Optional[int] = Field(8, alias="n_batch")
64
+ """Number of tokens to process in parallel.
65
+ Should be a number between 1 and n_ctx."""
66
+
67
+ n_gpu_layers: Optional[int] = Field(None, alias="n_gpu_layers")
68
+ """Number of layers to be loaded into gpu memory. Default None."""
69
+
70
+ suffix: Optional[str] = Field(None)
71
+ """A suffix to append to the generated text. If None, no suffix is appended."""
72
+
73
+ max_tokens: Optional[int] = 256
74
+ """The maximum number of tokens to generate."""
75
+
76
+ temperature: Optional[float] = 0.8
77
+ """The temperature to use for sampling."""
78
+
79
+ top_p: Optional[float] = 0.95
80
+ """The top-p value to use for sampling."""
81
+
82
+ logprobs: Optional[int] = Field(None)
83
+ """The number of logprobs to return. If None, no logprobs are returned."""
84
+
85
+ echo: Optional[bool] = False
86
+ """Whether to echo the prompt."""
87
+
88
+ stop: Optional[List[str]] = []
89
+ """A list of strings to stop generation when encountered."""
90
+
91
+ repeat_penalty: Optional[float] = 1.1
92
+ """The penalty to apply to repeated tokens."""
93
+
94
+ top_k: Optional[int] = 40
95
+ """The top-k value to use for sampling."""
96
+
97
+ last_n_tokens_size: Optional[int] = 64
98
+ """The number of tokens to look back when applying the repeat_penalty."""
99
+
100
+ use_mmap: Optional[bool] = True
101
+ """Whether to keep the model loaded in RAM"""
102
+
103
+ rope_freq_scale: float = 1.0
104
+ """Scale factor for rope sampling."""
105
+
106
+ rope_freq_base: float = 10000.0
107
+ """Base frequency for rope sampling."""
108
+
109
+ streaming: bool = True
110
+ """Whether to stream the results, token by token."""
111
+
112
+ verbose: bool = True
113
+ """Print verbose output to stderr."""
114
+
115
+ n_gqa: Optional[int] = None
116
+
117
+ @root_validator()
118
+ def validate_environment(cls, values: Dict) -> Dict:
119
+ """Validate that llama-cpp-python library is installed."""
120
+
121
+
122
+ model_path = values["model_path"]
123
+ model_param_names = [
124
+ "n_gqa",
125
+ "rope_freq_scale",
126
+ "rope_freq_base",
127
+ "lora_path",
128
+ "lora_base",
129
+ "n_ctx",
130
+ "n_parts",
131
+ "seed",
132
+ "f16_kv",
133
+ "logits_all",
134
+ "vocab_only",
135
+ "use_mlock",
136
+ "n_threads",
137
+ "n_batch",
138
+ "use_mmap",
139
+ "last_n_tokens_size",
140
+ "verbose",
141
+ ]
142
+ model_params = {k: values[k] for k in model_param_names}
143
+
144
+ model_params['n_gqa'] = 8 if '70B' in model_path.upper() else None # (TEMPORARY) must be 8 for llama2 70b
145
+ # For backwards compatibility, only include if non-null.
146
+ if values["n_gpu_layers"] is not None:
147
+ model_params["n_gpu_layers"] = values["n_gpu_layers"]
148
+
149
+ try:
150
+ from llama_cpp import Llama
151
+
152
+ values["client"] = Llama(model_path, **model_params)
153
+ except ImportError:
154
+ raise ImportError(
155
+ "Could not import llama-cpp-python library. "
156
+ "Please install the llama-cpp-python library to "
157
+ "use this embedding model: pip install llama-cpp-python"
158
+ )
159
+ except Exception as e:
160
+ raise ValueError(
161
+ f"Could not load Llama model from path: {model_path}. "
162
+ f"Received error {e}"
163
+ )
164
+
165
+ return values
166
+
167
+ @property
168
+ def _default_params(self) -> Dict[str, Any]:
169
+ """Get the default parameters for calling llama_cpp."""
170
+ return {
171
+ "suffix": self.suffix,
172
+ "max_tokens": self.max_tokens,
173
+ "temperature": self.temperature,
174
+ "top_p": self.top_p,
175
+ "logprobs": self.logprobs,
176
+ "echo": self.echo,
177
+ "stop_sequences": self.stop, # key here is convention among LLM classes
178
+ "repeat_penalty": self.repeat_penalty,
179
+ "top_k": self.top_k,
180
+ }
181
+
182
+ @property
183
+ def _identifying_params(self) -> Dict[str, Any]:
184
+ """Get the identifying parameters."""
185
+ return {**{"model_path": self.model_path}, **self._default_params}
186
+
187
+ @property
188
+ def _llm_type(self) -> str:
189
+ """Return type of llm."""
190
+ return "llamacpp"
191
+
192
+ def _get_parameters(self, stop: Optional[List[str]] = None) -> Dict[str, Any]:
193
+ """
194
+ Performs sanity check, preparing parameters in format needed by llama_cpp.
195
+
196
+ Args:
197
+ stop (Optional[List[str]]): List of stop sequences for llama_cpp.
198
+
199
+ Returns:
200
+ Dictionary containing the combined parameters.
201
+ """
202
+
203
+ # Raise error if stop sequences are in both input and default params
204
+ if self.stop and stop is not None:
205
+ raise ValueError("`stop` found in both the input and default params.")
206
+
207
+ params = self._default_params
208
+
209
+ # llama_cpp expects the "stop" key not this, so we remove it:
210
+ params.pop("stop_sequences")
211
+
212
+ # then sets it as configured, or default to an empty list:
213
+ params["stop"] = self.stop or stop or []
214
+
215
+ return params
216
+
217
+ def _call(
218
+ self,
219
+ prompt: str,
220
+ stop: Optional[List[str]] = None,
221
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
222
+ **kwargs: Any,
223
+ ) -> str:
224
+ """Call the Llama model and return the output.
225
+
226
+ Args:
227
+ prompt: The prompt to use for generation.
228
+ stop: A list of strings to stop generation when encountered.
229
+
230
+ Returns:
231
+ The generated text.
232
+
233
+ Example:
234
+ .. code-block:: python
235
+
236
+ from langchain.llms import LlamaCpp
237
+ llm = LlamaCpp(model_path="/path/to/local/llama/model.bin")
238
+ llm("This is a prompt.")
239
+ """
240
+ if self.streaming:
241
+ # If streaming is enabled, we use the stream
242
+ # method that yields as they are generated
243
+ # and return the combined strings from the first choices's text:
244
+ combined_text_output = ""
245
+ for chunk in self._stream(
246
+ prompt=prompt, stop=stop, run_manager=run_manager, **kwargs
247
+ ):
248
+ combined_text_output += chunk.text
249
+ return combined_text_output
250
+ else:
251
+ params = self._get_parameters(stop)
252
+ params = {**params, **kwargs}
253
+ result = self.client(prompt=prompt, **params)
254
+ return result["choices"][0]["text"]
255
+
256
+ def _stream(
257
+ self,
258
+ prompt: str,
259
+ stop: Optional[List[str]] = None,
260
+ run_manager: Optional[CallbackManagerForLLMRun] = None,
261
+ **kwargs: Any,
262
+ ) -> Iterator[GenerationChunk]:
263
+ """Yields results objects as they are generated in real time.
264
+
265
+ It also calls the callback manager's on_llm_new_token event with
266
+ similar parameters to the OpenAI LLM class method of the same name.
267
+
268
+ Args:
269
+ prompt: The prompts to pass into the model.
270
+ stop: Optional list of stop words to use when generating.
271
+
272
+ Returns:
273
+ A generator representing the stream of tokens being generated.
274
+
275
+ Yields:
276
+ A dictionary like objects containing a string token and metadata.
277
+ See llama-cpp-python docs and below for more.
278
+
279
+ Example:
280
+ .. code-block:: python
281
+
282
+ from langchain.llms import LlamaCpp
283
+ llm = LlamaCpp(
284
+ model_path="/path/to/local/model.bin",
285
+ temperature = 0.5
286
+ )
287
+ for chunk in llm.stream("Ask 'Hi, how are you?' like a pirate:'",
288
+ stop=["'","\n"]):
289
+ result = chunk["choices"][0]
290
+ print(result["text"], end='', flush=True)
291
+
292
+ """
293
+ params = {**self._get_parameters(stop), **kwargs}
294
+ result = self.client(prompt=prompt, stream=True, **params)
295
+ for part in result:
296
+ logprobs = part["choices"][0].get("logprobs", None)
297
+ chunk = GenerationChunk(
298
+ text=part["choices"][0]["text"],
299
+ generation_info={"logprobs": logprobs},
300
+ )
301
+ yield chunk
302
+ if run_manager:
303
+ run_manager.on_llm_new_token(
304
+ token=chunk.text, verbose=self.verbose, log_probs=logprobs
305
+ )
306
+
307
+ def get_num_tokens(self, text: str) -> int:
308
+ tokenized_text = self.client.tokenize(text.encode("utf-8"))
309
+ return len(tokenized_text)
conversadocs/llm_chess.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import chess
3
+ import chess.pgn
4
+
5
+ # credit code https://github.com/notnil/chess-gpt
6
+ def get_legal_moves(board):
7
+ """Returns a list of legal moves in UCI notation."""
8
+ return list(map(board.san, board.legal_moves))
9
+
10
+ def init_game() -> tuple[chess.pgn.Game, chess.Board]:
11
+ """Initializes a new game."""
12
+ board = chess.Board()
13
+ game = chess.pgn.Game()
14
+ game.headers["White"] = "User"
15
+ game.headers["Black"] = "Chess-engine"
16
+ del game.headers["Event"]
17
+ del game.headers["Date"]
18
+ del game.headers["Site"]
19
+ del game.headers["Round"]
20
+ del game.headers["Result"]
21
+ game.setup(board)
22
+ return game, board
23
+
24
+ def generate_prompt(game: chess.pgn.Game, board: chess.Board) -> str:
25
+
26
+ moves = get_legal_moves(board)
27
+ moves_str = ",".join(moves)
28
+ return f"""
29
+ The task is play a Chess game:
30
+ You are the Chess-engine playing a chess match against the user as black and trying to win.
31
+
32
+ The current FEN notation is:
33
+ {board.fen()}
34
+
35
+ The next valid moves are:
36
+ {moves_str}
37
+
38
+ Continue the game.
39
+ {str(game)[:-2]}"""
40
+
41
+ def get_move(content, moves):
42
+ lines = content.splitlines()
43
+ for line in lines:
44
+ for lm in moves:
45
+ if lm in line:
46
+ return lm
47
+
48
+ class ChessGame:
49
+ def __init__(self, docschatllm):
50
+ self.docschatllm = docschatllm
51
+
52
+ def start_game(self):
53
+ self.game, self.board = init_game()
54
+ self.game_cp, _ = init_game()
55
+ self.node = self.game
56
+ self.node_copy = self.game_cp
57
+
58
+ svg_board = chess.svg.board(self.board, size=350)
59
+ return svg_board, "Valid moves: "+",".join(get_legal_moves(self.board)) # display(self.board)
60
+
61
+ def user_move(self, move_input):
62
+ try:
63
+ self.board.push_san(move_input)
64
+ except ValueError:
65
+ print("Invalid move")
66
+ svg_board = chess.svg.board(self.board, size=350)
67
+ return svg_board, "Valid moves: "+",".join(get_legal_moves(self.board)), 'Invalid move'
68
+ self.node = self.node.add_variation(self.board.move_stack[-1])
69
+ self.node_copy = self.node_copy.add_variation(self.board.move_stack[-1])
70
+
71
+ if self.board.is_game_over():
72
+ svg_board = chess.svg.board(self.board, size=350)
73
+ return svg_board, ",".join(get_legal_moves(self.board)), 'GAME OVER'
74
+
75
+ prompt = generate_prompt(self.game, self.board)
76
+ print("Prompt: \n"+prompt)
77
+ print("#############")
78
+ for i in range(10): #tries
79
+ if i == 9:
80
+ svg_board = chess.svg.board(self.board, size=350)
81
+ return svg_board, ",".join(get_legal_moves(self.board)), "The model can't do a valid move"
82
+ try:
83
+ """Returns the move from the prompt."""
84
+ content = self.docschatllm.llm.predict(prompt) ### from selected model ###
85
+ #print(moves)
86
+ print("Response: \n"+content)
87
+ print("#############")
88
+
89
+ moves = get_legal_moves(self.board)
90
+ move = get_move(content, moves)
91
+ print(move)
92
+ print("#############")
93
+ self.board.push_san(move)
94
+ break
95
+ except:
96
+ prompt = prompt[1:]
97
+ print("attempt a move.")
98
+ self.node = self.node.add_variation(self.board.move_stack[-1])
99
+ self.node_copy = self.node_copy.add_variation(self.board.move_stack[-1])
100
+ svg_board = chess.svg.board(self.board, size=350)
101
+ return svg_board, "Valid moves: "+",".join(get_legal_moves(self.board)), ''
requirements.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ transformers
2
+ torch
3
+ pypdf
4
+ langchain==0.0.247
5
+ langchain[docarray]
6
+ tiktoken
7
+ sentence_transformers
8
+ chromadb
9
+ huggingface_hub
10
+ unstructured[local-inference]
11
+ gradio==3.35.2
12
+ param==1.13.0
13
+ openai
14
+ python-chess==1.999