Commit
•
e86290c
0
Parent(s):
Duplicate from shibing624/ChatPDF
Browse filesCo-authored-by: Ming Xu (徐明) <[email protected]>
- .gitattributes +34 -0
- LICENSE +201 -0
- README.md +14 -0
- app.py +282 -0
- chatpdf.py +171 -0
- requirements.txt +11 -0
- sample.pdf +0 -0
.gitattributes
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
28 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
29 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
30 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
31 |
+
*.xz 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
|
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
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
title: ChatPDF
|
3 |
+
emoji: 😁
|
4 |
+
colorFrom: blue
|
5 |
+
colorTo: blue
|
6 |
+
sdk: gradio
|
7 |
+
sdk_version: 3.24.1
|
8 |
+
app_file: app.py
|
9 |
+
pinned: false
|
10 |
+
license: apache-2.0
|
11 |
+
duplicated_from: shibing624/ChatPDF
|
12 |
+
---
|
13 |
+
|
14 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
app.py
ADDED
@@ -0,0 +1,282 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
"""
|
3 |
+
@author:XuMing([email protected])
|
4 |
+
@description:
|
5 |
+
modified from https://github.com/imClumsyPanda/langchain-ChatGLM/blob/master/webui.py
|
6 |
+
"""
|
7 |
+
import gradio as gr
|
8 |
+
import os
|
9 |
+
import shutil
|
10 |
+
from loguru import logger
|
11 |
+
from chatpdf import ChatPDF
|
12 |
+
import hashlib
|
13 |
+
|
14 |
+
pwd_path = os.path.abspath(os.path.dirname(__file__))
|
15 |
+
|
16 |
+
CONTENT_DIR = os.path.join(pwd_path, "content")
|
17 |
+
logger.info(f"CONTENT_DIR: {CONTENT_DIR}")
|
18 |
+
VECTOR_SEARCH_TOP_K = 3
|
19 |
+
MAX_INPUT_LEN = 2048
|
20 |
+
|
21 |
+
embedding_model_dict = {
|
22 |
+
"text2vec-large": "GanymedeNil/text2vec-large-chinese",
|
23 |
+
"text2vec-base": "shibing624/text2vec-base-chinese",
|
24 |
+
"sentence-transformers": "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2",
|
25 |
+
"ernie-tiny": "nghuyong/ernie-3.0-nano-zh",
|
26 |
+
"ernie-base": "nghuyong/ernie-3.0-base-zh",
|
27 |
+
|
28 |
+
}
|
29 |
+
|
30 |
+
# supported LLM models
|
31 |
+
llm_model_dict = {
|
32 |
+
"chatglm-6b-int4": "THUDM/chatglm-6b-int4",
|
33 |
+
"chatglm-6b-int4-qe": "THUDM/chatglm-6b-int4-qe",
|
34 |
+
"chatglm-6b": "THUDM/chatglm-6b",
|
35 |
+
"llama-7b": "decapoda-research/llama-7b-hf",
|
36 |
+
"llama-13b": "decapoda-research/llama-13b-hf",
|
37 |
+
}
|
38 |
+
|
39 |
+
llm_model_dict_list = list(llm_model_dict.keys())
|
40 |
+
embedding_model_dict_list = list(embedding_model_dict.keys())
|
41 |
+
|
42 |
+
model = None
|
43 |
+
|
44 |
+
|
45 |
+
def get_file_list():
|
46 |
+
if not os.path.exists("content"):
|
47 |
+
return []
|
48 |
+
return [f for f in os.listdir("content") if
|
49 |
+
f.endswith(".txt") or f.endswith(".pdf") or f.endswith(".docx") or f.endswith(".md")]
|
50 |
+
|
51 |
+
|
52 |
+
file_list = get_file_list()
|
53 |
+
|
54 |
+
|
55 |
+
def upload_file(file):
|
56 |
+
if not os.path.exists(CONTENT_DIR):
|
57 |
+
os.mkdir(CONTENT_DIR)
|
58 |
+
filename = os.path.basename(file.name)
|
59 |
+
shutil.move(file.name, os.path.join(CONTENT_DIR, filename))
|
60 |
+
# file_list首位插入新上传的文件
|
61 |
+
file_list.insert(0, filename)
|
62 |
+
return gr.Dropdown.update(choices=file_list, value=filename)
|
63 |
+
|
64 |
+
|
65 |
+
def parse_text(text):
|
66 |
+
"""copy from https://github.com/GaiZhenbiao/ChuanhuChatGPT/"""
|
67 |
+
lines = text.split("\n")
|
68 |
+
lines = [line for line in lines if line != ""]
|
69 |
+
count = 0
|
70 |
+
for i, line in enumerate(lines):
|
71 |
+
if "```" in line:
|
72 |
+
count += 1
|
73 |
+
items = line.split('`')
|
74 |
+
if count % 2 == 1:
|
75 |
+
lines[i] = f'<pre><code class="language-{items[-1]}">'
|
76 |
+
else:
|
77 |
+
lines[i] = f'<br></code></pre>'
|
78 |
+
else:
|
79 |
+
if i > 0:
|
80 |
+
if count % 2 == 1:
|
81 |
+
line = line.replace("`", "\`")
|
82 |
+
line = line.replace("<", "<")
|
83 |
+
line = line.replace(">", ">")
|
84 |
+
line = line.replace(" ", " ")
|
85 |
+
line = line.replace("*", "*")
|
86 |
+
line = line.replace("_", "_")
|
87 |
+
line = line.replace("-", "-")
|
88 |
+
line = line.replace(".", ".")
|
89 |
+
line = line.replace("!", "!")
|
90 |
+
line = line.replace("(", "(")
|
91 |
+
line = line.replace(")", ")")
|
92 |
+
line = line.replace("$", "$")
|
93 |
+
lines[i] = "<br>" + line
|
94 |
+
text = "".join(lines)
|
95 |
+
return text
|
96 |
+
|
97 |
+
|
98 |
+
def get_answer(query, index_path, history, topn=VECTOR_SEARCH_TOP_K, max_input_size=1024, only_chat=False):
|
99 |
+
if model is None:
|
100 |
+
return [None, "模型还未加载"], query
|
101 |
+
if index_path and not only_chat:
|
102 |
+
if not model.sim_model.corpus_embeddings:
|
103 |
+
model.load_index(index_path)
|
104 |
+
response, empty_history, reference_results = model.query(query=query, topn=topn, max_input_size=max_input_size)
|
105 |
+
|
106 |
+
logger.debug(f"query: {query}, response with content: {response}")
|
107 |
+
for i in range(len(reference_results)):
|
108 |
+
r = reference_results[i]
|
109 |
+
response += f"\n{r.strip()}"
|
110 |
+
response = parse_text(response)
|
111 |
+
history = history + [[query, response]]
|
112 |
+
else:
|
113 |
+
# 未加载文件,仅返回生成模型结果
|
114 |
+
response, empty_history = model.gen_model.chat(query)
|
115 |
+
response = parse_text(response)
|
116 |
+
history = history + [[query, response]]
|
117 |
+
logger.debug(f"query: {query}, response: {response}")
|
118 |
+
return history, ""
|
119 |
+
|
120 |
+
|
121 |
+
def update_status(history, status):
|
122 |
+
history = history + [[None, status]]
|
123 |
+
logger.info(status)
|
124 |
+
return history
|
125 |
+
|
126 |
+
|
127 |
+
def reinit_model(llm_model, embedding_model, history):
|
128 |
+
try:
|
129 |
+
global model
|
130 |
+
if model is not None:
|
131 |
+
del model
|
132 |
+
model = ChatPDF(
|
133 |
+
sim_model_name_or_path=embedding_model_dict.get(
|
134 |
+
embedding_model,
|
135 |
+
"sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"
|
136 |
+
),
|
137 |
+
gen_model_type=llm_model.split('-')[0],
|
138 |
+
gen_model_name_or_path=llm_model_dict.get(llm_model, "THUDM/chatglm-6b-int4"),
|
139 |
+
lora_model_name_or_path=None,
|
140 |
+
)
|
141 |
+
|
142 |
+
model_status = """模型已成功重新加载,请选择文件后点击"加载文件"按钮"""
|
143 |
+
except Exception as e:
|
144 |
+
model = None
|
145 |
+
logger.error(e)
|
146 |
+
model_status = """模型未成功重新加载,请重新选择后点击"加载模型"按钮"""
|
147 |
+
return history + [[None, model_status]]
|
148 |
+
|
149 |
+
|
150 |
+
def get_file_hash(fpath):
|
151 |
+
return hashlib.md5(open(fpath, 'rb').read()).hexdigest()
|
152 |
+
|
153 |
+
|
154 |
+
def get_vector_store(filepath, history, embedding_model):
|
155 |
+
logger.info(filepath, history)
|
156 |
+
index_path = None
|
157 |
+
file_status = ''
|
158 |
+
if model is not None:
|
159 |
+
|
160 |
+
local_file_path = os.path.join(CONTENT_DIR, filepath)
|
161 |
+
|
162 |
+
local_file_hash = get_file_hash(local_file_path)
|
163 |
+
index_file_name = f"{filepath}.{embedding_model}.{local_file_hash}.index.json"
|
164 |
+
|
165 |
+
local_index_path = os.path.join(CONTENT_DIR, index_file_name)
|
166 |
+
|
167 |
+
if os.path.exists(local_index_path):
|
168 |
+
model.load_index(local_index_path)
|
169 |
+
index_path = local_index_path
|
170 |
+
file_status = "文件已成功加载,请开始提问"
|
171 |
+
|
172 |
+
elif os.path.exists(local_file_path):
|
173 |
+
model.load_pdf_file(local_file_path)
|
174 |
+
model.save_index(local_index_path)
|
175 |
+
index_path = local_index_path
|
176 |
+
if index_path:
|
177 |
+
file_status = "文件索引并成功加载,请开始提问"
|
178 |
+
else:
|
179 |
+
file_status = "文件未成功加载,请重新上传文件"
|
180 |
+
else:
|
181 |
+
file_status = "模型未完成加载,请先在加载模型后再导入文件"
|
182 |
+
|
183 |
+
return index_path, history + [[None, file_status]]
|
184 |
+
|
185 |
+
|
186 |
+
def reset_chat(chatbot, state):
|
187 |
+
return None, None
|
188 |
+
|
189 |
+
|
190 |
+
def change_max_input_size(input_size):
|
191 |
+
if model is not None:
|
192 |
+
model.max_input_size = input_size
|
193 |
+
return
|
194 |
+
|
195 |
+
|
196 |
+
block_css = """.importantButton {
|
197 |
+
background: linear-gradient(45deg, #7e0570,#5d1c99, #6e00ff) !important;
|
198 |
+
border: none !important;
|
199 |
+
}
|
200 |
+
.importantButton:hover {
|
201 |
+
background: linear-gradient(45deg, #ff00e0,#8500ff, #6e00ff) !important;
|
202 |
+
border: none !important;
|
203 |
+
}"""
|
204 |
+
|
205 |
+
webui_title = """
|
206 |
+
# 🎉ChatPDF WebUI🎉
|
207 |
+
Link in: [https://github.com/shibing624/ChatPDF](https://github.com/shibing624/ChatPDF) PS: 2核CPU 16G内存机器,约2min一条😭
|
208 |
+
"""
|
209 |
+
|
210 |
+
init_message = """欢迎使用 ChatPDF Web UI,可以直接提问或上传文件后提问 """
|
211 |
+
|
212 |
+
with gr.Blocks(css=block_css) as demo:
|
213 |
+
index_path, file_status, model_status = gr.State(""), gr.State(""), gr.State("")
|
214 |
+
gr.Markdown(webui_title)
|
215 |
+
with gr.Row():
|
216 |
+
with gr.Column(scale=2):
|
217 |
+
chatbot = gr.Chatbot([[None, init_message], [None, None]],
|
218 |
+
elem_id="chat-box",
|
219 |
+
show_label=False).style(height=700)
|
220 |
+
query = gr.Textbox(show_label=False,
|
221 |
+
placeholder="请输入提问内容,按回车进行提交",
|
222 |
+
).style(container=False)
|
223 |
+
clear_btn = gr.Button('🔄Clear!', elem_id='clear').style(full_width=True)
|
224 |
+
with gr.Column(scale=1):
|
225 |
+
llm_model = gr.Radio(llm_model_dict_list,
|
226 |
+
label="LLM 模型",
|
227 |
+
value=list(llm_model_dict.keys())[0],
|
228 |
+
interactive=True)
|
229 |
+
embedding_model = gr.Radio(embedding_model_dict_list,
|
230 |
+
label="Embedding 模型",
|
231 |
+
value=embedding_model_dict_list[0],
|
232 |
+
interactive=True)
|
233 |
+
|
234 |
+
load_model_button = gr.Button("重新加载模型")
|
235 |
+
|
236 |
+
with gr.Row():
|
237 |
+
only_chat = gr.Checkbox(False, label="不加载文件(纯聊天)")
|
238 |
+
|
239 |
+
with gr.Row():
|
240 |
+
topn = gr.Slider(1, 100, 20, step=1, label="最大搜索数量")
|
241 |
+
max_input_size = gr.Slider(512, 4096, MAX_INPUT_LEN, step=10, label="摘要最大长度")
|
242 |
+
with gr.Tab("select"):
|
243 |
+
selectFile = gr.Dropdown(
|
244 |
+
file_list,
|
245 |
+
label="content file",
|
246 |
+
interactive=True,
|
247 |
+
value=file_list[0] if len(file_list) > 0 else None
|
248 |
+
)
|
249 |
+
with gr.Tab("upload"):
|
250 |
+
file = gr.File(
|
251 |
+
label="content file",
|
252 |
+
file_types=['.txt', '.md', '.docx', '.pdf']
|
253 |
+
)
|
254 |
+
load_file_button = gr.Button("加载文件")
|
255 |
+
max_input_size.change(
|
256 |
+
change_max_input_size,
|
257 |
+
inputs=max_input_size
|
258 |
+
)
|
259 |
+
load_model_button.click(
|
260 |
+
reinit_model,
|
261 |
+
show_progress=True,
|
262 |
+
inputs=[llm_model, embedding_model, chatbot],
|
263 |
+
outputs=chatbot
|
264 |
+
)
|
265 |
+
# 将上传的文件保存到content文件夹下,并更新下拉框
|
266 |
+
file.upload(upload_file, inputs=file, outputs=selectFile)
|
267 |
+
load_file_button.click(
|
268 |
+
get_vector_store,
|
269 |
+
show_progress=True,
|
270 |
+
inputs=[selectFile, chatbot, embedding_model],
|
271 |
+
outputs=[index_path, chatbot],
|
272 |
+
)
|
273 |
+
query.submit(
|
274 |
+
get_answer,
|
275 |
+
[query, index_path, chatbot, topn, max_input_size, only_chat],
|
276 |
+
[chatbot, query],
|
277 |
+
)
|
278 |
+
clear_btn.click(reset_chat, [chatbot, query], [chatbot, query])
|
279 |
+
|
280 |
+
demo.queue(concurrency_count=3).launch(
|
281 |
+
server_name='0.0.0.0', share=False, inbrowser=False
|
282 |
+
)
|
chatpdf.py
ADDED
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
"""
|
3 |
+
@author:XuMing([email protected])
|
4 |
+
@description:
|
5 |
+
"""
|
6 |
+
from similarities import Similarity
|
7 |
+
from textgen import ChatGlmModel, LlamaModel
|
8 |
+
|
9 |
+
PROMPT_TEMPLATE = """\
|
10 |
+
基于以下已知信息,简洁和专业的来回答用户的问题。
|
11 |
+
如果无法从中得到答案,请说 "根据已知信息无法回答该问题" 或 "没有提供足够的相关信息",不允许在答案中添加编造成分,答案请使用中文。
|
12 |
+
|
13 |
+
已知内容:
|
14 |
+
{context_str}
|
15 |
+
|
16 |
+
问题:
|
17 |
+
{query_str}
|
18 |
+
"""
|
19 |
+
|
20 |
+
|
21 |
+
class ChatPDF:
|
22 |
+
def __init__(
|
23 |
+
self,
|
24 |
+
sim_model_name_or_path: str = "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2",
|
25 |
+
gen_model_type: str = "chatglm",
|
26 |
+
gen_model_name_or_path: str = "THUDM/chatglm-6b-int4",
|
27 |
+
lora_model_name_or_path: str = None,
|
28 |
+
|
29 |
+
):
|
30 |
+
self.sim_model = Similarity(model_name_or_path=sim_model_name_or_path)
|
31 |
+
|
32 |
+
if gen_model_type == "chatglm":
|
33 |
+
self.gen_model = ChatGlmModel(gen_model_type, gen_model_name_or_path, lora_name=lora_model_name_or_path)
|
34 |
+
elif gen_model_type == "llama":
|
35 |
+
self.gen_model = LlamaModel(gen_model_type, gen_model_name_or_path, lora_name=lora_model_name_or_path)
|
36 |
+
else:
|
37 |
+
raise ValueError('gen_model_type must be chatglm or llama.')
|
38 |
+
self.history = None
|
39 |
+
self.pdf_path = None
|
40 |
+
|
41 |
+
def load_pdf_file(self, pdf_path: str):
|
42 |
+
"""Load a PDF file."""
|
43 |
+
if pdf_path.endswith('.pdf'):
|
44 |
+
corpus = self.extract_text_from_pdf(pdf_path)
|
45 |
+
elif pdf_path.endswith('.docx'):
|
46 |
+
corpus = self.extract_text_from_docx(pdf_path)
|
47 |
+
elif pdf_path.endswith('.md'):
|
48 |
+
corpus = self.extract_text_from_markdown(pdf_path)
|
49 |
+
else:
|
50 |
+
corpus = self.extract_text_from_txt(pdf_path)
|
51 |
+
self.sim_model.add_corpus(corpus)
|
52 |
+
self.pdf_path = pdf_path
|
53 |
+
|
54 |
+
@staticmethod
|
55 |
+
def extract_text_from_pdf(file_path: str):
|
56 |
+
"""Extract text content from a PDF file."""
|
57 |
+
import PyPDF2
|
58 |
+
contents = []
|
59 |
+
with open(file_path, 'rb') as f:
|
60 |
+
pdf_reader = PyPDF2.PdfReader(f)
|
61 |
+
for page in pdf_reader.pages:
|
62 |
+
page_text = page.extract_text().strip()
|
63 |
+
raw_text = [text.strip() for text in page_text.splitlines() if text.strip()]
|
64 |
+
new_text = ''
|
65 |
+
for text in raw_text:
|
66 |
+
new_text += text
|
67 |
+
if text[-1] in ['.', '!', '?', '。', '!', '?', '…', ';', ';', ':', ':', '”', '’', ')', '】', '》', '」',
|
68 |
+
'』', '〕', '〉', '》', '〗', '〞', '〟', '»', '"', "'", ')', ']', '}']:
|
69 |
+
contents.append(new_text)
|
70 |
+
new_text = ''
|
71 |
+
if new_text:
|
72 |
+
contents.append(new_text)
|
73 |
+
return contents
|
74 |
+
|
75 |
+
@staticmethod
|
76 |
+
def extract_text_from_txt(file_path: str):
|
77 |
+
"""Extract text content from a TXT file."""
|
78 |
+
contents = []
|
79 |
+
with open(file_path, 'r', encoding='utf-8') as f:
|
80 |
+
contents = [text.strip() for text in f.readlines() if text.strip()]
|
81 |
+
return contents
|
82 |
+
|
83 |
+
@staticmethod
|
84 |
+
def extract_text_from_docx(file_path: str):
|
85 |
+
"""Extract text content from a DOCX file."""
|
86 |
+
import docx
|
87 |
+
document = docx.Document(file_path)
|
88 |
+
contents = [paragraph.text.strip() for paragraph in document.paragraphs if paragraph.text.strip()]
|
89 |
+
return contents
|
90 |
+
|
91 |
+
@staticmethod
|
92 |
+
def extract_text_from_markdown(file_path: str):
|
93 |
+
"""Extract text content from a Markdown file."""
|
94 |
+
import markdown
|
95 |
+
from bs4 import BeautifulSoup
|
96 |
+
with open(file_path, 'r', encoding='utf-8') as f:
|
97 |
+
markdown_text = f.read()
|
98 |
+
html = markdown.markdown(markdown_text)
|
99 |
+
soup = BeautifulSoup(html, 'html.parser')
|
100 |
+
contents = [text.strip() for text in soup.get_text().splitlines() if text.strip()]
|
101 |
+
return contents
|
102 |
+
|
103 |
+
@staticmethod
|
104 |
+
def _add_source_numbers(lst):
|
105 |
+
"""Add source numbers to a list of strings."""
|
106 |
+
return [f'[{idx + 1}]\t "{item}"' for idx, item in enumerate(lst)]
|
107 |
+
|
108 |
+
def _generate_answer(self, query_str, context_str, history=None, max_length=1024):
|
109 |
+
"""Generate answer from query and context."""
|
110 |
+
prompt = PROMPT_TEMPLATE.format(context_str=context_str, query_str=query_str)
|
111 |
+
response, out_history = self.gen_model.chat(prompt, history, max_length=max_length)
|
112 |
+
return response, out_history
|
113 |
+
|
114 |
+
def query(
|
115 |
+
self,
|
116 |
+
query,
|
117 |
+
topn: int = 5,
|
118 |
+
max_length: int = 1024,
|
119 |
+
max_input_size: int = 1024,
|
120 |
+
use_history: bool = False
|
121 |
+
):
|
122 |
+
"""Query from corpus."""
|
123 |
+
|
124 |
+
sim_contents = self.sim_model.most_similar(query, topn=topn)
|
125 |
+
|
126 |
+
reference_results = []
|
127 |
+
for query_id, id_score_dict in sim_contents.items():
|
128 |
+
for corpus_id, s in id_score_dict.items():
|
129 |
+
reference_results.append(self.sim_model.corpus[corpus_id])
|
130 |
+
if not reference_results:
|
131 |
+
return '没有提供足够的相关信息', reference_results
|
132 |
+
reference_results = self._add_source_numbers(reference_results)
|
133 |
+
|
134 |
+
context_str = '\n'.join(reference_results)[:(max_input_size - len(PROMPT_TEMPLATE))]
|
135 |
+
|
136 |
+
if use_history:
|
137 |
+
response, out_history = self._generate_answer(query, context_str, self.history, max_length=max_length)
|
138 |
+
self.history = out_history
|
139 |
+
else:
|
140 |
+
|
141 |
+
response, out_history = self._generate_answer(query, context_str)
|
142 |
+
|
143 |
+
return response, out_history, reference_results
|
144 |
+
|
145 |
+
def save_index(self, index_path=None):
|
146 |
+
"""Save model."""
|
147 |
+
if index_path is None:
|
148 |
+
index_path = '.'.join(self.pdf_path.split('.')[:-1]) + '_index.json'
|
149 |
+
self.sim_model.save_index(index_path)
|
150 |
+
|
151 |
+
def load_index(self, index_path=None):
|
152 |
+
"""Load model."""
|
153 |
+
if index_path is None:
|
154 |
+
index_path = '.'.join(self.pdf_path.split('.')[:-1]) + '_index.json'
|
155 |
+
self.sim_model.load_index(index_path)
|
156 |
+
|
157 |
+
|
158 |
+
if __name__ == "__main__":
|
159 |
+
import sys
|
160 |
+
|
161 |
+
if len(sys.argv) > 2:
|
162 |
+
gen_model_name_or_path = sys.argv[1]
|
163 |
+
else:
|
164 |
+
print('Usage: python chatpdf.py <gen_model_name_or_path>')
|
165 |
+
gen_model_name_or_path = "THUDM/chatglm-6b-int4"
|
166 |
+
m = ChatPDF(gen_model_name_or_path=gen_model_name_or_path)
|
167 |
+
m.load_pdf_file(pdf_path='sample.pdf')
|
168 |
+
response = m.query('自然语言中的非平行迁移是指什么?')
|
169 |
+
print(response[0])
|
170 |
+
response = m.query('本文作者是谁?')
|
171 |
+
print(response[0])
|
requirements.txt
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
gradio
|
2 |
+
similarities
|
3 |
+
sentencepiece
|
4 |
+
textgen
|
5 |
+
markdown
|
6 |
+
PyPDF2
|
7 |
+
python-docx
|
8 |
+
pandas
|
9 |
+
protobuf
|
10 |
+
cpm-kernels
|
11 |
+
loguru
|
sample.pdf
ADDED
Binary file (375 kB). View file
|
|