File size: 11,844 Bytes
4479cfa |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 |
# -*- coding: utf-8 -*-
"""
@author:XuMing([email protected])
@description:
modified from https://github.com/imClumsyPanda/langchain-ChatGLM/blob/master/webui.py
"""
import argparse
import hashlib
import os
import shutil
import gradio as gr
from loguru import logger
from chatpdf import ChatPDF
pwd_path = os.path.abspath(os.path.dirname(__file__))
CONTENT_DIR = os.path.join(pwd_path, "content")
logger.info(f"CONTENT_DIR: {CONTENT_DIR}")
VECTOR_SEARCH_TOP_K = 3
MAX_INPUT_LEN = 2048
embedding_model_dict = {
"text2vec-base": "shibing624/text2vec-base-chinese",
"text2vec-multilingual": "shibing624/text2vec-base-multilingual",
"text2vec-large": "GanymedeNil/text2vec-large-chinese",
"sentence-transformers": "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2",
"ernie-tiny": "nghuyong/ernie-3.0-nano-zh",
"ernie-base": "nghuyong/ernie-3.0-base-zh",
}
# supported LLM models
llm_model_dict = {
"llama-2-7b": "LinkSoul/Chinese-Llama-2-7b-4bit",
"baichuan-13b-chat": "baichuan-inc/Baichuan-13B-Chat",
"chatglm-6b-int4-qe": "THUDM/chatglm-6b-int4-qe",
"chatglm-2-6b": "THUDM/chatglm2-6b",
"chatglm-2-6b-int4": "THUDM/chatglm2-6b-int4",
"chatglm-6b-int4": "THUDM/chatglm-6b-int4",
"chatglm-6b": "THUDM/chatglm-6b",
"llama-7b": "shibing624/chinese-alpaca-plus-7b-hf",
"llama-13b": "shibing624/chinese-alpaca-plus-13b-hf",
}
llm_model_dict_list = list(llm_model_dict.keys())
embedding_model_dict_list = list(embedding_model_dict.keys())
parser = argparse.ArgumentParser()
parser.add_argument("--sim_model", type=str, default="shibing624/text2vec-base-chinese")
parser.add_argument("--gen_model_type", type=str, default="llama")
parser.add_argument("--gen_model", type=str, default="LinkSoul/Chinese-Llama-2-7b-4bit")
parser.add_argument("--lora_model", type=str, default=None)
parser.add_argument("--device", type=str, default="cpu")
parser.add_argument("--int4", action='store_true', help="use int4 quantization")
parser.add_argument("--int8", action='store_true', help="use int8 quantization")
args = parser.parse_args()
print(args)
model = None
def get_file_list():
if not os.path.exists("content"):
return []
return [f for f in os.listdir("content") if
f.endswith(".txt") or f.endswith(".pdf") or f.endswith(".docx") or f.endswith(".md")]
file_list = get_file_list()
def upload_file(file):
if not os.path.exists(CONTENT_DIR):
os.mkdir(CONTENT_DIR)
filename = os.path.basename(file.name)
shutil.move(file.name, os.path.join(CONTENT_DIR, filename))
# file_list首位插入新上传的文件
file_list.insert(0, filename)
return gr.Dropdown.update(choices=file_list, value=filename)
def parse_text(text):
"""copy from https://github.com/GaiZhenbiao/ChuanhuChatGPT/"""
lines = text.split("\n")
lines = [line for line in lines if line != ""]
count = 0
for i, line in enumerate(lines):
if "```" in line:
count += 1
items = line.split('`')
if count % 2 == 1:
lines[i] = f'<pre><code class="language-{items[-1]}">'
else:
lines[i] = f'<br></code></pre>'
else:
if i > 0:
if count % 2 == 1:
line = line.replace("`", "\`")
line = line.replace("<", "<")
line = line.replace(">", ">")
line = line.replace(" ", " ")
line = line.replace("*", "*")
line = line.replace("_", "_")
line = line.replace("-", "-")
line = line.replace(".", ".")
line = line.replace("!", "!")
line = line.replace("(", "(")
line = line.replace(")", ")")
line = line.replace("$", "$")
lines[i] = "<br>" + line
text = "".join(lines)
return text
def get_answer(query, index_path, history, topn=VECTOR_SEARCH_TOP_K, max_input_size=1024, only_chat=False):
if model is None:
return [None, "模型还未加载"], query
if index_path and not only_chat:
if not model.sim_model.corpus_embeddings:
model.load_index(index_path)
response, reference_results = model.predict(
query=query, topn=topn, context_len=max_input_size)
logger.debug(f"query: {query}, response with content: {response}")
for i in range(len(reference_results)):
r = reference_results[i]
response += f"\n{r.strip()}"
response = parse_text(response)
history = history + [[query, response]]
else:
# 未加载文件,仅返回生成模型结果
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.
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]"""
if args.gen_model_type == "llama":
query = instruction.format(query)
model.history.append([query, ''])
response = ""
for new_text in model.stream_generate_answer(query, context_len=max_input_size):
response += new_text
response = response.strip()
model.history[-1][1] = response
response = parse_text(response)
history = history + [[query, response]]
logger.debug(f"query: {query}, response: {response}")
return history, ""
def update_status(history, status):
history = history + [[None, status]]
logger.info(status)
return history
def reinit_model(llm_model, embedding_model, history):
try:
global model
if model is not None:
del model
model = ChatPDF(
sim_model_name_or_path=embedding_model_dict.get(
embedding_model,
"shibing624/text2vec-base-chinese"
),
gen_model_type=llm_model.split('-')[0],
gen_model_name_or_path=llm_model_dict.get(llm_model, "LinkSoul/Chinese-Llama-2-7b-4bit"),
lora_model_name_or_path=None,
)
model_status = """模型已成功重新加载,请选择文件后点击"加载文件"按钮"""
except Exception as e:
model = None
logger.error(e)
model_status = """模型未成功重新加载,请重新选择后点击"加载模型"按钮"""
return history + [[None, model_status]]
def get_file_hash(fpath):
return hashlib.md5(open(fpath, 'rb').read()).hexdigest()
def get_vector_store(filepath, history, embedding_model):
logger.info(filepath, history)
index_path = None
file_status = ''
if model is not None:
local_file_path = os.path.join(CONTENT_DIR, filepath)
local_file_hash = get_file_hash(local_file_path)
index_file_name = f"{filepath}.{embedding_model}.{local_file_hash}.index.json"
local_index_path = os.path.join(CONTENT_DIR, index_file_name)
if os.path.exists(local_index_path):
model.load_index(local_index_path)
index_path = local_index_path
file_status = "文件已成功加载,请开始提问"
elif os.path.exists(local_file_path):
model.load_doc_files(local_file_path)
model.save_index(local_index_path)
index_path = local_index_path
if index_path:
file_status = "文件索引并成功加载,请开始提问"
else:
file_status = "文件未成功加载,请重新上传文件"
else:
file_status = "模型未完成加载,请先在加载模型后再导入文件"
return index_path, history + [[None, file_status]]
def reset_chat(chatbot, state):
return None, None
def change_max_input_size(input_size):
if model is not None:
model.max_input_size = input_size
return
block_css = """.importantButton {
background: linear-gradient(45deg, #7e0570,#5d1c99, #6e00ff) !important;
border: none !important;
}
.importantButton:hover {
background: linear-gradient(45deg, #ff00e0,#8500ff, #6e00ff) !important;
border: none !important;
}"""
webui_title = """
# 🎉ChatPDF WebUI🎉
Link in: [https://github.com/shibing624/ChatPDF](https://github.com/shibing624/ChatPDF) PS: 2核CPU 16G内存机器,约2min一条😭
"""
init_message = """欢迎使用 ChatPDF Web UI,可以直接提问或上传文件后提问 """
with gr.Blocks(css=block_css) as demo:
index_path, file_status, model_status = gr.State(""), gr.State(""), gr.State("")
gr.Markdown(webui_title)
with gr.Row():
with gr.Column(scale=2):
chatbot = gr.Chatbot([[None, init_message], [None, None]],
elem_id="chat-box",
show_label=False).style(height=700)
query = gr.Textbox(show_label=False,
placeholder="请输入提问内容,按回车进行提交",
).style(container=False)
clear_btn = gr.Button('🔄Clear!', elem_id='clear').style(full_width=True)
with gr.Column(scale=1):
llm_model = gr.Radio(llm_model_dict_list,
label="LLM 模型",
value=list(llm_model_dict.keys())[0],
interactive=True)
embedding_model = gr.Radio(embedding_model_dict_list,
label="Embedding 模型",
value=embedding_model_dict_list[0],
interactive=True)
load_model_button = gr.Button("重新加载模型")
with gr.Row():
only_chat = gr.Checkbox(False, label="不加载文件(纯聊天)")
with gr.Row():
topn = gr.Slider(1, 100, 20, step=1, label="最大搜索数量")
max_input_size = gr.Slider(512, 4096, MAX_INPUT_LEN, step=10, label="摘要最大长度")
with gr.Tab("select"):
selectFile = gr.Dropdown(
file_list,
label="content file",
interactive=True,
value=file_list[0] if len(file_list) > 0 else None
)
with gr.Tab("upload"):
file = gr.File(
label="content file",
file_types=['.txt', '.md', '.docx', '.pdf']
)
load_file_button = gr.Button("加载文件")
max_input_size.change(
change_max_input_size,
inputs=max_input_size
)
load_model_button.click(
reinit_model,
show_progress=True,
inputs=[llm_model, embedding_model, chatbot],
outputs=chatbot
)
# 将上传的文件保存到content文件夹下,并更新下拉框
file.upload(upload_file, inputs=file, outputs=selectFile)
load_file_button.click(
get_vector_store,
show_progress=True,
inputs=[selectFile, chatbot, embedding_model],
outputs=[index_path, chatbot],
)
query.submit(
get_answer,
[query, index_path, chatbot, topn, max_input_size, only_chat],
[chatbot, query],
)
clear_btn.click(reset_chat, [chatbot, query], [chatbot, query])
demo.queue(concurrency_count=3).launch()
|