SANDRAMSC commited on
Commit
4492db0
2 Parent(s): a203bc8 6b63bdc

Merge branch 'eliawaefler:main' into main

Browse files
Files changed (4) hide show
  1. app.py +11 -17
  2. app_V2.py +247 -0
  3. backend/generate_metadata.py +9 -8
  4. flake.nix +11 -3
app.py CHANGED
@@ -2,7 +2,7 @@ import time
2
  import streamlit as st
3
  from PyPDF2 import PdfReader
4
  from langchain.text_splitter import CharacterTextSplitter
5
- from langchain.embeddings import OpenAIEmbeddings, HuggingFaceInstructEmbeddings
6
  from langchain.vectorstores import FAISS
7
  from langchain.chat_models import ChatOpenAI
8
  from langchain.memory import ConversationBufferMemory
@@ -112,16 +112,11 @@ def handle_userinput(user_question):
112
  # Display AI response
113
  st.write(bot_template.replace("{{MSG}}", message.content), unsafe_allow_html=True)
114
 
115
- # THIS DOESNT WORK, SOMEONE PLS FIX
116
- # Display source document information if available in the message
117
- if hasattr(message, 'source') and message.source:
118
- st.write(f"Source Document: {message.source}", unsafe_allow_html=True)
119
-
120
 
121
  def safe_vec_store():
122
  # USE VECTARA INSTEAD
123
  os.makedirs('vectorstore', exist_ok=True)
124
- filename = 'vectores' + datetime.now().strftime('%Y%m%d%H%M') + '.pkl'
125
  file_path = os.path.join('vectorstore', filename)
126
  vector_store = st.session_state.vectorstore
127
 
@@ -131,18 +126,21 @@ def safe_vec_store():
131
 
132
 
133
  def main():
134
- st.set_page_config(page_title="Doc Verify RAG", page_icon=":hospital:")
135
  st.write(css, unsafe_allow_html=True)
 
 
136
  if "openai_api_key" not in st.session_state:
137
  st.session_state.openai_api_key = False
138
  if "openai_org" not in st.session_state:
139
  st.session_state.openai_org = False
140
  if "classify" not in st.session_state:
141
  st.session_state.classify = False
 
142
  def set_pw():
143
  st.session_state.openai_api_key = True
 
144
  st.subheader("Your documents")
145
- # OPENAI_ORG_ID = st.text_input("OPENAI ORG ID:")
146
  OPENAI_API_KEY = st.text_input("OPENAI API KEY:", type="password",
147
  disabled=st.session_state.openai_api_key, on_change=set_pw)
148
  if st.session_state.classify:
@@ -179,20 +177,18 @@ def main():
179
  st.session_state.conversation = get_conversation_chain(vec)
180
  st.success("data loaded")
181
 
182
-
183
  if "conversation" not in st.session_state:
184
  st.session_state.conversation = None
185
  if "chat_history" not in st.session_state:
186
  st.session_state.chat_history = None
187
 
188
- st.header("Doc Verify RAG :hospital:")
189
  user_question = st.text_input("Ask a question about your documents:")
190
  if user_question:
191
  handle_userinput(user_question)
192
  with st.sidebar:
193
-
194
- st.subheader("Classification Instrucitons")
195
- classifier_docs = st.file_uploader("Upload your instructions here and click on 'Process'", accept_multiple_files=True)
196
  filenames = [file.name for file in classifier_docs if file is not None]
197
 
198
  if st.button("Process Classification"):
@@ -201,8 +197,6 @@ def main():
201
  st.warning("set classify")
202
  time.sleep(3)
203
 
204
-
205
- # Save and Load Embeddings
206
  if st.button("Save Embeddings"):
207
  if "vectorstore" in st.session_state:
208
  safe_vec_store()
@@ -216,4 +210,4 @@ def main():
216
 
217
 
218
  if __name__ == '__main__':
219
- main()
 
2
  import streamlit as st
3
  from PyPDF2 import PdfReader
4
  from langchain.text_splitter import CharacterTextSplitter
5
+ from langchain.embeddings import OpenAIEmbeddings
6
  from langchain.vectorstores import FAISS
7
  from langchain.chat_models import ChatOpenAI
8
  from langchain.memory import ConversationBufferMemory
 
112
  # Display AI response
113
  st.write(bot_template.replace("{{MSG}}", message.content), unsafe_allow_html=True)
114
 
 
 
 
 
 
115
 
116
  def safe_vec_store():
117
  # USE VECTARA INSTEAD
118
  os.makedirs('vectorstore', exist_ok=True)
119
+ filename = 'vectors' + datetime.now().strftime('%Y%m%d%H%M') + '.pkl'
120
  file_path = os.path.join('vectorstore', filename)
121
  vector_store = st.session_state.vectorstore
122
 
 
126
 
127
 
128
  def main():
129
+ st.set_page_config(page_title="Doc Verify RAG", page_icon=":mag:")
130
  st.write(css, unsafe_allow_html=True)
131
+ st.header("Doc Verify RAG :mag:")
132
+
133
  if "openai_api_key" not in st.session_state:
134
  st.session_state.openai_api_key = False
135
  if "openai_org" not in st.session_state:
136
  st.session_state.openai_org = False
137
  if "classify" not in st.session_state:
138
  st.session_state.classify = False
139
+
140
  def set_pw():
141
  st.session_state.openai_api_key = True
142
+
143
  st.subheader("Your documents")
 
144
  OPENAI_API_KEY = st.text_input("OPENAI API KEY:", type="password",
145
  disabled=st.session_state.openai_api_key, on_change=set_pw)
146
  if st.session_state.classify:
 
177
  st.session_state.conversation = get_conversation_chain(vec)
178
  st.success("data loaded")
179
 
 
180
  if "conversation" not in st.session_state:
181
  st.session_state.conversation = None
182
  if "chat_history" not in st.session_state:
183
  st.session_state.chat_history = None
184
 
 
185
  user_question = st.text_input("Ask a question about your documents:")
186
  if user_question:
187
  handle_userinput(user_question)
188
  with st.sidebar:
189
+ st.subheader("Classification instructions")
190
+ classifier_docs = st.file_uploader("Upload your instructions here and click on 'Process'",
191
+ accept_multiple_files=True)
192
  filenames = [file.name for file in classifier_docs if file is not None]
193
 
194
  if st.button("Process Classification"):
 
197
  st.warning("set classify")
198
  time.sleep(3)
199
 
 
 
200
  if st.button("Save Embeddings"):
201
  if "vectorstore" in st.session_state:
202
  safe_vec_store()
 
210
 
211
 
212
  if __name__ == '__main__':
213
+ main()
app_V2.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tempfile
2
+ import streamlit as st
3
+ from PyPDF2 import PdfReader
4
+ from langchain.text_splitter import CharacterTextSplitter
5
+ from langchain.embeddings import OpenAIEmbeddings
6
+ from langchain.vectorstores import FAISS
7
+ from langchain.chat_models import ChatOpenAI
8
+ from langchain.memory import ConversationBufferMemory
9
+ from langchain.chains import ConversationalRetrievalChain
10
+ import os
11
+ import pickle
12
+ from datetime import datetime
13
+ from backend.generate_metadata import generate_metadata, ingest
14
+
15
+ MODEL_NAME = "mixtral"
16
+ css = '''
17
+ <style>
18
+ .chat-message {
19
+ padding: 1.5rem; border-radius: 0.5rem; margin-bottom: 1rem; display: flex
20
+ }
21
+ .chat-message.user {
22
+ background-color: #2b313e
23
+ }
24
+ .chat-message.bot {
25
+ background-color: #475063
26
+ }
27
+ .chat-message .avatar {
28
+ width: 20%;
29
+ }
30
+ .chat-message .avatar img {
31
+ max-width: 78px;
32
+ max-height: 78px;
33
+ border-radius: 50%;
34
+ object-fit: cover;
35
+ }
36
+ .chat-message .message {
37
+ width: 80%;
38
+ padding: 0 1.5rem;
39
+ color: #fff;
40
+ }
41
+ '''
42
+ bot_template = '''
43
+ <div class="chat-message bot">
44
+ <div class="avatar">
45
+ <img src="https://i.ibb.co/cN0nmSj/Screenshot-2023-05-28-at-02-37-21.png"
46
+ style="max-height: 78px; max-width: 78px; border-radius: 50%; object-fit: cover;">
47
+ </div>
48
+ <div class="message">{{MSG}}</div>
49
+ </div>
50
+ '''
51
+ user_template = '''
52
+ <div class="chat-message user">
53
+ <div class="avatar">
54
+ <img src="https://i.ibb.co/rdZC7LZ/Photo-logo-1.png">
55
+ </div>
56
+ <div class="message">{{MSG}}</div>
57
+ </div>
58
+ '''
59
+
60
+
61
+ def get_pdf_text(pdf_docs):
62
+ text = ""
63
+ for pdf in pdf_docs:
64
+ pdf_reader = PdfReader(pdf)
65
+ for page in pdf_reader.pages:
66
+ text += page.extract_text()
67
+ return text
68
+
69
+
70
+ def get_text_chunks(text):
71
+ text_splitter = CharacterTextSplitter(
72
+ separator="\n",
73
+ chunk_size=1000,
74
+ chunk_overlap=200,
75
+ length_function=len
76
+ )
77
+ chunks = text_splitter.split_text(text)
78
+ return chunks
79
+
80
+
81
+ def get_vectorstore(text_chunks):
82
+ embeddings = OpenAIEmbeddings()
83
+ # embeddings = HuggingFaceInstructEmbeddings(model_name="hkunlp/instructor-xl")
84
+ vectorstore = FAISS.from_texts(texts=text_chunks, embedding=embeddings)
85
+ return vectorstore
86
+
87
+
88
+ def get_conversation_chain(vectorstore):
89
+ llm = ChatOpenAI()
90
+ # llm = HuggingFaceHub(repo_id="google/flan-t5-xxl", model_kwargs={"temperature":0.5, "max_length":512})
91
+
92
+ memory = ConversationBufferMemory(
93
+ memory_key='chat_history', return_messages=True)
94
+ conversation_chain = ConversationalRetrievalChain.from_llm(
95
+ llm=llm,
96
+ retriever=vectorstore.as_retriever(),
97
+ memory=memory
98
+ )
99
+ return conversation_chain
100
+
101
+
102
+ def handle_userinput(user_question):
103
+ response = st.session_state.conversation({'question': user_question})
104
+ st.session_state.chat_history = response['chat_history']
105
+
106
+ for i, message in enumerate(st.session_state.chat_history):
107
+ # Display user message
108
+ if i % 2 == 0:
109
+ st.write(user_template.replace("{{MSG}}", message.content), unsafe_allow_html=True)
110
+ else:
111
+ print(message)
112
+ # Display AI response
113
+ st.write(bot_template.replace("{{MSG}}", message.content), unsafe_allow_html=True)
114
+
115
+
116
+ def safe_vec_store():
117
+ # USE VECTARA INSTEAD
118
+ os.makedirs('vectorstore', exist_ok=True)
119
+ filename = 'vectors' + datetime.now().strftime('%Y%m%d%H%M') + '.pkl'
120
+ file_path = os.path.join('vectorstore', filename)
121
+ vector_store = st.session_state.vectorstore
122
+
123
+ # Serialize and save the entire FAISS object using pickle
124
+ with open(file_path, 'wb') as f:
125
+ pickle.dump(vector_store, f)
126
+
127
+
128
+ """
129
+ def main():
130
+
131
+
132
+
133
+ st.subheader("Your documents")
134
+
135
+ if st.session_state.classify:
136
+ pdf_doc = st.file_uploader("Upload your PDFs here and click on 'Process'", accept_multiple_files=False)
137
+ else:
138
+ pdf_docs = st.file_uploader("Upload your PDFs here and click on 'Process'", accept_multiple_files=True)
139
+ filenames = [file.name for file in pdf_docs if file is not None]
140
+ if st.button("Process"):
141
+ with st.spinner("Processing"):
142
+ if st.session_state.classify:
143
+ # THE CLASSIFICATION APP
144
+ st.write("Classifying")
145
+ plain_text_doc = ingest(pdf_doc.name)
146
+ classification_result = generate_metadata(plain_text_doc)
147
+ st.write(classification_result)
148
+ else:
149
+ # NORMAL RAG
150
+ loaded_vec_store = None
151
+ for filename in filenames:
152
+ if ".pkl" in filename:
153
+ file_path = os.path.join('vectorstore', filename)
154
+ with open(file_path, 'rb') as f:
155
+ loaded_vec_store = pickle.load(f)
156
+ raw_text = get_pdf_text(pdf_docs)
157
+ text_chunks = get_text_chunks(raw_text)
158
+ vec = get_vectorstore(text_chunks)
159
+ if loaded_vec_store:
160
+ vec.merge_from(loaded_vec_store)
161
+ st.warning("loaded vectorstore")
162
+ if "vectorstore" in st.session_state:
163
+ vec.merge_from(st.session_state.vectorstore)
164
+ st.warning("merged to existing")
165
+ st.session_state.vectorstore = vec
166
+ st.session_state.conversation = get_conversation_chain(vec)
167
+ st.success("data loaded")
168
+
169
+ if "conversation" not in st.session_state:
170
+ st.session_state.conversation = None
171
+ if "chat_history" not in st.session_state:
172
+ st.session_state.chat_history = None
173
+
174
+ user_question = st.text_input("Ask a question about your documents:")
175
+ if user_question:
176
+ handle_userinput(user_question)
177
+ with st.sidebar:
178
+ st.subheader("Classification instructions")
179
+ classifier_docs = st.file_uploader("Upload your instructions here and click on 'Process'",
180
+ accept_multiple_files=True)
181
+ filenames = [file.name for file in classifier_docs if file is not None]
182
+
183
+ if st.button("Process Classification"):
184
+ st.session_state.classify = True
185
+ with st.spinner("Processing"):
186
+ st.warning("set classify")
187
+ time.sleep(3)
188
+
189
+ if st.button("Save Embeddings"):
190
+ if "vectorstore" in st.session_state:
191
+ safe_vec_store()
192
+ # st.session_state.vectorstore.save_local("faiss_index")
193
+ st.sidebar.success("saved")
194
+ else:
195
+ st.sidebar.warning("No embeddings to save. Please process documents first.")
196
+
197
+ if st.button("Load Embeddings"):
198
+ st.warning("this function is not in use, just upload the vectorstore")
199
+ """
200
+
201
+
202
+ def main():
203
+
204
+ st.set_page_config(page_title="Doc Verify RAG", page_icon=":mag:")
205
+ st.write('Anomaly detection for document metadata', unsafe_allow_html=True)
206
+ st.header("Doc Verify RAG :mag:")
207
+
208
+ def set_pw():
209
+ st.session_state.openai_api_key = True
210
+
211
+ if "openai_api_key" not in st.session_state:
212
+ st.session_state.openai_api_key = False
213
+ if "openai_org" not in st.session_state:
214
+ st.session_state.openai_org = False
215
+ if "classify" not in st.session_state:
216
+ st.session_state.classify = False
217
+
218
+ col1, col2 = st.columns(2)
219
+ with col1:
220
+ uploaded_file = st.file_uploader("Choose a PDF file", type=["pdf", "txt"])
221
+
222
+ if uploaded_file is not None:
223
+ try:
224
+ with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(uploaded_file.name)[1]) as tmp:
225
+ tmp.write(uploaded_file.read())
226
+ file_path = tmp.name
227
+ st.write(f'Created temporary file {file_path}')
228
+
229
+ docs = ingest(file_path)
230
+ st.write('## Querying Together.ai API')
231
+ metadata = generate_metadata(docs)
232
+ st.write(f'## Metadata Generated by {MODEL_NAME}')
233
+ st.write(metadata)
234
+
235
+ # Clean up the temporary file
236
+ os.remove(file_path)
237
+
238
+ except Exception as e:
239
+ st.error(f'Error: {e}')
240
+ with col2:
241
+ OPENAI_API_KEY = st.text_input("OPENAI API KEY:", type="password",
242
+ disabled=st.session_state.openai_api_key, on_change=set_pw)
243
+ classification = st.file_uploader("upload the metadata", type=["csv", "txt"])
244
+
245
+
246
+ if __name__ == '__main__':
247
+ main()
backend/generate_metadata.py CHANGED
@@ -1,4 +1,5 @@
1
  import os
 
2
  import argparse
3
  import json
4
  import openai
@@ -12,13 +13,13 @@ from langchain_text_splitters import RecursiveCharacterTextSplitter
12
  load_dotenv()
13
 
14
 
15
- def ingest(file_path):
16
- extension = file_path.split('.')[-1]
17
- ext = extension.lower()
18
- if ext == 'pdf':
19
- loader = UnstructuredPDFLoader(file_path)
20
- elif ext == 'txt':
21
- loader = TextLoader(file_path)
22
  else:
23
  raise NotImplementedError('Only .txt or .pdf files are supported')
24
 
@@ -29,7 +30,7 @@ def ingest(file_path):
29
  "\n\n",
30
  "\n",
31
  " ",
32
- ",",
33
  "\uff0c", # Fullwidth comma
34
  "\u3001", # Ideographic comma
35
  "\uff0e", # Fullwidth full stop
 
1
  import os
2
+ import io
3
  import argparse
4
  import json
5
  import openai
 
13
  load_dotenv()
14
 
15
 
16
+ import io
17
+
18
+ def ingest(file_obj, file_ext='pdf'):
19
+ if file_ext == 'pdf':
20
+ loader = UnstructuredPDFLoader(file_obj)
21
+ elif file_ext == 'txt':
22
+ loader = TextLoader(file_obj)
23
  else:
24
  raise NotImplementedError('Only .txt or .pdf files are supported')
25
 
 
30
  "\n\n",
31
  "\n",
32
  " ",
33
+ ",",
34
  "\uff0c", # Fullwidth comma
35
  "\u3001", # Ideographic comma
36
  "\uff0e", # Fullwidth full stop
flake.nix CHANGED
@@ -14,6 +14,9 @@
14
  devShells.${system}.default = pkgs.mkShell {
15
  packages = [
16
  (pkgs.python311.withPackages (python-pkgs: [
 
 
 
17
  python-pkgs.numpy
18
  python-pkgs.pandas
19
  python-pkgs.scipy
@@ -23,15 +26,20 @@
23
  python-pkgs.langchain
24
  python-pkgs.langchain-text-splitters
25
  python-pkgs.unstructured
 
 
 
 
 
 
 
 
26
  python-pkgs.openai
27
  python-pkgs.pydantic
28
  python-pkgs.python-dotenv
29
  python-pkgs.configargparse
30
  python-pkgs.streamlit
31
- python-pkgs.pip
32
  python-pkgs.lark
33
- python-pkgs.jupyter
34
- python-pkgs.notebook
35
  python-pkgs.sentence-transformers
36
  pkgs.unstructured-api
37
  ]))
 
14
  devShells.${system}.default = pkgs.mkShell {
15
  packages = [
16
  (pkgs.python311.withPackages (python-pkgs: [
17
+ python-pkgs.pip # VsCode starts
18
+ python-pkgs.jupyter
19
+ python-pkgs.notebook # VsCode ends
20
  python-pkgs.numpy
21
  python-pkgs.pandas
22
  python-pkgs.scipy
 
26
  python-pkgs.langchain
27
  python-pkgs.langchain-text-splitters
28
  python-pkgs.unstructured
29
+ python-pkgs.wrapt # unstructured[local-inference] starts
30
+ python-pkgs.iso-639
31
+ python-pkgs.emoji
32
+ python-pkgs.pillow-heif
33
+ python-pkgs.magic
34
+ python-pkgs.poppler-qt5
35
+ python-pkgs.pytesseract
36
+ python-pkgs.langdetect # unstructured[local-inference] ends
37
  python-pkgs.openai
38
  python-pkgs.pydantic
39
  python-pkgs.python-dotenv
40
  python-pkgs.configargparse
41
  python-pkgs.streamlit
 
42
  python-pkgs.lark
 
 
43
  python-pkgs.sentence-transformers
44
  pkgs.unstructured-api
45
  ]))