Spaces:
Sleeping
Sleeping
Commit
·
656fdc6
1
Parent(s):
d8b389b
Create app002-py
Browse files
app002-py
ADDED
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#删除了documents=[]
|
2 |
+
#将st.session_state的变量全部移动到相应的变量第一次出现位置,而不是在最开始全部声明为None
|
3 |
+
#将pdf_files = st.file_uploader("Choose your PDF Files and Press OK", type=['pdf'], accept_multiple_files=True)
|
4 |
+
#修改为if "pdf_files" not in st.session_state:
|
5 |
+
# st.session_state.pdf_files = st.file_uploader("Choose your PDF Files and Press OK", type=['pdf'], accept_multiple_files=True)
|
6 |
+
#if not st.session_state.pdf_files:
|
7 |
+
#意思就是如果st.session_state.pdf_files为空,就停止执行程序
|
8 |
+
|
9 |
+
import streamlit as st
|
10 |
+
from llama_index import VectorStoreIndex, SimpleDirectoryReader
|
11 |
+
from langchain.embeddings.huggingface import HuggingFaceEmbeddings
|
12 |
+
from llama_index import LangchainEmbedding, ServiceContext
|
13 |
+
from llama_index import StorageContext, load_index_from_storage
|
14 |
+
from llama_index import LLMPredictor
|
15 |
+
#from transformers import HuggingFaceHub
|
16 |
+
from langchain import HuggingFaceHub
|
17 |
+
from streamlit.components.v1 import html
|
18 |
+
from pathlib import Path
|
19 |
+
from time import sleep
|
20 |
+
import random
|
21 |
+
import string
|
22 |
+
|
23 |
+
import os
|
24 |
+
from dotenv import load_dotenv
|
25 |
+
load_dotenv()
|
26 |
+
|
27 |
+
import timeit
|
28 |
+
|
29 |
+
st.set_page_config(page_title="Open AI Doc-Chat Assistant", layout="wide")
|
30 |
+
st.subheader("Open AI Doc-Chat Assistant: Life Enhancing with AI!")
|
31 |
+
|
32 |
+
css_file = "main.css"
|
33 |
+
with open(css_file) as f:
|
34 |
+
st.markdown("<style>{}</style>".format(f.read()), unsafe_allow_html=True)
|
35 |
+
|
36 |
+
HUGGINGFACEHUB_API_TOKEN = os.getenv("HUGGINGFACEHUB_API_TOKEN")
|
37 |
+
|
38 |
+
def generate_random_string(length):
|
39 |
+
letters = string.ascii_lowercase
|
40 |
+
return ''.join(random.choice(letters) for i in range(length))
|
41 |
+
|
42 |
+
#random_string = generate_random_string(20)
|
43 |
+
#directory_path=random_string
|
44 |
+
|
45 |
+
if "directory_path" not in st.session_state:
|
46 |
+
st.session_state.directory_path = generate_random_string(20)
|
47 |
+
|
48 |
+
with st.sidebar:
|
49 |
+
st.subheader("Upload your Documents Here: ")
|
50 |
+
if "pdf_files" not in st.session_state:
|
51 |
+
st.session_state.pdf_files = st.file_uploader("Choose your PDF Files and Press OK", type=['pdf'], accept_multiple_files=True)
|
52 |
+
if not st.session_state.pdf_files: #如果没有上传文件,则程序停止执行,就不会出现documents为空的错误情况
|
53 |
+
st.warning("请上传文档文件")
|
54 |
+
st.stop()
|
55 |
+
else: #如果已经上传文件,则装载文件SimpleDirectoryReader.load_data()
|
56 |
+
st.session_state.pdf_files=pdf_files
|
57 |
+
if not os.path.exists(st.session_state.directory_path):
|
58 |
+
os.makedirs(st.session_state.directory_path)
|
59 |
+
for pdf_file in st.session_state.pdf_files:
|
60 |
+
#for pdf_file in pdf_files:
|
61 |
+
file_path = os.path.join(st.session_state.directory_path, pdf_file.name)
|
62 |
+
with open(file_path, 'wb') as f:
|
63 |
+
f.write(pdf_file.read())
|
64 |
+
st.success(f"File '{pdf_file.name}' saved successfully.")
|
65 |
+
try:
|
66 |
+
start_1 = timeit.default_timer() # Start timer
|
67 |
+
st.write(f"QA文档加载开始:{start_1}")
|
68 |
+
if "documents" not in st.session_state:
|
69 |
+
st.session_state.documents = SimpleDirectoryReader(st.session_state.directory_path).load_data()
|
70 |
+
end_1 = timeit.default_timer() # Start timer
|
71 |
+
st.write(f"QA文档加载结束:{end_1}")
|
72 |
+
st.write(f"QA文档加载耗时:{end_1 - start_1}")
|
73 |
+
except Exception as e:
|
74 |
+
print("文档加载出现问题/Waiting for path creation.")
|
75 |
+
|
76 |
+
# Load documents from a directory
|
77 |
+
#documents = SimpleDirectoryReader('data').load_data()
|
78 |
+
|
79 |
+
start_2 = timeit.default_timer() # Start timer
|
80 |
+
st.write(f"向量模型加载开始:{start_2}")
|
81 |
+
if "embed_model" not in st.session_state:
|
82 |
+
st.session_state.embed_model = LangchainEmbedding(HuggingFaceEmbeddings(model_name='sentence-transformers/all-MiniLM-L6-v2'))
|
83 |
+
end_2 = timeit.default_timer() # Start timer
|
84 |
+
st.write(f"向量模型加载加载结束:{end_2}")
|
85 |
+
st.write(f"向量模型加载耗时:{end_2 - start_2}")
|
86 |
+
|
87 |
+
if "llm_predictor" not in st.session_state:
|
88 |
+
st.session_state.llm_predictor = LLMPredictor(HuggingFaceHub(repo_id="HuggingFaceH4/starchat-beta", model_kwargs={"min_length":100, "max_new_tokens":1024, "do_sample":True, "temperature":0.2,"top_k":50, "top_p":0.95, "eos_token_id":49155}))
|
89 |
+
|
90 |
+
if "service_context" not in st.session_state:
|
91 |
+
st.session_state.service_context = ServiceContext.from_defaults(llm_predictor=st.session_state.llm_predictor, embed_model=st.session_state.embed_model)
|
92 |
+
|
93 |
+
start_3 = timeit.default_timer() # Start timer
|
94 |
+
st.write(f"向量库构建开始:{start_3}")
|
95 |
+
if "new_index" not in st.session_state:
|
96 |
+
st.session_state.new_index = VectorStoreIndex.from_documents(
|
97 |
+
st.session_state.documents,
|
98 |
+
service_context=st.session_state.service_context,
|
99 |
+
)
|
100 |
+
end_3 = timeit.default_timer() # Start timer
|
101 |
+
st.write(f"向量库构建结束:{end_3}")
|
102 |
+
st.write(f"向量库构建耗时:{end_3 - start_3}")
|
103 |
+
|
104 |
+
st.session_state.new_index.storage_context.persist("st.session_state.directory_path")
|
105 |
+
|
106 |
+
if "storage_context" not in st.session_state:
|
107 |
+
st.session_state.storage_context = StorageContext.from_defaults(persist_dir="st.session_state.directory_path")
|
108 |
+
|
109 |
+
start_4 = timeit.default_timer() # Start timer
|
110 |
+
st.write(f"向量库装载开始:{start_4}")
|
111 |
+
if "loadedindex" not in st.session_state:
|
112 |
+
st.session_state.loadedindex = load_index_from_storage(storage_context=st.session_state.storage_context, service_context=st.session_state.service_context)
|
113 |
+
end_4 = timeit.default_timer() # Start timer
|
114 |
+
st.write(f"向量库装载结束:{end_4}")
|
115 |
+
st.write(f"向量库装载耗时:{end_4 - start_4}")
|
116 |
+
|
117 |
+
if "query_engine" not in st.session_state:
|
118 |
+
st.session_state.query_engine = st.session_state.loadedindex.as_query_engine()
|
119 |
+
|
120 |
+
if "user_question " not in st.session_state:
|
121 |
+
st.session_state.user_question = st.text_input("Enter your query:")
|
122 |
+
if st.session_state.user_question !="" and not st.session_state.user_question.strip().isspace() and not st.session_state.user_question == "" and not st.session_state.user_question.strip() == "" and not st.session_state.user_question.isspace():
|
123 |
+
print("user question: "+st.session_state.user_question)
|
124 |
+
with st.spinner("AI Thinking...Please wait a while to Cheers!"):
|
125 |
+
start_5 = timeit.default_timer() # Start timer
|
126 |
+
st.write(f"Query Engine - AI QA开始:{start_5}")
|
127 |
+
initial_response = st.session_state.query_engine.query(st.session_state.user_question)
|
128 |
+
temp_ai_response=str(initial_response)
|
129 |
+
final_ai_response=temp_ai_response.partition('<|end|>')[0]
|
130 |
+
print("AI Response:\n"+final_ai_response)
|
131 |
+
st.write("AI Response:\n\n"+final_ai_response)
|