kevinwang676 shibing624 commited on
Commit
9f6cbde
·
0 Parent(s):

Duplicate from shibing624/ChatPDF

Browse files

Co-authored-by: xuming <shibing624@users.noreply.huggingface.co>

Files changed (7) hide show
  1. .gitattributes +34 -0
  2. LICENSE +201 -0
  3. README.md +14 -0
  4. app.py +210 -0
  5. chatpdf.py +154 -0
  6. requirements.txt +11 -0
  7. 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,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ @author:XuMing(xuming624@qq.com)
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
+
13
+ pwd_path = os.path.abspath(os.path.dirname(__file__))
14
+
15
+ CONTENT_DIR = os.path.join(pwd_path, "content")
16
+ logger.info(f"CONTENT_DIR: {CONTENT_DIR}")
17
+ VECTOR_SEARCH_TOP_K = 3
18
+ MAX_INPUT_LEN = 512
19
+
20
+ embedding_model_dict = {
21
+ "sentence-transformers": "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2",
22
+ "ernie-tiny": "nghuyong/ernie-3.0-nano-zh",
23
+ "ernie-base": "nghuyong/ernie-3.0-base-zh",
24
+ "text2vec": "shibing624/text2vec-base-chinese",
25
+ }
26
+
27
+ # supported LLM models
28
+ llm_model_dict = {
29
+ "chatglm-6b-int4": "THUDM/chatglm-6b-int4",
30
+ "chatglm-6b-int4-qe": "THUDM/chatglm-6b-int4-qe",
31
+ "chatglm-6b": "THUDM/chatglm-6b",
32
+ "llama-7b": "decapoda-research/llama-7b-hf",
33
+ "llama-13b": "decapoda-research/llama-13b-hf",
34
+ }
35
+
36
+ llm_model_dict_list = list(llm_model_dict.keys())
37
+ embedding_model_dict_list = list(embedding_model_dict.keys())
38
+
39
+ model = ChatPDF(
40
+ sim_model_name_or_path="sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2",
41
+ gen_model_type="chatglm",
42
+ gen_model_name_or_path="THUDM/chatglm-6b-int4",
43
+ lora_model_name_or_path=None,
44
+ max_input_size=MAX_INPUT_LEN,
45
+ )
46
+
47
+
48
+ def get_file_list():
49
+ if not os.path.exists("content"):
50
+ return []
51
+ return [f for f in os.listdir("content") if
52
+ f.endswith(".txt") or f.endswith(".pdf") or f.endswith(".docx") or f.endswith(".md")]
53
+
54
+
55
+ file_list = get_file_list()
56
+
57
+
58
+ def upload_file(file):
59
+ if not os.path.exists(CONTENT_DIR):
60
+ os.mkdir(CONTENT_DIR)
61
+ filename = os.path.basename(file.name)
62
+ shutil.move(file.name, os.path.join(CONTENT_DIR, filename))
63
+ # file_list首位插入新上传的文件
64
+ file_list.insert(0, filename)
65
+ return gr.Dropdown.update(choices=file_list, value=filename)
66
+
67
+
68
+ def get_answer(query, index_path, history):
69
+ if index_path:
70
+ if not model.sim_model.corpus_embeddings:
71
+ model.load_index(index_path)
72
+ response, empty_history = model.query(query, topn=VECTOR_SEARCH_TOP_K)
73
+ history = history + [[query, response]]
74
+ else:
75
+ # history = history + [[None, "请先加载文件后,再进行提问。"]]
76
+ # 未加载文件,仅返回生成模型结果
77
+ response, empty_history = model.gen_model.chat(query)
78
+ history = history + [[query, response]]
79
+ logger.debug(f"query: {query}, response: {response}")
80
+ return history, ""
81
+
82
+
83
+ def update_status(history, status):
84
+ history = history + [[None, status]]
85
+ logger.info(status)
86
+ return history
87
+
88
+
89
+ def reinit_model(llm_model, embedding_model, history):
90
+ try:
91
+ global model
92
+ del model
93
+ model = ChatPDF(
94
+ sim_model_name_or_path=embedding_model_dict.get(
95
+ embedding_model,
96
+ "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"),
97
+ gen_model_type=llm_model.split('-')[0],
98
+ gen_model_name_or_path=llm_model_dict.get(llm_model, "THUDM/chatglm-6b-int4"),
99
+ lora_model_name_or_path=None,
100
+ max_input_size=MAX_INPUT_LEN,
101
+ )
102
+ model_status = """模型已成功重新加载,请选择文件后点击"加载文件"按钮"""
103
+ except Exception as e:
104
+ model = None
105
+ logger.error(e)
106
+ model_status = """模型未成功重新加载,请重新选择后点击"加载模型"按钮"""
107
+ return history + [[None, model_status]]
108
+
109
+
110
+ def get_vector_store(filepath, history):
111
+ logger.info(filepath, history)
112
+ index_path = None
113
+ file_status = ''
114
+ if model is not None:
115
+ local_file_path = os.path.join(CONTENT_DIR, filepath)
116
+ local_index_path = os.path.join(CONTENT_DIR, filepath + ".index.json")
117
+ if os.path.exists(local_file_path):
118
+ model.load_pdf_file(local_file_path)
119
+ model.save_index(local_index_path)
120
+ index_path = local_index_path
121
+ if index_path:
122
+ file_status = "文件已成功加载,请开始提问"
123
+ else:
124
+ file_status = "文件未成功加载,请重新上传文件"
125
+ else:
126
+ file_status = "模型未完成加载,请先在加载模型后再导入文件"
127
+
128
+ return index_path, history + [[None, file_status]]
129
+
130
+
131
+ def reset_chat(chatbot, state):
132
+ return None, None
133
+
134
+
135
+ block_css = """.importantButton {
136
+ background: linear-gradient(45deg, #7e0570,#5d1c99, #6e00ff) !important;
137
+ border: none !important;
138
+ }
139
+ .importantButton:hover {
140
+ background: linear-gradient(45deg, #ff00e0,#8500ff, #6e00ff) !important;
141
+ border: none !important;
142
+ }"""
143
+
144
+ webui_title = """
145
+ # 🎉ChatPDF WebUI🎉
146
+ Link in: [https://github.com/shibing624/ChatPDF](https://github.com/shibing624/ChatPDF) PS: 2核CPU 16G内存机器,约2min一条😭
147
+ """
148
+
149
+ init_message = """���迎使用 ChatPDF Web UI,可以直接提问或上传文件后提问 """
150
+
151
+ with gr.Blocks(css=block_css) as demo:
152
+ index_path, file_status, model_status = gr.State(""), gr.State(""), gr.State("")
153
+ gr.Markdown(webui_title)
154
+ with gr.Row():
155
+ with gr.Column(scale=2):
156
+ chatbot = gr.Chatbot([[None, init_message], [None, None]],
157
+ elem_id="chat-box",
158
+ show_label=False).style(height=700)
159
+ query = gr.Textbox(show_label=False,
160
+ placeholder="请输入提问内容,按回车进行提交",
161
+ ).style(container=False)
162
+ clear_btn = gr.Button('🔄Clear!', elem_id='clear').style(full_width=True)
163
+ with gr.Column(scale=1):
164
+ llm_model = gr.Radio(llm_model_dict_list,
165
+ label="LLM 模型",
166
+ value=list(llm_model_dict.keys())[0],
167
+ interactive=True)
168
+ embedding_model = gr.Radio(embedding_model_dict_list,
169
+ label="Embedding 模型",
170
+ value=embedding_model_dict_list[0],
171
+ interactive=True)
172
+ load_model_button = gr.Button("重新加载模型")
173
+
174
+ with gr.Tab("select"):
175
+ selectFile = gr.Dropdown(
176
+ file_list,
177
+ label="content file",
178
+ interactive=True,
179
+ value=file_list[0] if len(file_list) > 0 else None
180
+ )
181
+ with gr.Tab("upload"):
182
+ file = gr.File(
183
+ label="content file",
184
+ file_types=['.txt', '.md', '.docx', '.pdf']
185
+ )
186
+ load_file_button = gr.Button("加载文件")
187
+ load_model_button.click(
188
+ reinit_model,
189
+ show_progress=True,
190
+ inputs=[llm_model, embedding_model, chatbot],
191
+ outputs=chatbot
192
+ )
193
+ # 将上传的文件保存到content文件夹下,并更新下拉框
194
+ file.upload(upload_file, inputs=file, outputs=selectFile)
195
+ load_file_button.click(
196
+ get_vector_store,
197
+ show_progress=True,
198
+ inputs=[selectFile, chatbot],
199
+ outputs=[index_path, chatbot],
200
+ )
201
+ query.submit(
202
+ get_answer,
203
+ [query, index_path, chatbot],
204
+ [chatbot, query],
205
+ )
206
+ clear_btn.click(reset_chat, [chatbot, query], [chatbot, query])
207
+
208
+ demo.queue(concurrency_count=3).launch(
209
+ server_name='0.0.0.0', share=False, inbrowser=False
210
+ )
chatpdf.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ @author:XuMing(xuming624@qq.com)
4
+ @description:
5
+ """
6
+ from loguru import logger
7
+ from similarities import Similarity
8
+ from textgen import ChatGlmModel, LlamaModel
9
+
10
+ PROMPT_TEMPLATE = """\
11
+ 基于以下已知信息,简洁和专业的来回答用户的问题。
12
+ 如果无法从中得到答案,请说 "根据已知信息无法回答该问题" 或 "没有提供足够的相关信息",不允许在答案中添加编造成分,答案请使用中文。
13
+
14
+ 已知内容:
15
+ {context_str}
16
+
17
+ 问题:
18
+ {query_str}
19
+ """
20
+
21
+
22
+ class ChatPDF:
23
+ def __init__(
24
+ self,
25
+ sim_model_name_or_path: str = "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2",
26
+ gen_model_type: str = "chatglm",
27
+ gen_model_name_or_path: str = "THUDM/chatglm-6b-int4",
28
+ lora_model_name_or_path: str = None,
29
+ max_input_size: int = 1024,
30
+ ):
31
+ self.sim_model = Similarity(model_name_or_path=sim_model_name_or_path)
32
+ self.max_input_size = max_input_size
33
+ if gen_model_type == "chatglm":
34
+ self.gen_model = ChatGlmModel(gen_model_type, gen_model_name_or_path, lora_name=lora_model_name_or_path)
35
+ elif gen_model_type == "llama":
36
+ self.gen_model = LlamaModel(gen_model_type, gen_model_name_or_path, lora_name=lora_model_name_or_path)
37
+ else:
38
+ raise ValueError('gen_model_type must be chatglm or llama.')
39
+ self.history = None
40
+ self.pdf_path = None
41
+
42
+ def load_pdf_file(self, pdf_path: str):
43
+ """Load a PDF file."""
44
+ if pdf_path.endswith('.pdf'):
45
+ corpus = self.extract_text_from_pdf(pdf_path)
46
+ elif pdf_path.endswith('.docx'):
47
+ corpus = self.extract_text_from_docx(pdf_path)
48
+ elif pdf_path.endswith('.md'):
49
+ corpus = self.extract_text_from_markdown(pdf_path)
50
+ else:
51
+ corpus = self.extract_text_from_txt(pdf_path)
52
+ self.sim_model.add_corpus(corpus)
53
+ self.pdf_path = pdf_path
54
+
55
+ @staticmethod
56
+ def extract_text_from_pdf(file_path: str):
57
+ """Extract text content from a PDF file."""
58
+ import PyPDF2
59
+ contents = []
60
+ with open(file_path, 'rb') as f:
61
+ pdf_reader = PyPDF2.PdfReader(f)
62
+ for page in pdf_reader.pages:
63
+ page_text = page.extract_text().strip()
64
+ raw_text = [text.strip() for text in page_text.splitlines() if text.strip()]
65
+ new_text = ''
66
+ for text in raw_text:
67
+ new_text += text
68
+ if text[-1] in ['.', '!', '?', '。', '!', '?', '…', ';', ';', ':', ':', '”', '’', ')', '】', '》', '」',
69
+ '』', '〕', '〉', '》', '〗', '〞', '〟', '»', '"', "'", ')', ']', '}']:
70
+ contents.append(new_text)
71
+ new_text = ''
72
+ if new_text:
73
+ contents.append(new_text)
74
+ return contents
75
+
76
+ @staticmethod
77
+ def extract_text_from_txt(file_path: str):
78
+ """Extract text content from a TXT file."""
79
+ contents = []
80
+ with open(file_path, 'r', encoding='utf-8') as f:
81
+ contents = [text.strip() for text in f.readlines() if text.strip()]
82
+ return contents
83
+
84
+ @staticmethod
85
+ def extract_text_from_docx(file_path: str):
86
+ """Extract text content from a DOCX file."""
87
+ import docx
88
+ document = docx.Document(file_path)
89
+ contents = [paragraph.text.strip() for paragraph in document.paragraphs if paragraph.text.strip()]
90
+ return contents
91
+
92
+ @staticmethod
93
+ def extract_text_from_markdown(file_path: str):
94
+ """Extract text content from a Markdown file."""
95
+ import markdown
96
+ from bs4 import BeautifulSoup
97
+ with open(file_path, 'r', encoding='utf-8') as f:
98
+ markdown_text = f.read()
99
+ html = markdown.markdown(markdown_text)
100
+ soup = BeautifulSoup(html, 'html.parser')
101
+ contents = [text.strip() for text in soup.get_text().splitlines() if text.strip()]
102
+ return contents
103
+
104
+ @staticmethod
105
+ def _add_source_numbers(lst):
106
+ """Add source numbers to a list of strings."""
107
+ return [f'[{idx + 1}]\t "{item}"' for idx, item in enumerate(lst)]
108
+
109
+ def _generate_answer(self, query_str, context_str, history=None, max_length=1024):
110
+ """Generate answer from query and context."""
111
+ prompt = PROMPT_TEMPLATE.format(context_str=context_str, query_str=query_str)
112
+ response, out_history = self.gen_model.chat(prompt, history, max_length=max_length)
113
+ return response, out_history
114
+
115
+ def query(self, query_str, topn=5, use_history=False, max_length=1024):
116
+ """Query from corpus."""
117
+ sim_contents = self.sim_model.most_similar(query_str, topn=topn)
118
+ logger.debug(sim_contents)
119
+ reference_results = []
120
+ for query_id, id_score_dict in sim_contents.items():
121
+ for corpus_id, s in id_score_dict.items():
122
+ reference_results.append(self.sim_model.corpus[corpus_id])
123
+ if not reference_results:
124
+ return '没有提供足够的相关信息', reference_results
125
+ reference_results = self._add_source_numbers(reference_results)
126
+ logger.debug(reference_results)
127
+ context_str = '\n'.join(reference_results)[:(self.max_input_size - len(PROMPT_TEMPLATE))]
128
+ if use_history:
129
+ response, out_history = self._generate_answer(query_str, context_str, self.history, max_length=max_length)
130
+ self.history = out_history
131
+ else:
132
+ response, out_history = self._generate_answer(query_str, context_str)
133
+ return response, out_history
134
+
135
+ def save_index(self, index_path=None):
136
+ """Save model."""
137
+ if index_path is None:
138
+ index_path = '.'.join(self.pdf_path.split('.')[:-1]) + '_index.json'
139
+ self.sim_model.save_index(index_path)
140
+
141
+ def load_index(self, index_path=None):
142
+ """Load model."""
143
+ if index_path is None:
144
+ index_path = '.'.join(self.pdf_path.split('.')[:-1]) + '_index.json'
145
+ self.sim_model.load_index(index_path)
146
+
147
+
148
+ if __name__ == "__main__":
149
+ m = ChatPDF()
150
+ m.load_pdf_file(pdf_path='sample.pdf')
151
+ response, _ = m.query('自然语言中的非平行迁移是指什么?')
152
+ print(response)
153
+ response, _ = m.query('本文作者是谁?')
154
+ print(response)
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