elia-waefler commited on
Commit
aac6922
1 Parent(s): e6fff0b

new file: salga's HF app + some functionality

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