Commit
•
4479cfa
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 +310 -0
- chatpdf.py +296 -0
- requirements.txt +16 -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,310 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 argparse
|
8 |
+
import hashlib
|
9 |
+
import os
|
10 |
+
import shutil
|
11 |
+
|
12 |
+
import gradio as gr
|
13 |
+
from loguru import logger
|
14 |
+
|
15 |
+
from chatpdf import ChatPDF
|
16 |
+
|
17 |
+
pwd_path = os.path.abspath(os.path.dirname(__file__))
|
18 |
+
|
19 |
+
CONTENT_DIR = os.path.join(pwd_path, "content")
|
20 |
+
logger.info(f"CONTENT_DIR: {CONTENT_DIR}")
|
21 |
+
VECTOR_SEARCH_TOP_K = 3
|
22 |
+
MAX_INPUT_LEN = 2048
|
23 |
+
|
24 |
+
embedding_model_dict = {
|
25 |
+
"text2vec-base": "shibing624/text2vec-base-chinese",
|
26 |
+
"text2vec-multilingual": "shibing624/text2vec-base-multilingual",
|
27 |
+
"text2vec-large": "GanymedeNil/text2vec-large-chinese",
|
28 |
+
"sentence-transformers": "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2",
|
29 |
+
"ernie-tiny": "nghuyong/ernie-3.0-nano-zh",
|
30 |
+
"ernie-base": "nghuyong/ernie-3.0-base-zh",
|
31 |
+
}
|
32 |
+
|
33 |
+
# supported LLM models
|
34 |
+
llm_model_dict = {
|
35 |
+
"llama-2-7b": "LinkSoul/Chinese-Llama-2-7b-4bit",
|
36 |
+
"baichuan-13b-chat": "baichuan-inc/Baichuan-13B-Chat",
|
37 |
+
"chatglm-6b-int4-qe": "THUDM/chatglm-6b-int4-qe",
|
38 |
+
"chatglm-2-6b": "THUDM/chatglm2-6b",
|
39 |
+
"chatglm-2-6b-int4": "THUDM/chatglm2-6b-int4",
|
40 |
+
"chatglm-6b-int4": "THUDM/chatglm-6b-int4",
|
41 |
+
"chatglm-6b": "THUDM/chatglm-6b",
|
42 |
+
"llama-7b": "shibing624/chinese-alpaca-plus-7b-hf",
|
43 |
+
"llama-13b": "shibing624/chinese-alpaca-plus-13b-hf",
|
44 |
+
}
|
45 |
+
|
46 |
+
llm_model_dict_list = list(llm_model_dict.keys())
|
47 |
+
embedding_model_dict_list = list(embedding_model_dict.keys())
|
48 |
+
|
49 |
+
parser = argparse.ArgumentParser()
|
50 |
+
parser.add_argument("--sim_model", type=str, default="shibing624/text2vec-base-chinese")
|
51 |
+
parser.add_argument("--gen_model_type", type=str, default="llama")
|
52 |
+
parser.add_argument("--gen_model", type=str, default="LinkSoul/Chinese-Llama-2-7b-4bit")
|
53 |
+
parser.add_argument("--lora_model", type=str, default=None)
|
54 |
+
parser.add_argument("--device", type=str, default="cpu")
|
55 |
+
parser.add_argument("--int4", action='store_true', help="use int4 quantization")
|
56 |
+
parser.add_argument("--int8", action='store_true', help="use int8 quantization")
|
57 |
+
args = parser.parse_args()
|
58 |
+
print(args)
|
59 |
+
|
60 |
+
model = None
|
61 |
+
|
62 |
+
|
63 |
+
def get_file_list():
|
64 |
+
if not os.path.exists("content"):
|
65 |
+
return []
|
66 |
+
return [f for f in os.listdir("content") if
|
67 |
+
f.endswith(".txt") or f.endswith(".pdf") or f.endswith(".docx") or f.endswith(".md")]
|
68 |
+
|
69 |
+
|
70 |
+
file_list = get_file_list()
|
71 |
+
|
72 |
+
|
73 |
+
def upload_file(file):
|
74 |
+
if not os.path.exists(CONTENT_DIR):
|
75 |
+
os.mkdir(CONTENT_DIR)
|
76 |
+
filename = os.path.basename(file.name)
|
77 |
+
shutil.move(file.name, os.path.join(CONTENT_DIR, filename))
|
78 |
+
# file_list首位插入新上传的文件
|
79 |
+
file_list.insert(0, filename)
|
80 |
+
return gr.Dropdown.update(choices=file_list, value=filename)
|
81 |
+
|
82 |
+
|
83 |
+
def parse_text(text):
|
84 |
+
"""copy from https://github.com/GaiZhenbiao/ChuanhuChatGPT/"""
|
85 |
+
lines = text.split("\n")
|
86 |
+
lines = [line for line in lines if line != ""]
|
87 |
+
count = 0
|
88 |
+
for i, line in enumerate(lines):
|
89 |
+
if "```" in line:
|
90 |
+
count += 1
|
91 |
+
items = line.split('`')
|
92 |
+
if count % 2 == 1:
|
93 |
+
lines[i] = f'<pre><code class="language-{items[-1]}">'
|
94 |
+
else:
|
95 |
+
lines[i] = f'<br></code></pre>'
|
96 |
+
else:
|
97 |
+
if i > 0:
|
98 |
+
if count % 2 == 1:
|
99 |
+
line = line.replace("`", "\`")
|
100 |
+
line = line.replace("<", "<")
|
101 |
+
line = line.replace(">", ">")
|
102 |
+
line = line.replace(" ", " ")
|
103 |
+
line = line.replace("*", "*")
|
104 |
+
line = line.replace("_", "_")
|
105 |
+
line = line.replace("-", "-")
|
106 |
+
line = line.replace(".", ".")
|
107 |
+
line = line.replace("!", "!")
|
108 |
+
line = line.replace("(", "(")
|
109 |
+
line = line.replace(")", ")")
|
110 |
+
line = line.replace("$", "$")
|
111 |
+
lines[i] = "<br>" + line
|
112 |
+
text = "".join(lines)
|
113 |
+
return text
|
114 |
+
|
115 |
+
|
116 |
+
def get_answer(query, index_path, history, topn=VECTOR_SEARCH_TOP_K, max_input_size=1024, only_chat=False):
|
117 |
+
if model is None:
|
118 |
+
return [None, "模型还未加载"], query
|
119 |
+
if index_path and not only_chat:
|
120 |
+
if not model.sim_model.corpus_embeddings:
|
121 |
+
model.load_index(index_path)
|
122 |
+
response, reference_results = model.predict(
|
123 |
+
query=query, topn=topn, context_len=max_input_size)
|
124 |
+
|
125 |
+
logger.debug(f"query: {query}, response with content: {response}")
|
126 |
+
for i in range(len(reference_results)):
|
127 |
+
r = reference_results[i]
|
128 |
+
response += f"\n{r.strip()}"
|
129 |
+
response = parse_text(response)
|
130 |
+
history = history + [[query, response]]
|
131 |
+
else:
|
132 |
+
# 未加载文件,仅返回生成模型结果
|
133 |
+
instruction = """[INST] <<SYS>>\nYou are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.
|
134 |
+
|
135 |
+
If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.\n<</SYS>>\n\n{} [/INST]"""
|
136 |
+
if args.gen_model_type == "llama":
|
137 |
+
query = instruction.format(query)
|
138 |
+
model.history.append([query, ''])
|
139 |
+
response = ""
|
140 |
+
for new_text in model.stream_generate_answer(query, context_len=max_input_size):
|
141 |
+
response += new_text
|
142 |
+
response = response.strip()
|
143 |
+
model.history[-1][1] = response
|
144 |
+
response = parse_text(response)
|
145 |
+
history = history + [[query, response]]
|
146 |
+
logger.debug(f"query: {query}, response: {response}")
|
147 |
+
return history, ""
|
148 |
+
|
149 |
+
|
150 |
+
def update_status(history, status):
|
151 |
+
history = history + [[None, status]]
|
152 |
+
logger.info(status)
|
153 |
+
return history
|
154 |
+
|
155 |
+
|
156 |
+
def reinit_model(llm_model, embedding_model, history):
|
157 |
+
try:
|
158 |
+
global model
|
159 |
+
if model is not None:
|
160 |
+
del model
|
161 |
+
|
162 |
+
model = ChatPDF(
|
163 |
+
sim_model_name_or_path=embedding_model_dict.get(
|
164 |
+
embedding_model,
|
165 |
+
"shibing624/text2vec-base-chinese"
|
166 |
+
),
|
167 |
+
gen_model_type=llm_model.split('-')[0],
|
168 |
+
gen_model_name_or_path=llm_model_dict.get(llm_model, "LinkSoul/Chinese-Llama-2-7b-4bit"),
|
169 |
+
lora_model_name_or_path=None,
|
170 |
+
)
|
171 |
+
|
172 |
+
model_status = """模型已成功重新加载,请选择文件后点击"加载文件"按钮"""
|
173 |
+
except Exception as e:
|
174 |
+
model = None
|
175 |
+
logger.error(e)
|
176 |
+
model_status = """模型未成功重新加载,请重新选择后点击"加载模型"按钮"""
|
177 |
+
return history + [[None, model_status]]
|
178 |
+
|
179 |
+
|
180 |
+
def get_file_hash(fpath):
|
181 |
+
return hashlib.md5(open(fpath, 'rb').read()).hexdigest()
|
182 |
+
|
183 |
+
|
184 |
+
def get_vector_store(filepath, history, embedding_model):
|
185 |
+
logger.info(filepath, history)
|
186 |
+
index_path = None
|
187 |
+
file_status = ''
|
188 |
+
if model is not None:
|
189 |
+
|
190 |
+
local_file_path = os.path.join(CONTENT_DIR, filepath)
|
191 |
+
|
192 |
+
local_file_hash = get_file_hash(local_file_path)
|
193 |
+
index_file_name = f"{filepath}.{embedding_model}.{local_file_hash}.index.json"
|
194 |
+
|
195 |
+
local_index_path = os.path.join(CONTENT_DIR, index_file_name)
|
196 |
+
|
197 |
+
if os.path.exists(local_index_path):
|
198 |
+
model.load_index(local_index_path)
|
199 |
+
index_path = local_index_path
|
200 |
+
file_status = "文件已成功加载,请开始提问"
|
201 |
+
|
202 |
+
elif os.path.exists(local_file_path):
|
203 |
+
model.load_doc_files(local_file_path)
|
204 |
+
model.save_index(local_index_path)
|
205 |
+
index_path = local_index_path
|
206 |
+
if index_path:
|
207 |
+
file_status = "文件索引并成功加载,请开始提问"
|
208 |
+
else:
|
209 |
+
file_status = "文件未成功加载,请重新上传文件"
|
210 |
+
else:
|
211 |
+
file_status = "模型未完成加载,请先在加载模型后再导入文件"
|
212 |
+
|
213 |
+
return index_path, history + [[None, file_status]]
|
214 |
+
|
215 |
+
|
216 |
+
def reset_chat(chatbot, state):
|
217 |
+
return None, None
|
218 |
+
|
219 |
+
|
220 |
+
def change_max_input_size(input_size):
|
221 |
+
if model is not None:
|
222 |
+
model.max_input_size = input_size
|
223 |
+
return
|
224 |
+
|
225 |
+
|
226 |
+
block_css = """.importantButton {
|
227 |
+
background: linear-gradient(45deg, #7e0570,#5d1c99, #6e00ff) !important;
|
228 |
+
border: none !important;
|
229 |
+
}
|
230 |
+
.importantButton:hover {
|
231 |
+
background: linear-gradient(45deg, #ff00e0,#8500ff, #6e00ff) !important;
|
232 |
+
border: none !important;
|
233 |
+
}"""
|
234 |
+
|
235 |
+
webui_title = """
|
236 |
+
# 🎉ChatPDF WebUI🎉
|
237 |
+
Link in: [https://github.com/shibing624/ChatPDF](https://github.com/shibing624/ChatPDF) PS: 2核CPU 16G内存机器,约2min一条😭
|
238 |
+
"""
|
239 |
+
|
240 |
+
init_message = """欢迎使用 ChatPDF Web UI,可以直接提问或上传文件后提问 """
|
241 |
+
|
242 |
+
with gr.Blocks(css=block_css) as demo:
|
243 |
+
index_path, file_status, model_status = gr.State(""), gr.State(""), gr.State("")
|
244 |
+
gr.Markdown(webui_title)
|
245 |
+
with gr.Row():
|
246 |
+
with gr.Column(scale=2):
|
247 |
+
chatbot = gr.Chatbot([[None, init_message], [None, None]],
|
248 |
+
elem_id="chat-box",
|
249 |
+
show_label=False).style(height=700)
|
250 |
+
query = gr.Textbox(show_label=False,
|
251 |
+
placeholder="请输入提问内容,按回车进行提交",
|
252 |
+
).style(container=False)
|
253 |
+
clear_btn = gr.Button('🔄Clear!', elem_id='clear').style(full_width=True)
|
254 |
+
with gr.Column(scale=1):
|
255 |
+
llm_model = gr.Radio(llm_model_dict_list,
|
256 |
+
label="LLM 模型",
|
257 |
+
value=list(llm_model_dict.keys())[0],
|
258 |
+
interactive=True)
|
259 |
+
embedding_model = gr.Radio(embedding_model_dict_list,
|
260 |
+
label="Embedding 模型",
|
261 |
+
value=embedding_model_dict_list[0],
|
262 |
+
interactive=True)
|
263 |
+
|
264 |
+
load_model_button = gr.Button("重新加载模型")
|
265 |
+
|
266 |
+
with gr.Row():
|
267 |
+
only_chat = gr.Checkbox(False, label="不加载文件(纯聊天)")
|
268 |
+
|
269 |
+
with gr.Row():
|
270 |
+
topn = gr.Slider(1, 100, 20, step=1, label="最大搜索数量")
|
271 |
+
max_input_size = gr.Slider(512, 4096, MAX_INPUT_LEN, step=10, label="摘要最大长度")
|
272 |
+
with gr.Tab("select"):
|
273 |
+
selectFile = gr.Dropdown(
|
274 |
+
file_list,
|
275 |
+
label="content file",
|
276 |
+
interactive=True,
|
277 |
+
value=file_list[0] if len(file_list) > 0 else None
|
278 |
+
)
|
279 |
+
with gr.Tab("upload"):
|
280 |
+
file = gr.File(
|
281 |
+
label="content file",
|
282 |
+
file_types=['.txt', '.md', '.docx', '.pdf']
|
283 |
+
)
|
284 |
+
load_file_button = gr.Button("加载文件")
|
285 |
+
max_input_size.change(
|
286 |
+
change_max_input_size,
|
287 |
+
inputs=max_input_size
|
288 |
+
)
|
289 |
+
load_model_button.click(
|
290 |
+
reinit_model,
|
291 |
+
show_progress=True,
|
292 |
+
inputs=[llm_model, embedding_model, chatbot],
|
293 |
+
outputs=chatbot
|
294 |
+
)
|
295 |
+
# 将上传的文件保存到content文件夹下,并更新下拉框
|
296 |
+
file.upload(upload_file, inputs=file, outputs=selectFile)
|
297 |
+
load_file_button.click(
|
298 |
+
get_vector_store,
|
299 |
+
show_progress=True,
|
300 |
+
inputs=[selectFile, chatbot, embedding_model],
|
301 |
+
outputs=[index_path, chatbot],
|
302 |
+
)
|
303 |
+
query.submit(
|
304 |
+
get_answer,
|
305 |
+
[query, index_path, chatbot, topn, max_input_size, only_chat],
|
306 |
+
[chatbot, query],
|
307 |
+
)
|
308 |
+
clear_btn.click(reset_chat, [chatbot, query], [chatbot, query])
|
309 |
+
|
310 |
+
demo.queue(concurrency_count=3).launch()
|
chatpdf.py
ADDED
@@ -0,0 +1,296 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
"""
|
3 |
+
@author:XuMing([email protected])
|
4 |
+
@description:
|
5 |
+
"""
|
6 |
+
import argparse
|
7 |
+
from threading import Thread
|
8 |
+
from typing import Union, List
|
9 |
+
|
10 |
+
import torch
|
11 |
+
from loguru import logger
|
12 |
+
from peft import PeftModel
|
13 |
+
from similarities import Similarity
|
14 |
+
from transformers import (
|
15 |
+
AutoModel,
|
16 |
+
AutoModelForCausalLM,
|
17 |
+
AutoTokenizer,
|
18 |
+
BloomForCausalLM,
|
19 |
+
BloomTokenizerFast,
|
20 |
+
LlamaTokenizer,
|
21 |
+
LlamaForCausalLM,
|
22 |
+
TextIteratorStreamer,
|
23 |
+
GenerationConfig,
|
24 |
+
)
|
25 |
+
|
26 |
+
MODEL_CLASSES = {
|
27 |
+
"bloom": (BloomForCausalLM, BloomTokenizerFast),
|
28 |
+
"chatglm": (AutoModel, AutoTokenizer),
|
29 |
+
"llama": (LlamaForCausalLM, LlamaTokenizer),
|
30 |
+
"baichuan": (AutoModelForCausalLM, AutoTokenizer),
|
31 |
+
"auto": (AutoModelForCausalLM, AutoTokenizer),
|
32 |
+
}
|
33 |
+
|
34 |
+
LLAMA_TEMPLATE = """[INST] <<SYS>>\nYou are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.
|
35 |
+
|
36 |
+
If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.\n<</SYS>>\n\n"""
|
37 |
+
|
38 |
+
PROMPT_TEMPLATE = """基于以下已知信息,简洁和专业的来回答用户的问题。
|
39 |
+
如果无法从中得到答案,请说 "根据已知信息无法回答该问题" 或 "没有提供足够的相关信息",不允许在答案中添加编造成分,答案请使用中文。
|
40 |
+
|
41 |
+
已知内容:
|
42 |
+
{context_str}
|
43 |
+
|
44 |
+
问题:
|
45 |
+
{query_str}
|
46 |
+
"""
|
47 |
+
|
48 |
+
|
49 |
+
class ChatPDF:
|
50 |
+
def __init__(
|
51 |
+
self,
|
52 |
+
sim_model_name_or_path: str = "shibing624/text2vec-base-chinese",
|
53 |
+
gen_model_type: str = "baichuan",
|
54 |
+
gen_model_name_or_path: str = "baichuan-inc/Baichuan-13B-Chat",
|
55 |
+
lora_model_name_or_path: str = None,
|
56 |
+
device: str = None,
|
57 |
+
int8: bool = False,
|
58 |
+
int4: bool = False,
|
59 |
+
):
|
60 |
+
default_device = torch.device('cpu')
|
61 |
+
if torch.cuda.is_available():
|
62 |
+
default_device = torch.device(0)
|
63 |
+
elif torch.backends.mps.is_available():
|
64 |
+
default_device = 'mps'
|
65 |
+
self.device = device or default_device
|
66 |
+
self.sim_model = Similarity(model_name_or_path=sim_model_name_or_path, device=self.device)
|
67 |
+
self.gen_model, self.tokenizer = self._init_gen_model(
|
68 |
+
gen_model_type,
|
69 |
+
gen_model_name_or_path,
|
70 |
+
peft_name=lora_model_name_or_path,
|
71 |
+
int8=int8,
|
72 |
+
int4=int4,
|
73 |
+
)
|
74 |
+
self.history = []
|
75 |
+
self.doc_files = None
|
76 |
+
|
77 |
+
def _init_gen_model(
|
78 |
+
self,
|
79 |
+
gen_model_type: str,
|
80 |
+
gen_model_name_or_path: str,
|
81 |
+
peft_name: str = None,
|
82 |
+
int8: bool = False,
|
83 |
+
int4: bool = False,
|
84 |
+
):
|
85 |
+
"""Init generate model."""
|
86 |
+
if int8 or int4:
|
87 |
+
device_map = None
|
88 |
+
else:
|
89 |
+
device_map = "auto"
|
90 |
+
model_class, tokenizer_class = MODEL_CLASSES[gen_model_type]
|
91 |
+
tokenizer = tokenizer_class.from_pretrained(gen_model_name_or_path, trust_remote_code=True)
|
92 |
+
model = model_class.from_pretrained(
|
93 |
+
gen_model_name_or_path,
|
94 |
+
load_in_8bit=int8 if gen_model_type not in ['baichuan', 'chatglm'] else False,
|
95 |
+
load_in_4bit=int4 if gen_model_type not in ['baichuan', 'chatglm'] else False,
|
96 |
+
torch_dtype=torch.float16,
|
97 |
+
low_cpu_mem_usage=True,
|
98 |
+
device_map=device_map,
|
99 |
+
trust_remote_code=True,
|
100 |
+
)
|
101 |
+
if self.device == torch.device('cpu'):
|
102 |
+
model.float()
|
103 |
+
if gen_model_type in ['baichuan', 'chatglm']:
|
104 |
+
if int4:
|
105 |
+
model = model.quantize(4).cuda()
|
106 |
+
elif int8:
|
107 |
+
model = model.quantize(8).cuda()
|
108 |
+
try:
|
109 |
+
model.generation_config = GenerationConfig.from_pretrained(gen_model_name_or_path, trust_remote_code=True)
|
110 |
+
except Exception as e:
|
111 |
+
logger.warning(f"Failed to load generation config from {gen_model_name_or_path}, {e}")
|
112 |
+
if peft_name:
|
113 |
+
model = PeftModel.from_pretrained(
|
114 |
+
model,
|
115 |
+
peft_name,
|
116 |
+
torch_dtype=torch.float16,
|
117 |
+
)
|
118 |
+
logger.info(f"Loaded peft model from {peft_name}")
|
119 |
+
model.eval()
|
120 |
+
return model, tokenizer
|
121 |
+
|
122 |
+
@torch.inference_mode()
|
123 |
+
def stream_generate_answer(
|
124 |
+
self,
|
125 |
+
prompt,
|
126 |
+
max_new_tokens=512,
|
127 |
+
temperature=0.7,
|
128 |
+
repetition_penalty=1.0,
|
129 |
+
context_len=2048
|
130 |
+
):
|
131 |
+
streamer = TextIteratorStreamer(self.tokenizer, timeout=60.0, skip_prompt=True, skip_special_tokens=True)
|
132 |
+
input_ids = self.tokenizer(prompt).input_ids
|
133 |
+
max_src_len = context_len - max_new_tokens - 8
|
134 |
+
input_ids = input_ids[-max_src_len:]
|
135 |
+
generation_kwargs = dict(
|
136 |
+
input_ids=torch.as_tensor([input_ids]).to(self.device),
|
137 |
+
max_new_tokens=max_new_tokens,
|
138 |
+
temperature=temperature,
|
139 |
+
repetition_penalty=repetition_penalty,
|
140 |
+
streamer=streamer,
|
141 |
+
)
|
142 |
+
thread = Thread(target=self.gen_model.generate, kwargs=generation_kwargs)
|
143 |
+
thread.start()
|
144 |
+
|
145 |
+
yield from streamer
|
146 |
+
|
147 |
+
def load_doc_files(self, doc_files: Union[str, List[str]]):
|
148 |
+
"""Load document files."""
|
149 |
+
if isinstance(doc_files, str):
|
150 |
+
doc_files = [doc_files]
|
151 |
+
for doc_file in doc_files:
|
152 |
+
if doc_file.endswith('.pdf'):
|
153 |
+
corpus = self.extract_text_from_pdf(doc_file)
|
154 |
+
elif doc_file.endswith('.docx'):
|
155 |
+
corpus = self.extract_text_from_docx(doc_file)
|
156 |
+
elif doc_file.endswith('.md'):
|
157 |
+
corpus = self.extract_text_from_markdown(doc_file)
|
158 |
+
else:
|
159 |
+
corpus = self.extract_text_from_txt(doc_file)
|
160 |
+
self.sim_model.add_corpus(corpus)
|
161 |
+
self.doc_files = doc_files
|
162 |
+
|
163 |
+
@staticmethod
|
164 |
+
def extract_text_from_pdf(file_path: str):
|
165 |
+
"""Extract text content from a PDF file."""
|
166 |
+
import PyPDF2
|
167 |
+
contents = []
|
168 |
+
with open(file_path, 'rb') as f:
|
169 |
+
pdf_reader = PyPDF2.PdfReader(f)
|
170 |
+
for page in pdf_reader.pages:
|
171 |
+
page_text = page.extract_text().strip()
|
172 |
+
raw_text = [text.strip() for text in page_text.splitlines() if text.strip()]
|
173 |
+
new_text = ''
|
174 |
+
for text in raw_text:
|
175 |
+
new_text += text
|
176 |
+
if text[-1] in ['.', '!', '?', '。', '!', '?', '…', ';', ';', ':', ':', '”', '’', ')', '】', '》', '」',
|
177 |
+
'』', '〕', '〉', '》', '〗', '〞', '〟', '»', '"', "'", ')', ']', '}']:
|
178 |
+
contents.append(new_text)
|
179 |
+
new_text = ''
|
180 |
+
if new_text:
|
181 |
+
contents.append(new_text)
|
182 |
+
return contents
|
183 |
+
|
184 |
+
@staticmethod
|
185 |
+
def extract_text_from_txt(file_path: str):
|
186 |
+
"""Extract text content from a TXT file."""
|
187 |
+
contents = []
|
188 |
+
with open(file_path, 'r', encoding='utf-8') as f:
|
189 |
+
contents = [text.strip() for text in f.readlines() if text.strip()]
|
190 |
+
return contents
|
191 |
+
|
192 |
+
@staticmethod
|
193 |
+
def extract_text_from_docx(file_path: str):
|
194 |
+
"""Extract text content from a DOCX file."""
|
195 |
+
import docx
|
196 |
+
document = docx.Document(file_path)
|
197 |
+
contents = [paragraph.text.strip() for paragraph in document.paragraphs if paragraph.text.strip()]
|
198 |
+
return contents
|
199 |
+
|
200 |
+
@staticmethod
|
201 |
+
def extract_text_from_markdown(file_path: str):
|
202 |
+
"""Extract text content from a Markdown file."""
|
203 |
+
import markdown
|
204 |
+
from bs4 import BeautifulSoup
|
205 |
+
with open(file_path, 'r', encoding='utf-8') as f:
|
206 |
+
markdown_text = f.read()
|
207 |
+
html = markdown.markdown(markdown_text)
|
208 |
+
soup = BeautifulSoup(html, 'html.parser')
|
209 |
+
contents = [text.strip() for text in soup.get_text().splitlines() if text.strip()]
|
210 |
+
return contents
|
211 |
+
|
212 |
+
@staticmethod
|
213 |
+
def _add_source_numbers(lst):
|
214 |
+
"""Add source numbers to a list of strings."""
|
215 |
+
return [f'[{idx + 1}]\t "{item}"' for idx, item in enumerate(lst)]
|
216 |
+
|
217 |
+
def predict(
|
218 |
+
self,
|
219 |
+
query: str,
|
220 |
+
topn: int = 5,
|
221 |
+
max_length: int = 512,
|
222 |
+
context_len: int = 2048,
|
223 |
+
temperature: float = 0.7,
|
224 |
+
do_print: bool = True,
|
225 |
+
):
|
226 |
+
"""Query from corpus."""
|
227 |
+
|
228 |
+
sim_contents = self.sim_model.most_similar(query, topn=topn)
|
229 |
+
|
230 |
+
reference_results = []
|
231 |
+
for query_id, id_score_dict in sim_contents.items():
|
232 |
+
for corpus_id, s in id_score_dict.items():
|
233 |
+
reference_results.append(self.sim_model.corpus[corpus_id])
|
234 |
+
if not reference_results:
|
235 |
+
return '没有提供足够的相关信息', reference_results
|
236 |
+
reference_results = self._add_source_numbers(reference_results)
|
237 |
+
context_str = '\n'.join(reference_results)[:(context_len - len(PROMPT_TEMPLATE))]
|
238 |
+
|
239 |
+
prompt = PROMPT_TEMPLATE.format(context_str=context_str, query_str=query)
|
240 |
+
self.history.append([prompt, ''])
|
241 |
+
response = ""
|
242 |
+
for new_text in self.stream_generate_answer(
|
243 |
+
prompt,
|
244 |
+
max_new_tokens=max_length,
|
245 |
+
temperature=temperature,
|
246 |
+
context_len=context_len,
|
247 |
+
):
|
248 |
+
response += new_text
|
249 |
+
if do_print:
|
250 |
+
print(new_text, end="", flush=True)
|
251 |
+
if do_print:
|
252 |
+
print("", flush=True)
|
253 |
+
response = response.strip()
|
254 |
+
self.history[-1][1] = response
|
255 |
+
return response, reference_results
|
256 |
+
|
257 |
+
def save_index(self, index_path=None):
|
258 |
+
"""Save model."""
|
259 |
+
if index_path is None:
|
260 |
+
index_path = '.'.join(self.doc_files.split('.')[:-1]) + '_index.json'
|
261 |
+
self.sim_model.save_index(index_path)
|
262 |
+
|
263 |
+
def load_index(self, index_path=None):
|
264 |
+
"""Load model."""
|
265 |
+
if index_path is None:
|
266 |
+
index_path = '.'.join(self.doc_files.split('.')[:-1]) + '_index.json'
|
267 |
+
self.sim_model.load_index(index_path)
|
268 |
+
|
269 |
+
|
270 |
+
if __name__ == "__main__":
|
271 |
+
parser = argparse.ArgumentParser()
|
272 |
+
parser.add_argument("--sim_model", type=str, default="shibing624/text2vec-base-chinese")
|
273 |
+
parser.add_argument("--gen_model_type", type=str, default="baichuan")
|
274 |
+
parser.add_argument("--gen_model", type=str, default="baichuan-inc/Baichuan-13B-Chat")
|
275 |
+
parser.add_argument("--lora_model", type=str, default=None)
|
276 |
+
parser.add_argument("--device", type=str, default=None)
|
277 |
+
parser.add_argument("--int4", action='store_true', help="use int4 quantization")
|
278 |
+
parser.add_argument("--int8", action='store_true', help="use int8 quantization")
|
279 |
+
args = parser.parse_args()
|
280 |
+
print(args)
|
281 |
+
m = ChatPDF(
|
282 |
+
sim_model_name_or_path=args.sim_model,
|
283 |
+
gen_model_type=args.gen_model_type,
|
284 |
+
gen_model_name_or_path=args.gen_model,
|
285 |
+
lora_model_name_or_path=args.lora_model,
|
286 |
+
device=args.device,
|
287 |
+
int4=args.int4,
|
288 |
+
int8=args.int8
|
289 |
+
)
|
290 |
+
m.load_doc_files(doc_files='sample.pdf')
|
291 |
+
m.predict('自然语言中的非平行迁移是指什么?', do_print=True)
|
292 |
+
while True:
|
293 |
+
query = input("> ")
|
294 |
+
if query == 'exit':
|
295 |
+
break
|
296 |
+
m.predict(query, do_print=True)
|
requirements.txt
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
gradio==3.26.0
|
2 |
+
protobuf
|
3 |
+
mdtex2html
|
4 |
+
bitsandbytes
|
5 |
+
similarities
|
6 |
+
sentencepiece
|
7 |
+
textgen>=1.0.1
|
8 |
+
markdown
|
9 |
+
PyPDF2
|
10 |
+
python-docx
|
11 |
+
pandas
|
12 |
+
cpm-kernels
|
13 |
+
torch>=2.0
|
14 |
+
loguru
|
15 |
+
accelerate
|
16 |
+
transformers>=4.30.2
|
sample.pdf
ADDED
Binary file (375 kB). View file
|
|