Zenne commited on
Commit
90094f6
1 Parent(s): c42e105

initial commit

Browse files
app.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Import required libraries
2
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
3
+ from langchain.document_loaders import (
4
+ UnstructuredWordDocumentLoader,
5
+ PyMuPDFLoader,
6
+ UnstructuredFileLoader,
7
+ )
8
+ from langchain.embeddings.openai import OpenAIEmbeddings
9
+ from langchain.chat_models import ChatOpenAI
10
+ from langchain.vectorstores import Pinecone
11
+ from langchain.chains.qa_with_sources import load_qa_with_sources_chain
12
+ from langchain.retrievers.self_query.base import SelfQueryRetriever
13
+ from langchain.chains.query_constructor.base import AttributeInfo
14
+ import os
15
+ import langchain
16
+ import pinecone
17
+ import streamlit as st
18
+ import shutil
19
+ import json
20
+ import re
21
+
22
+ OPENAI_API_KEY = ''
23
+ PINECONE_API_KEY = ''
24
+ PINECONE_API_ENV = ''
25
+ langchain.verbose = False
26
+
27
+ @st.cache_data()
28
+ def init():
29
+ pinecone_index_name = ''
30
+ pinecone_namespace = ''
31
+ docsearch_ready = False
32
+ directory_name = 'tmp_docs'
33
+ return pinecone_index_name, pinecone_namespace, docsearch_ready, directory_name
34
+
35
+
36
+ @st.cache_data()
37
+ def save_file(files):
38
+ # Remove existing files in the directory
39
+ if os.path.exists(directory_name):
40
+ for filename in os.listdir(directory_name):
41
+ file_path = os.path.join(directory_name, filename)
42
+ try:
43
+ if os.path.isfile(file_path):
44
+ os.remove(file_path)
45
+ except Exception as e:
46
+ print(f"Error: {e}")
47
+ # Save the new file with original filename
48
+ if files is not None:
49
+ for file in files:
50
+ file_name = file.name
51
+ file_path = os.path.join(directory_name, file_name)
52
+ with open(file_path, 'wb') as f:
53
+ shutil.copyfileobj(file, f)
54
+
55
+
56
+ def load_files():
57
+ all_texts = []
58
+ n_files = 0
59
+ n_char = 0
60
+ n_texts = 0
61
+
62
+ text_splitter = RecursiveCharacterTextSplitter(
63
+ chunk_size=400, chunk_overlap=50
64
+ )
65
+ for filename in os.listdir(directory_name):
66
+ file = os.path.join(directory_name, filename)
67
+ if os.path.isfile(file):
68
+ if file.endswith(".docx"):
69
+ loader = UnstructuredWordDocumentLoader(file)
70
+ elif file.endswith(".pdf"):
71
+ loader = PyMuPDFLoader(file)
72
+ else: # assume a pure text format and attempt to load it
73
+ loader = UnstructuredFileLoader(file)
74
+ data = loader.load()
75
+ metadata = data[0].metadata
76
+ fn = os.path.basename(metadata['source'])
77
+ author = os.path.splitext(fn)[0]
78
+ data[0].metadata['author'] = author
79
+ texts = text_splitter.split_documents(data)
80
+ n_files += 1
81
+ n_char += len(data[0].page_content)
82
+ n_texts += len(texts)
83
+ all_texts.extend(texts)
84
+ st.write(
85
+ f"Loaded {n_files} file(s) with {n_char} characters, and split into {n_texts} split-documents."
86
+ )
87
+ return all_texts, n_texts
88
+
89
+
90
+ @st.cache_resource()
91
+ def ingest(_all_texts, _embeddings, pinecone_index_name, pinecone_namespace):
92
+ docsearch = Pinecone.from_documents(
93
+ _all_texts, _embeddings, index_name=pinecone_index_name, namespace=pinecone_namespace)
94
+ return docsearch
95
+
96
+
97
+ def setup_retriever(docsearch, k, llm):
98
+ metadata_field_info = [
99
+ AttributeInfo(
100
+ name="author",
101
+ description="The author of the document/text/piece of context",
102
+ type="string or list[string]",
103
+ )
104
+ ]
105
+ document_content_description = "Views/opions/proposals suggested by the author on one or more discussion points."
106
+ retriever = SelfQueryRetriever.from_llm(
107
+ llm, docsearch, document_content_description, metadata_field_info, verbose=True)
108
+ return retriever
109
+
110
+
111
+ def setup_docsearch(pinecone_index_name, pinecone_namespace, embeddings):
112
+ docsearch = []
113
+ n_texts = 0
114
+ # Load the pre-created Pinecone index.
115
+ # The index which has already be stored in pinecone.io as long-term memory
116
+ if pinecone_index_name in pinecone.list_indexes():
117
+ docsearch = Pinecone.from_existing_index(
118
+ index_name=pinecone_index_name, embedding=embeddings, text_key='text', namespace=pinecone_namespace)
119
+ index_client = pinecone.Index(pinecone_index_name)
120
+ # Get the index information
121
+ index_info = index_client.describe_index_stats()
122
+ n_texts = index_info['namespaces'][pinecone_namespace]['vector_count']
123
+ else:
124
+ raise ValueError('''Cannot find the specified Pinecone index.
125
+ Create one in pinecone.io or using, e.g.,
126
+ pinecone.create_index(
127
+ name=index_name, dimension=1536, metric="cosine", shards=1)''')
128
+ return docsearch, n_texts
129
+
130
+
131
+ def get_response(query, chat_history, CRqa):
132
+ result = CRqa({"question": query, "chat_history": chat_history})
133
+ return result['answer'], result['source_documents']
134
+
135
+
136
+ def setup_em_llm(OPENAI_API_KEY, temperature):
137
+ # Set up OpenAI embeddings
138
+ embeddings = OpenAIEmbeddings(openai_api_key=OPENAI_API_KEY)
139
+ # Use Open AI LLM with gpt-3.5-turbo.
140
+ # Set the temperature to be 0 if you do not want it to make up things
141
+ llm = ChatOpenAI(temperature=temperature, model_name="gpt-3.5-turbo", streaming=True,
142
+ openai_api_key=OPENAI_API_KEY)
143
+ return embeddings, llm
144
+
145
+
146
+ def load_chat_history(CHAT_HISTORY_FILENAME):
147
+ try:
148
+ with open(CHAT_HISTORY_FILENAME, 'r') as f:
149
+ chat_history = json.load(f)
150
+ except (FileNotFoundError, json.JSONDecodeError):
151
+ chat_history = []
152
+ return chat_history
153
+
154
+
155
+ def save_chat_history(chat_history, CHAT_HISTORY_FILENAME):
156
+ with open(CHAT_HISTORY_FILENAME, 'w') as f:
157
+ json.dump(chat_history, f)
158
+
159
+
160
+ pinecone_index_name, pinecone_namespace, docsearch_ready, directory_name = init()
161
+
162
+
163
+ def main(pinecone_index_name, pinecone_namespace, docsearch_ready):
164
+ docsearch_ready = False
165
+ chat_history = []
166
+ # Get user input of whether to use Pinecone or not
167
+ col1, col2, col3 = st.columns([1, 1, 1])
168
+ # create the radio buttons and text input fields
169
+ with col1:
170
+ r_ingest = st.radio(
171
+ 'Ingest file(s)?', ('Yes', 'No'))
172
+ OPENAI_API_KEY = st.text_input(
173
+ "OpenAI API key:", type="password")
174
+
175
+ with col2:
176
+ PINECONE_API_KEY = st.text_input(
177
+ "Pinecone API key:", type="password")
178
+ PINECONE_API_ENV = st.text_input(
179
+ "Pinecone API env:", type="password")
180
+ pinecone_index_name = st.text_input('Pinecone index:')
181
+ pinecone.init(api_key=PINECONE_API_KEY,
182
+ environment=PINECONE_API_ENV)
183
+ with col3:
184
+ pinecone_namespace = st.text_input('Pinecone namespace:')
185
+ temperature = st.slider('Temperature', 0.0, 1.0, 0.1)
186
+ k_sources = st.slider('# source(s) to print out', 0, 20, 2)
187
+
188
+ if pinecone_index_name:
189
+ session_name = pinecone_index_name
190
+ embeddings, llm = setup_em_llm(OPENAI_API_KEY, temperature)
191
+ if r_ingest.lower() == 'yes':
192
+ files = st.file_uploader(
193
+ 'Upload Files', accept_multiple_files=True)
194
+ if files:
195
+ save_file(files)
196
+ all_texts, n_texts = load_files()
197
+ docsearch = ingest(all_texts, embeddings,
198
+ pinecone_index_name, pinecone_namespace)
199
+ docsearch_ready = True
200
+ else:
201
+ st.write(
202
+ 'No data is to be ingested. Make sure the Pinecone index you provided contains data.')
203
+ docsearch, n_texts = setup_docsearch(pinecone_index_name, pinecone_namespace,
204
+ embeddings)
205
+ docsearch_ready = True
206
+ if docsearch_ready:
207
+ # number of sources (split-documents when ingesting files); default is 4
208
+ k = min([20, n_texts])
209
+ retriever = setup_retriever(docsearch, k, llm)
210
+ CRqa = load_qa_with_sources_chain(llm, chain_type="stuff")
211
+
212
+ st.title('Chatbot')
213
+ # Get user input
214
+ query = st.text_area('Enter your question:', height=10,
215
+ placeholder='Summarize the context.')
216
+ if query:
217
+ # Generate a reply based on the user input and chat history
218
+ CHAT_HISTORY_FILENAME = f"chat_history/{session_name}_chat_hist.json"
219
+ chat_history = load_chat_history(CHAT_HISTORY_FILENAME)
220
+ chat_history = [(user, bot)
221
+ for user, bot in chat_history]
222
+ docs = retriever.get_relevant_documents(query)
223
+ if not docs:
224
+ docs = docsearch.similarity_search(query)
225
+ result = CRqa.run(input_documents=docs, question=query)
226
+ reply = re.match(r'(.+?)\.\s*SOURCES:', result).group(1)
227
+ source = re.search(r'SOURCES:\s*(.+)', result).group(1)
228
+ # Update the chat history with the user input and system response
229
+ chat_history.append(('User', query))
230
+ chat_history.append(('Bot', reply))
231
+ save_chat_history(chat_history, CHAT_HISTORY_FILENAME)
232
+ latest_chats = chat_history[-4:]
233
+ chat_history_str = '\n'.join(
234
+ [f'{x[0]}: {x[1]}' for x in latest_chats])
235
+ st.text_area('Chat record:', value=chat_history_str, height=250)
236
+
237
+
238
+ if __name__ == '__main__':
239
+ main(pinecone_index_name, pinecone_namespace,
240
+ docsearch_ready)
chat_history/empty_chat_hist.json ADDED
File without changes
requirements.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ langchain
2
+ openai
3
+ streamlit
4
+ pinecone-client
5
+ chromadb
6
+ unstructured
7
+ pdf2image
8
+ pytesseract
9
+ tiktoken
10
+ pymupdf
11
+ tabulate
12
+ lark
tmp_docs/empty.txt ADDED
File without changes